私は次のチュートリアル、Android開発者ガイドを通じてGCMを学んでいます。「アプリケーションはサービスを開始する前にウェイクロックを取得する必要があります。そうしないと、サービスを開始する前にデバイスをスリープ状態にする可能性があります。」という行があります。
サンプルコードでは、最初に受信者がメッセージを受信し、次に、の独自の実装をトリガーしますIntentService
。コードは次のとおりです。
私の質問は、なぜこれWakeLock
をIntentService
クラスで取得するのにクラスでは取得しないのかということReceiver
です。
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();
}
}
}
}