I am learning GCM through the following tutorial, Android Developer Guide. There is such line "your application must acquire a wake lock before starting the service—otherwise the device could be put to sleep before the service is started."
In the example codes, first the receiver receive messages and then trigger your own implementation of IntentService
, the codes are as follow.
My question is why we obtain this WakeLock
in IntentService
class but not in the Receiver
class?
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public final void onReceive(Context context, Intent intent) {
MyIntentService.runIntentInService(context, intent);
setResult(Activity.RESULT_OK, null, null);
}
}
public class MyIntentService extends IntentService {
private static PowerManager.WakeLock sWakeLock;
private static final Object LOCK = MyIntentService.class;
static void runIntentInService(Context context, Intent intent) {
synchronized(LOCK) {
if (sWakeLock == null) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_wakelock");
}
}
sWakeLock.acquire();
intent.setClassName(context, MyIntentService.class.getName());
context.startService(intent);
}
@Override
public final void onHandleIntent(Intent intent) {
try {
String action = intent.getAction();
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
handleRegistration(intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(intent);
}
} finally {
synchronized(LOCK) {
sWakeLock.release();
}
}
}
}
The wakelock is for the Service. When you are done with wakelock object, you have to release the object, that's why.