Android通知栏前台服务的实现

  


  

  

前台服务是那些被认为用户知道且在系统内存不足的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在运行(持续)标题之下,这就意味着通知只有在这个服务被终止或从前台主动移除通知后才能被解除。

  

最常见的表现形式就是音乐播放服务,应用程序后台运行时,用户可以通过通知栏,知道当前播放内容,并进行暂停,继续,切歌等相关操作。

  


  

  

后台运行服务的系统优先级相对较低,当系统内存不足时,在后台运行的服务就有可能被回收,为了保持后台服务的正常运行及相关操作,可以选择将需要保持运行的服务设置为前台服务,从而使应用长时间处于后台或者关闭(进程未被清理)时,服务能够保持工作。

  


  

  

创建服务内容,如下(四大组件不要忘记清单文件进行注册,否则启动会找不到服务);
  

        公开课ForegroundService延伸服务{      私有静态最终字符串标签=ForegroundService.class.getSimpleName ();      @Override   公共空间>/* *   *创建服务通知   */私人通知createForegroundNotification () {   NotificationManager NotificationManager=(NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);//唯一的通知通道的id。   字符串notificationChannelId=皀otification_channel_id_01”;//Android8.0以上的系统,新建消息通道   如果(Build.VERSION。SDK_INT祝辞=Build.VERSION_CODES.O) {//用户可见的通道名称   字符串channelName=扒疤ǚ裢ㄖ?//通道的重要程度   int重要性=NotificationManager.IMPORTANCE_HIGH;   NotificationChannel NotificationChannel=new NotificationChannel (notificationChannelId channelName,重要性);   notificationChannel。setDescription(“频道描述”);//LED灯   notificationChannel.enableLights(真正的);   notificationChannel.setLightColor (Color.RED);//震动   notificationChannel。setVibrationPattern(新长[]{0,1000,500,1000});   notificationChannel.enableVibration(真正的);   如果(notificationManager !=null) {   notificationManager.createNotificationChannel (notificationChannel);   }   }      NotificationCompat。新NotificationCompat Builder构建器=9菇ㄆ?这,notificationChannelId);//通知小图标   builder.setSmallIcon (R.drawable.ic_launcher);//通知标题   builder.setContentTitle (“ContentTitle”);//通知内容   builder.setContentText (“ContentText”);//设定通知显示的时间   builder.setWhen (System.currentTimeMillis ());//设定启动的内容   意图activityIntent=new意图(这个,NotificationActivity.class);   PendingIntent PendingIntent=PendingIntent。getActivity(1,这activityIntent PendingIntent.FLAG_UPDATE_CURRENT);   builder.setContentIntent (pendingIntent);//创建通知并返回   返回builder.build ();   }      之前      

启动服务时,创建通知:
  

        @Override   公共空间>   @Override   公共空间>   @Override   公共int>   & lt; uses-permission android: name=" android.permission。FOREGROUND_SERVICE”/比;   之前      

服务的启动和停止
  

     //启动服务   如果(! ForegroundService.serviceIsLive) {//Android 8.0使用startForegroundService在前台启动新服务   mForegroundService=new意图(这个,ForegroundService.class);   mForegroundService。putExtra(“前景”,“这是前台服务。”);   如果(Build.VERSION。SDK_INT祝辞=Build.VERSION_CODES.O) {   startForegroundService (mForegroundService);   其他}{   startService (mForegroundService);   }   其他}{   吐司。makeText(这个,”前台服务正在运行中……”Toast.LENGTH_SHORT),告诉();   }   之前         //停止服务   mForegroundService=new意图(这个,ForegroundService.class);   stopService (mForegroundService);   之前      

关于前台服务的介绍及使用就到这里了,相关使用已上传至Github开发记录,欢迎点击查阅及明星,我也会继续补充其它有用的知识及例子在项目上。

  

到此这篇关于Android通知栏前台服务的实现的文章就介绍到这了,更多相关Android通知栏前台内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

Android通知栏前台服务的实现