【问题标题】:Android toast doesn't show on UI for some reason由于某种原因,Android toast 未在 UI 上显示
【发布时间】:2012-06-01 20:34:36
【问题描述】:

我正在做与这里讨论的类似的事情: Android BroadcastReceiver within 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 线程上?为什么我会观察到这种行为?

【问题讨论】:

    标签: java android broadcastreceiver


    【解决方案1】:

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

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

    当然,你也可以:

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

    【讨论】:

    • @katit:重点是你缺少的show()。
    【解决方案2】:
    Toast.makeText(BaseActivity.this, "received", Toast.LENGTH_LONG);
    

    您正在制作Toast,但您没有显示它。你需要调用show就可以了,像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 2012-08-19
      相关资源
      最近更新 更多