0

我正在做类似于这里讨论的内容: Android BroadcastReceiver inside Activity

我有运行有或没有 UI 的应用程序。当屏幕关闭时,它只是在后台工作。当 UI 开启且可见时 - 我想让用户知道刚刚发生了一些事情。

因此,我按照上面主题中的示例并在我的Activity. 我注册onResume和注销onPause

private BroadcastReceiver uiNeedToBeUpdatedReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            // TODO Auto-generated method stub
            Toast.makeText(BaseActivity.this, "received", Toast.LENGTH_LONG);
        }
    };

@Override
    protected void onPause()
    {
        Log.d(LOG_TAG, "onPause");
        super.onPause();

        // TODO: Unregister broadcast receiver
        unregisterReceiver(uiNeedToBeUpdatedReceiver);
    }

@Override
    protected void onResume()
    {
        Log.d(LOG_TAG, "onResume");
        super.onResume();

        // TODO: Register for broadcast events
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.my.uineedtobeupdated");
        registerReceiver(uiNeedToBeUpdatedReceiver, filter);

在我在后台运行的内部我AsyncTask这样做:

// Send broadcast - if UI active it will see it:
        Intent broadcast = new Intent();
        broadcast.setAction("com.my.uineedtobeupdated");
        MyApplication.Me.sendBroadcast(broadcast);

好吧,一切正常。我收到广播,我在调试器中看到我正在运行 Toast 应该显示的行。但我没有看到任何吐司弹出。

是线程问题吗?我虽然如果我收到广播它应该在 UI 线程上?为什么我会观察到这种行为?

4

2 回答 2

11

不仅要创建 Toast,而且要实际显示它。简单的方法:

Toast.makeText(BaseActivity.this, "received", Toast.LENGTH_LONG).show();

当然,您也可以:

Toast myToast = Toast.makeText(BaseActivity.this, "received", Toast.LENGTH_LONG);
myToast.show();
于 2012-06-01T20:36:21.133 回答
2
Toast.makeText(BaseActivity.this, "received", Toast.LENGTH_LONG);

你正在制作一个Toast,但你没有展示它。您需要调用show它,如下所示:

Toast.makeText(BaseActivity.this, "received", Toast.LENGTH_LONG).show();
于 2012-06-01T20:36:52.423 回答