方法一:
利用onStartCommand方法中,返回START_STICKY。
public int onStartCommand(Intent intent, int flags, int startId) {
//intent - 启动时,启动组件传递过来的intent
//flags - 启动请求时否额外参数,默认是0
// startId - 指明当前服务的唯一ID,与stopSelfResult(startId)配合使用,可以更安全地更加ID停止服务
flags=START_STICKY;
return super.onStartCommand(intent, flags, startId);
}
返回值 | 含义 | 适用场景 |
---|---|---|
START_STICKY | 当Service因内存不足而被系统kill后,一段时间后内存再次空闲时,系统将会尝试重新创建Service,一旦创建成功后将回调onStartCommand方法,但其中的Intent将使null,也就是onStartCommand方法虽然会只下但是获取不到Intent信息 | 这个状态下比较适用于任意时刻开始,结束的服务(如音乐播放器) |
STRAT_NOT_STICKY | 当Service因内存不足而被系统kill后,即使系统内存再次空闲时,系统也不会尝试去重新创建Service。除非程序中再次回调startService启动此Service。 | 某个Servicce执行的工作被中断几次无关紧要 |
START_REDELIVER_INTENT | 当Service因内存不足而被系统杀死后,则会重新创建服务,并通过传递给服务的最后一个Intent调用onStartCommand(),任何挂起Intent均依次传递。与START_STICKY不同的是,START_REDELIVER_STICKY传递的Intent将使非空,是最后一次调用startService中的intent | 使用于主动执行应该立即恢复的作业。 |
方法二
在AndroidMainifest中通过android:priority提升Service优先级,在AndroidMainfest.xml文件中对于intent-filter可以通过android:priority="1000"这个属性设置最高优先级,1000是最高值,如果数字越小则优先级越低,同时适用广播。
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="com.service.test"/>
</intent-filter>
</service>
方法三
onDestroy方法里重启Service
service+broadcast方式,就是当Service调用onDestory的时候,发送一个自定义的广播,当收到广播的时候,重新启动service;或者startService()重新打开服务。
方法四
使用startForeground将service放到前台状态,提升service进程优先级,Android进程是托管的,但系统进程空间紧张的时候,就会按照优先级自动进行进程的回收。Android将进程分为6个等级,它们按优先级顺序高到低依次是:前台进程,可见进程,服务进程,后台进程,空进程。当Service运行在低内存的环境时,就会kill掉一些存在的进程。因此进程的优先级很重要,可以使用startForeground将service放到前台状态。这些在低内存时会被kill的几率会低一些。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//添加下列代码将后台service变成前台Service
//构建点击通知后打开MainActivity的Intent对象
Intent notifyIntent=new Intent(this,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notifyIntent,0);
//构建Builder对象
Notification.Builder builder=new Notification.Builder(this);
builder.setContentTitle("前台服务标题");
builder.setContentText("内容");
builder.setSmallIcon(R.drawable.ic_launcher_background);
//设置点击通知后的操作
builder.setContentIntent(pendingIntent);
//将Builder对象转变成普通的notify
Notification notification=builder.build();
//将Service变成前台Service,并在系统的状态显示出来
startForeground(1,notification);
return super.onStartCommand(intent, flags, startId);
}
网友评论