BroadcastReceiver wake lock needed if only AsyncTask is executed?

久未见 提交于 2019-12-23 01:34:16

问题


I have got a class, which extends from BroadcastReceiver and gets called from AlarmManager. In the onReceive method I execute an AsyncTask, which fetches some data from the internet and stores the data in the local database of the application.

Do I need to acquire wakelock with:

@Override
public void onReceive(Context context, Intent intent) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
    mWakeLock.acquire();

    // execute AsyncTask
}

private void asyncTaskDone() {
    mWakeLock.release();
}

in order to stop the CPU from sleeping or is it safe to execute the AsyncTask without a wake lock?


回答1:


I suggest you to read the docs about the receiver lifecycle. What you are trying to do is not good practice, If the onReceive() method returns the process can be killed. Hence your task can't complete the work. Because of this you should start a Service/IntentService to run the task and to keep the process alive.




回答2:


The OnReceive method reference from the BroadcastReceiver doc says :

..you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed)

So you'd better replace your AsyncTask with a service and then call this service from the OnReceive method. Your service will keep running even if the broadcastReceiver get killed.



来源:https://stackoverflow.com/questions/25229685/broadcastreceiver-wake-lock-needed-if-only-asynctask-is-executed

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