I can instantiate an AsyncTask from WakefulBroadcastReceiver (see my motivation for favouring AsyncTask over Service), e.g.,
public abstract class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
new AsyncTask<Void,Void,Void>(){
@Override
protected Void doInBackground(Void... v) {
while (true) {
SystemClock.sleep(7000);
Log.w("", "alive");
}
}
}.execute();
}
}
But is this recommendable? In particular, are there life cycle issues associated with instantiating an AsyncTask from a WakefulBroadcastReceiver? For instance, can my AsyncTask be killed prematurely?
(I know I can wrap the AsyncTask inside a service, but this seems like overkill?)
Answer
Instantiating an AsyncTask from a WakefulBroadcastReceiver is ill-advised, since anything instantiated by a BroadcastReceiver will be considered killable by the system once the onReceive() method returns, i.e., the system may kill AsyncTask. Thanks to corsair992.
See process lifecycle for further details about killable processes.