参考:http://blog.csdn.net/yyingwei/article/details/8509402
http://www.cnblogs.com/ylligang/articles/2665181.html
1. onStartCommand 中返回 START_STICKY
public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; }
2.onDestroy 中重新启动( settings 中stop service会调用service onDestroy方法)
public void onDestroy() { Intent localIntent = new Intent(); localIntent.setClass(this, MyService.class); //销毁时重新启动Service this.startService(localIntent); }
3.提升服务优先级 前台服务
一个已启动的service可以调用startForeground(int, Notification)将service置为foreground状态,调用stopForeground(boolean)将service置为 background状态。 我们会在调用startForeground(int, Notification)传入参数notification,它会在状态栏里显示正在进行的foreground service。background service不会在状态栏里显示。
Notification notification =newNotification(R.drawable.icon, getText(R.string.ticker_text),System.currentTimeMillis());Intent notificationIntent =newIntent(this,ExampleActivity.class);PendingIntent pendingIntent =PendingIntent.getActivity(this,0, notificationIntent,0); notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_message), pendingIntent); startForeground(ONGOING_NOTIFICATION, notification);
在AndroidManifest.xml文件中对于intent-filter可以通过android:priority = "1000"这个属性设置最高优先级
4.broadcastReceiver 启动
开机启动ndroid.intent.action.BOOT_COMPLETED