2012年2月25日土曜日

[Android SDK] Android起動時にサービス等を起動する

Android起動時には"ACTION_REBOOT"インテントが発行されますので、BroadcastReceiverで受け取ることで任意の処理を実行できます。
1.BroadcastReceiverの準備
2.Intent Filterの登録
3.Permissionの登録

1.BroadcastReceiverの準備
参考に下記ように作成します。
package com.runpeta.android.notify;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class RpNotifyReceiver extends BroadcastReceiver {
 private static final String TAG = "RpNotifyReceiver";

 @Override
 public void onReceive(Context context, Intent intent) {
  Log.d(TAG, "onReceive");
  String action = intent.getAction();
  if (action != null) {
   if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
    // システム起動完了時
    Log.d(TAG, "ACTION_BOOT_COMPLETED");
    context.startService(new Intent(context, RpNotifyService.class));
   }
  }
 }
}
2.Intent Filterの登録
AndroidManifest.xmlを開き、BroadcastReceiverのIntent Filterに"ACTION_REBOOT"を登録します。

3.Permissionの登録
AndroidManifest.xmlを開き、Permissionに"RECEIVE_BOOT_COMPLETED"を登録します。

以上で、Android起動時にBroadcastReceiverのonReceiveが呼ばれるようになります。

0 件のコメント:

コメントを投稿