Niklas
Niklas

Reputation: 25413

BroadcastReceiver wake lock needed if only AsyncTask is executed?

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?

Upvotes: 1

Views: 1492

Answers (2)

Steve Benett
Steve Benett

Reputation: 12933

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.

Upvotes: 1

sosta
sosta

Reputation: 102

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.

Upvotes: 2

Related Questions