Is instantiating an AsyncTask from a WakefulBroadcastReceiver recommended?

一曲冷凌霜 提交于 2019-12-30 11:01:42

问题


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.

来源:https://stackoverflow.com/questions/25174226/is-instantiating-an-asynctask-from-a-wakefulbroadcastreceiver-recommended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!