0

I'm doing similar to what discussed here: Android BroadcastReceiver within Activity

I have application that runs with or without UI. When screen is off it's just working on background. When UI is on and visible - I would like to let user know that something just happened.

So, I followed samples in topic above and registered broadcast receiver on my Activity. I register onResume and unregister on 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);

Inside my AsyncTask that runs on background I do this:

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

Well, everyting works. I get broadcasts and I see in my debugger that I'm hitting line where Toast should show. But I don't see any toast popping up.

Is that threading issue? I though if I receive broadcast it shuld be on UI thread? Why do I observe this behavior?

Community
  • 1
  • 1
katit
  • 17,375
  • 35
  • 128
  • 256

2 Answers2

11

It's important not only to create the Toast, but actually display it. The easy way:

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

You can also, of course:

Toast myToast = Toast.makeText(BaseActivity.this, "received", Toast.LENGTH_LONG);
myToast.show();
Vicente Plata
  • 3,370
  • 1
  • 19
  • 26
2
Toast.makeText(BaseActivity.this, "received", Toast.LENGTH_LONG);

You are making a Toast, but you are not showing it. You need to call show on it, like this:

Toast.makeText(BaseActivity.this, "received", Toast.LENGTH_LONG).show();
K-ballo
  • 80,396
  • 20
  • 159
  • 169