android开机自启动service

来源:互联网 发布:莫斯科不相信眼泪知乎 编辑:程序博客网 时间:2024/06/09 16:06

开机通过监听广播去进行相关的操作:

首先在广播类中代码如下:

public class BootBroadcastReceiver extends BroadcastReceiver {// 重写onReceive的方法@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stub// Intent.ACTION_BOOT_COMPLETED监听开机自启动if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {// 启动serviceIntent intent1 = new Intent();intent1.setClass(context, MyService.class);intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 启动服务选项!!!!!context.startService(intent1);}}}
Myservice.class中的代码:

public class MyService extends Service {@Overridepublic IBinder onBind(Intent intned) {// TODO Auto-generated method stubreturn null;}public void onCreate() {super.onCreate();Log.v("=============", "*******This is myService :onCreate() ********");}public int onStartCommand(Intent intent, int flags, int startId) {Log.v("=============", "******This is myService : onStart()*******");flags = START_STICKY;super.onStartCommand(intent, flags, startId);Intent mintent = new Intent(this, AlarmReceiver.class);PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, mintent, 0);long startTime = SystemClock.elapsedRealtime();// 开始时间AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);// 每10秒发送一个广播,时间到了将发送pIntent这个广播,在alarmReceiver中接受广播alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,startTime, 10 * 1000, pIntent);// service被第三方的软件kill之后就可以通过START_STICKY参数重启。。return super.onStartCommand(intent, flags, startId);}@SuppressWarnings("deprecation")public void onStart(Intent intent, int startId) {// 再次动态注册广播IntentFilter localIntentFilter = new IntentFilter("android.intent.action.USER_PRESENT");localIntentFilter.setPriority(Integer.MAX_VALUE);// 整形最大值BootBroadcastReceiver searchReceiver = new BootBroadcastReceiver();registerReceiver(searchReceiver, localIntentFilter);super.onStart(intent, startId);}public void onDestroy() {// 在onDestroy中再次启动service,当service直接被调用销毁停止service的时候,此方法可以再次启动service,保证service可以一直在后台运行。Log.v("==============", "*******This is myService :onDestroy()********");Intent localIntent = new Intent();localIntent.setClass(this, MyService.class);this.startService(localIntent);super.onDestroy();}}


1 0