Is blocking the BroadcastReceiver alarm necessary if only AsyncTask is running?

I have a class that extends from BroadcastReceiver

and is called from AlarmManager

. In the method onReceive

I am running AsyncTask

, which fetches some data from the internet and stores the data in the local application database.

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();
}

      

to stop the processor from sleeping or is it safe to execute AsyncTask

without blocking the trail?

+1


source to share


2 answers


I suggest you read the docs about the receiver lifecycle . What you are trying to do is not good practice. If the onReceive () method returns a process, it might be killed. Hence, your task cannot complete. Because of this, you must start Service / IntentService to start the task and save the process.



+1


source


The OnReceive reference method from the BroadcastReceiver doc says:

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



So you better replace your AsyncTask service and then call that service from the OnReceive method. Your service will continue to work even if the broadcast of the radio transmitter is killed.

+2


source







All Articles