Wednesday, March 28, 2012

Is starting a thread in broadcast receiver a good idea in Android?


Usually, the purpose of using thread is to perform a heavy task in the background without interrupting any UI activity. In addition, the onReceive() is running on UI thread so any long time operation may cause ANR (application not responding). Thus, most developers may think of using a thread in the onReceive() to perform long time operation to avoid the ANR issue. However, using a thread in onReceive() may not be a good idea neither.
As we already know that the broadcast receiver life cycle is very short, and it is destroyed shortly after onReceive() end. Thus, putting a thread in onReceive() will cause it to be in a state that not belong to anything and it may be easily killed which end up cause unexpected behavior. A better way to handle long time operation in onReceive() is to start an Intent Service instead (NOT bind service). See an example below on how to start a service from onReceive().
public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // start an intent service
        context.startService(new Intent(this, MyService.class));
    }
}
public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // do something here
        return START_STICKY;
    }
}

No comments:

Post a Comment