Android 实现监听开机启动开启后台服务,并实现自动重启。

时间:2021-05-16 04:44:55


1.创建广播监听器,继承BroadcastReceiver

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootBroadcastReceiver extends BroadcastReceiver {

static final String ACTION = "android.intent.action.BOOT_COMPLETED";

@Override
public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals(ACTION)) {
Intent service = new Intent(context, BootService.class);
context.startService(service);
}
}
}
2.在AndroidManifest.xml中注册广播接收器,并设置action为android.intent.action.BOOT_COMPLETED,这样项目就能监听开机事件。

 

       <receiver android:name="com.huahu.bootstart.BootBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>


3.创建 BootService服务,重写onStartCommand方法,设置flags,这样当服务关闭时,能够自动重启服务。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
flags = START_STICKY;
return super.onStartCommand(intent, flags, startId);
}