简体   繁体   中英

Android BroadCastReceiver lagging application

I have an issue with BroadcastReceiver which I'm using in my activities. I'm actually doing this :

In onCreate() :

        receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("finish")) {
             // some code
            }               
        }
    };
    registerReceiver(receiver, intentFilter);

and in onResume() and onPause() I'm doing this :

@Override
public void onResume(){
    super.onResume();
    MyCollectionList.this.registerReceiver(receiver, intentFilter);
}

@Override
public void onPause(){
    super.onPause();
    MyCollectionList.this.unregisterReceiver(receiver);
}

where intentFilter is :

IntentFilter intentFilter = new IntentFilter("finish");

and when I do this in 6 activities where I need to add this broadcast receiver my application start lagging and getting slow than before.

So is there any other better way to watch for intent filters without slowing the app/or best way in my situation.

Thanks in advance!

Instead of registering your receiver with Activity's context, register it with your application's context in your 1st activity as below:

getApplication().registerReceiver(receiver, intentFilter);

This way even if your activities goes into 'pause' state, your receiver will remain active as your application will keep on running in the background.

Hope this helps.

  • dont register your broadcast receiver in onCreate. Registering it in onResume and unregistering in onPause is safe and enough in your case
  • you must be doing some heavy load processing in your receiver method. Android offers a 10sec window to perform what ever you want in your receiver otherwise it will declare it as ANR
  • To avoid lag, load your processing on a new worker thread

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