安卓开机启动service后台运行
Android开机启动时会发送一个广播android.intent.action.BOOT_COMPLETED,捕捉到这个广播,然后可以进行相应的操作,比如:通过捕捉开机广播启动Activity,或者Service。
1、新建BootBroadcastReceiver类,继承BroadcastReceiver。
public class BootBroadcastReceiver extends BroadcastReceiver {
private final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
if (ACTION_BOOT.equals(intent.getAction())) {
System.out.println("boot receiver start......\n");
context.startService(new Intent(context, CollService.class));
}
}
}
2、AndroidManifest配置
<receiver android:name="com.example.BootBroadcastReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
<intent-filter android:priority="1000">
<action android:name="android.intent.action.MEDIA_MOUNTED"/>
<action android:name="android.intent.action.MEDIA_EJECT"/>
<data android:scheme="file"/>
</intent-filter>
</receiver>