Android 前台服务

普通的Service容易被系统回收,而前台服务系统优先级更高,不易被回收。下面介绍下前台服务的几种实现方法。


1. 提高Service的优先级:
<!-- 为防止Service被系统回收,可以尝试通过提高服务的优先级解决,1000是最高优先级,数字越小,优先级越低 -->  android:priority="1000"


2.把service写成系统服务,将不会被回收:
在Manifest.xml文件中设置persistent属性为true,则可使该服务免受out-of-memory killer的影响。但是这种做法一定要谨慎,系统服务太多将严重影响系统的整体运行效率。


3.将服务改成前台服务foreground service:
重写onStartCommand方法,使用StartForeground(int,Notification)方法来启动service。  
注:一般前台服务会在状态栏显示一个通知,最典型的应用就是音乐播放器,只要在播放状态下,就算休眠也不会被杀,如果不想显示通知,只要把参数里的int设为0即可。
同时,对于通过startForeground启动的service,onDestory方法中需要通过stopForeground(true)来取消前台运行状态。
这个方案也是本文目前准备详细介绍的。


4.利用Android的系统广播
利用ANDROID的系统广播检查Service的运行状态,如果被杀掉,就再起来,系统广播是Intent.ACTION_TIME_TICK,这个广播每分钟发送一次,我们可以每分钟检查一次Service的运行状态,如果已经被结束了,就重新启动Service。

这里介绍下第3种方法

在Service的onStartCommand中添加如下代码:
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {  
    Log.d(TAG, "onStartCommand()");  
    // 在API11之后构建Notification的方式  
    Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器

  Intent nfIntent = new Intent(this, MainActivity.class);
  builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent

    .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.mipmap.ic_large)) // 设置下拉列表中的图标(大图标)
    .setContentTitle("下拉列表中的Title") // 设置下拉列表里的标题
    .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标

    .setContentText("要显示的内容") // 设置上下文内容
    .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
    Notification notification = builder.build(); // 获取构建好的Notification 
   notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音}

在完成Notification通知消息的构建后,在Service的onStartCommand中可以使用startForeground方法来让Android服务运行在前台。

// 参数一:唯一的通知标识;参数二:通知消息。startForeground(0, notification);// 开始前台服务

如果需要停止前台服务,可以使用stopForeground来停止正在运行的前台服务。

@Overridepublic void onDestroy() {
  Log.d(TAG, "onDestroy()");
  stopForeground(true);// 停止前台服务--参数:表示是否移除之前的通知

  super.onDestroy();
}
 

猜你喜欢

转载自blog.csdn.net/qq_25017839/article/details/89633961