廣播代碼如下:
public class BootBroadcastReceiver extends BroadcastReceiver{
private String action = "android.intent.action.BOOT_COMPLETED";
private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
if(intent.getAction().equals(action))
{
Log.d("BootBroadcastReceiver", "BroadcastReceiver onReceive ");
//在這裏啓動服務
Intent service = new Intent(context,MyService.class);
mContext.startService(service);
}
}
}
service測試代碼:
public class MyService extends Service {
public static final String TAG = "MyService";
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() executed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() executed");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
進行簡單配置即完成操作:
<service android:name="MyService"></service>
<receiver android:name="BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>