广播
public class BootReceiver extends BroadcastReceiver {
public void onReceive(Context ctx, Intent intent) {
Log.d("BootReceiver", "system boot completed");
Intent s = new Intent(ctx, MyService.class);
ctx.startService(s);
}
}
服务
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("======", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
}
广播与服务的配置
<receiver android:name=".BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<service android:name=".MyService" >
自启动权限配置
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />