最終更新:
moonlight_aska 2013年09月01日(日) 12:29:16履歴
端末起動時に自動的にサービスを起動するには, 起動時完了時に ブロードキャストされるブロードキャストアクション"ACTION_BOOT_COMPLETED"を利用する.

- BootReceiver.java
- アクションがIntent.ACTION_BOOT_COMPLETEDか否か判定する.
- サービスを指定して, インテントのインスタンスを取得する.
- startServiceメソッドで, サービスを起動する.
package com.moonlight_aska.android.service06;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
// サービスの起動
Intent service = new Intent(context, TestService.class);
context.startService(service);
}
}
}
- TestService.java
- AndroidManifest.xml
- android:installLocation="internalOnly"を指定する.
- android.permission.RECEIVE_BOOT_COMPLETEDのパーミッションを設定する.
- サービスを登録する.
- ブロードキャストレシーバを登録する.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.moonlight_aska.android.service06"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="internalOnly"
>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<!-- サービス登録 -->
<service android:name="TestService" /></service>
<!-- レシーバ登録 -->
<receiver android:name="BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
- 動作例
- 端末:SHARP SH-03C / Android 2.2

コメントをかく