Android, use/don wake locks when receiving a message from GCM and want to do work outside the onReceive, if the device is in deep sleep mode?

StackOverflow https://stackoverflow.com/questions/20720514

  •  20-09-2022
  •  | 
  •  

Question

I am developing an application in which I have

  • a Service, that does http requests and writes data to db

  • a receiver declared in manifest, that listens for GCM messages

  • a receiver, declared in code ( in the Service ), used to "talk" to the service

Each time I am receiving a GCM message I want extract the data from the intent, and broadcast it to the service. The service will then query an http server, get the response and insert data into db.

Now, I am afraid that, if the phone is in deep sleep, the phone will be wake just until the GCM onReceive executes and not until my Service does work. Here is my GCM receiver onReceive:

@Override
public void onReceive(Context context, Intent intent) {
    String url = extractUrl(intent.getExtras());

    Intent serviceIntent = new Intent(context, MyService.class);
    serviceIntent.setAction(MyService.ACTION_DO_WORK);
    Bundle data = new Bundle();
    data.putString(MyService.URL_KEY, url);
    LocalBroadcastManager.getInstance(context).sendBroadcast(serviceIntent);
} 

I have the feeling I have to use a CPU lock ( correct me if I'm mistakeing )

Where should I acquire the partial wake lock? Should I acquire it here and then release it in my Service, after he does the work? ( is it safe to acquire the lock in one place and release it in other one )

Thanks,

Was it helpful?

Solution

Where should I acquire the partial wake lock?

Ideally, you let some tested code do that, by using WakefulBroadcastReceiver or my WakefulIntentService.

Both of those will acquire the WakeLock during the call to onReceive() and will arrange to release the WakeLock when your IntentService completes its work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top