简体   繁体   中英

Update the UI of the calling activity or start a new activity when the alarm is triggered from a broadcast receiver

I am writing an alarm code and using a broadcast receiver. I am able to receive the broadcast receiver. but now I want to come back to the calling activity and update the UI of my activity. I am not able to this. I used the following code in my activity but it is never executing that code.

 private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "I am back!!", Toast.LENGTH_LONG).show();
    }
  };


  @Override
    protected void onPause()
    {
        super.onPause();
        unregisterReceiver(myBroadcastReceiver);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter("com.test.Main");
        registerReceiver(myBroadcastReceiver, intentFilter);
    }

in the manifest file I have included the following, here gotAlarm is the broadcast receiver file

   <receiver android:name=".gotAlarm"
        android:enabled="true">
        </receiver>

gotAlarm file is one which gets called from the pending intent of the alarm set

public class gotAlarm extends BroadcastReceiver {
public void onReceive(Context context, Intent intent){
    Toast.makeText(context, "Wake Up!!", Toast.LENGTH_LONG).show();

   }
 }

May be I am missing something very basic. please help.

Two things:

  1. If you dynamically register the receiver via Context.registerReceiver() then you won't receive broadcasts when Activity is paused (or stopped or not-running). If you need to receive broadcasts even when Activity is paused then create a top-level BroadcastReceiver class (as opposed to your inner class) and use <receiver> to register it.

  2. BroadcastReceiver lifecycle docs state that BroadcastReceiver object is alive only during processing of onReceive() . You can not do any async tasks like showing dialogs, etc.. In your case (Activities might not be running and you receive a broadcast) you should use NotificationManager to notify user something happened.

I have dropped this way and I am starting a new activity on receiving broadcast. And I am sending information data from calling activity to broadcast and from broadcast to next activity. This has served the purpose.

Did you register your BroadcastReceiver (you can do this in the 'onResume'-method of your Activity)? Also, you should unregister your BroadcastReceiver in the 'onPause'-method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM