创建前台 Service

 Service在后台运行时,如果系统内存内存不足时,就有可能会回收掉后台运行的Service,

 如果想要Service一直运行,而不会因为内存不足时被回收,就可以使用前台Service;

 前台Service和普通Service的区别:

 前台Service会有个图标显示在系统的状态栏,下拉状态栏会有更详细的信息

 前台Service的创建

  在onCreate()方法中:

  1、创建一个Notification对象。并设置参数;

  2、调用startForeground(1,notification); //启动为前台Service



public void onCreate() { super.onCreate(); Intent intent = new Intent(this,MainActivity.class); PendingIntent pend = PendingIntent.getActivity(this,0, intent,0); //创建Notification NotificationCompat.Builder nc = new Builder(this); nc.setContentTitle("前台Service"); nc.setContentText("有新消息"); nc.setSmallIcon(R.drawable.ic_launcher); nc.setContentIntent(pend); Notification notifivatiion = nc.build(); //开启模式为 前台Service startForeground(1,notifivatiion); }

  

 

原文地址:https://www.cnblogs.com/pbq-dream/p/5393195.html