Inform Activity from a BroadcastReceiver ONLY if it is in the foreground

后端 未结 2 611
灰色年华
灰色年华 2020-11-30 20:35

Maybe it\'s easy, but I couldn\'t really figure this out right so far... I got a BroadcastReceiver waiting to get triggered by the AlarmMangager - this works fi

相关标签:
2条回答
  • 2020-11-30 21:20

    So this is almost Bino's answer, but: instead of moving the receiver into the activity, use two receivers, with different Intents. The first one is your original alarm Intent, with a receiver registered in the manifest as you already have, and then that receiver sends a second broadcast intent, which is handled by a receiver registered by the activity as Bino says.

    I've done this in my own timer project, on github. Here are the alarm receiver and the requery receiver. Hope that helps.

    0 讨论(0)
  • 2020-11-30 21:42

    I believe that you're familiar with AlarmManager now (creating a new Alarm, register a receiver...) so I will not talk about that. Just give you a solution for your question.

    Instead of registering a BroadcastReceiver in a class file and in manifest, you only create a new BroadcastReceiver in your activity, and then, register it in onResume method, and unregister it in onPause method, sth like this in your activity:

    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          //do something       
        }
    };
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction("your alarm action");
        ...
    }
    
    @Override
    protected void onResume() {
    registerReceiver(mIntentReceiver, mIntentFilter);
        ...
    super.onResume();
    }
    
    @Override
    protected void onPause() {
    unregisterReceiver(mIntentReceiver);
        ...
    super.onPause();
    }
    

    The receiver will only receive the alarm intent when your activity is in foreground :)

    (Sorry if my English is not clear)

    0 讨论(0)
提交回复
热议问题