サービスを起動させる。
package com.android.my.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO 自動生成されたメソッド・スタブ
return null;
}
public void onCreate() {
Log.d("タグ", "onCreate");
}
public void onStart(Intent intent, int StartId) {
super.onStart(intent, StartId);
// stopSelf();
Log.d("タグ", "onStart");
}
public void onDestroy() {
Log.d("タグ", "onDestroy");
}
}
package com.android.my.test;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BootReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.d("タグ", "onReceive");
context.startService(new Intent(context, MyService.class));
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.my.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<service android:name="MyService" >
</service>
<receiver
android:name="BootReciever"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<activity
android:label="@string/app_name"
android:name=".AdnroidServiceTestActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
BOOT_COMPLETEDをReceiveするアプリの場合、
実際にBOOT_COMPLETEDがBroadcastされるのはシステム起動時だけなので、
動作確認はAVDにコマンドプロンプトからamコマンドからインテントを投げて確認する。
E:\soft\android-sdk-windows\platform-tools>adb shell
# am broadcast -a android.intent.action.BOOT_COMPLETED
アクティビティーはプロジェクト作成時に自動的に作成されたのを残しています。
必要ないのでマニフェストのアクティビティー関連の設定を削除して、
アプリの上書きをした場合は動きますが、
アプリを削除して、再インストールした場合は動きません。
0 件のコメント:
コメントを投稿