其实网上很多这样的文章,大多数都是没用的或者只是草率的说一下。
其实要降低被杀死的风险,最好用的方法就是把service设置为前台服务,
startForeground(NOTI_ID, new Notification());
但是这个方法在你使用的时候会有点问题,因为这个方法设置后在4.2 以后的系统里会显示一个通知,如果你是做播放器的应用,可以不在意这个,如果你是做其它应用,那就要去掉这个通知。
去掉这个通知的方法就是在你的service里面写一个内部service来去除通知。
看代码:
package com.servicedemo;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
/**
* Created by laixiang on 2014/9/15.
*/
public class MyService extends Service
{
private static final int NOTI_ID = 4527;
static MyService myService;
@Override
public void onCreate()
{
super.onCreate();
myService = this;
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
flags = START_STICKY;
/**
* 设置为前台服务,降低被系统杀死的概率。
* 对于系统版本小于18的来说,直接设置就行了,因为小于18的android版本设置为前台服务是不会显示空的通知的。
* 而对于大于等于18的android版本,系统连空的通知也会显示,这样的话我们得借助KernelService来去掉那个通知
*/
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2)
{
startForeground(NOTI_ID, new Notification());
}
else
{
startService(new Intent(this, KernelService.class));
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy()
{
super.onDestroy();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2)
{
stopForeground(true);
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2)
{
stopService(new Intent(this, KernelService.class));
}
}
public static class KernelService extends Service
{
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
flags = START_STICKY;
/**
* 去除通知栏
*/
MyService.myService.startForeground(NOTI_ID, new Notification());
startForeground(NOTI_ID, new Notification());
MyService.myService.stopForeground(true);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy()
{
super.onDestroy();
stopForeground(true);
}
}
}
这样的话就能在4.2以上的机型去掉那个前台服务的通知了,也能兼容4.2及4.2以下的机型。android版的QQ也是这样实现。