一、前台服务的简单介绍

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

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

二、为什么使用前台服务

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

三、前台服务的详细使用

  1. 创建服务内容,如下(四大组件不要忘记清单文件进行注册,否则启动会找不到服务);
  1. public class ForegroundService extends Service {
  2. private static final String TAG = ForegroundService.class.getSimpleName();
  3. @Override
  4. public void onCreate() {
  5. super.onCreate();
  6. Log.e(TAG, "onCreate");
  7. }
  8. @Nullable
  9. @Override
  10. public IBinder onBind(Intent intent) {
  11. Log.e(TAG, "onBind");
  12. return null;
  13. }
  14. @Override
  15. public int onStartCommand(Intent intent, int flags, int startId) {
  16. Log.e(TAG, "onStartCommand");
  17. return super.onStartCommand(intent, flags, startId);
  18. }
  19. @Override
  20. public void onDestroy() {
  21. Log.e(TAG, "onDestroy");
  22. super.onDestroy();
  23. }
  24. }
  1. 创建服务通知内容,例如音乐播放,蓝牙设备正在连接等:
  1. /**
  2. * 创建服务通知
  3. */
  4. private Notification createForegroundNotification() {
  5. NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  6. // 唯一的通知通道的id.
  7. String notificationChannelId = "notification_channel_id_01";
  8. // Android8.0以上的系统,新建消息通道
  9. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  10. //用户可见的通道名称
  11. String channelName = "Foreground Service Notification";
  12. //通道的重要程度
  13. int importance = NotificationManager.IMPORTANCE_HIGH;
  14. NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
  15. notificationChannel.setDescription("Channel description");
  16. //LED灯
  17. notificationChannel.enableLights(true);
  18. notificationChannel.setLightColor(Color.RED);
  19. //震动
  20. notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
  21. notificationChannel.enableVibration(true);
  22. if (notificationManager != null) {
  23. notificationManager.createNotificationChannel(notificationChannel);
  24. }
  25. }
  26. NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId);
  27. //通知小图标
  28. builder.setSmallIcon(R.drawable.ic_launcher);
  29. //通知标题
  30. builder.setContentTitle("ContentTitle");
  31. //通知内容
  32. builder.setContentText("ContentText");
  33. //设定通知显示的时间
  34. builder.setWhen(System.currentTimeMillis());
  35. //设定启动的内容
  36. Intent activityIntent = new Intent(this, NotificationActivity.class);
  37. PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
  38. builder.setContentIntent(pendingIntent);
  39. //创建通知并返回
  40. return builder.build();
  41. }
  1. 启动服务时,创建通知:
  1. @Override
  2. public void onCreate() {
  3. super.onCreate();
  4. Log.e(TAG, "onCreate");
  5. // 获取服务通知
  6. Notification notification = createForegroundNotification();
  7. //将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
  8. startForeground(NOTIFICATION_ID, notification);
  9. }
  1. 停止服务时,移除通知:
  1. @Override
  2. public void onDestroy() {
  3. Log.e(TAG, "onDestroy");
  4. // 标记服务关闭
  5. ForegroundService.serviceIsLive = false;
  6. // 移除通知
  7. stopForeground(true);
  8. super.onDestroy();
  9. }
  1. 判断服务是否启动及获取传递信息:
  1. @Override
  2. public int onStartCommand(Intent intent, int flags, int startId) {
  3. Log.e(TAG, "onStartCommand");
  4. // 标记服务启动
  5. ForegroundService.serviceIsLive = true;
  6. // 数据获取
  7. String data = intent.getStringExtra("Foreground");
  8. Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
  9. return super.onStartCommand(intent, flags, startId);
  10. }

以上就是前台服务的创建过程,相关注释已经很明白了,具体使用可以查看文末的Demo。

服务创建完毕,接下来就可以进行服务的启动了,启动前不要忘记在清单文件中进行前台服务权限的添加:

  1. <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  1. 服务的启动和停止
  1. //启动服务
  2. if (!ForegroundService.serviceIsLive) {
  3. // Android 8.0使用startForegroundService在前台启动新服务
  4. mForegroundService = new Intent(this, ForegroundService.class);
  5. mForegroundService.putExtra("Foreground", "This is a foreground service.");
  6. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  7. startForegroundService(mForegroundService);
  8. } else {
  9. startService(mForegroundService);
  10. }
  11. } else {
  12. Toast.makeText(this, "前台服务正在运行中...", Toast.LENGTH_SHORT).show();
  13. }
  1. //停止服务
  2. mForegroundService = new Intent(this, ForegroundService.class);
  3. stopService(mForegroundService);

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

欢迎点赞、评论,你们的赞同和鼓励是我写作的最大动力!

欢迎关注公众号:几圈年轮,查看更多有趣的技术、工具、闲言、资源。

Android通知栏前台服务的更多相关文章

  1. android: 使用前台服务

    9.5.1    使用前台服务 服务几乎都是在后台运行的,一直以来它都是默默地做着辛苦的工作.但是服务的系统 优先级还是比较低的,当系统出现内存不足的情况时,就有可能会回收掉正在后台运行的服 务.如果 ...

  2. Android 前台服务

    Android 前台服务 学习自 https://blog.csdn.net/guolin_blog/article/details/11952435#t3 前台服务漫谈 我们之前学习的Service ...

  3. Android开发之如何保证Service不被杀掉(前台服务)

    序言 最近项目要实现这样一个效果:运行后,要有一个service始终保持在后台运行,不管用户作出什么操作,都要保证service不被kill.参考了现今各种定制版的系统和安全厂商牛虻软件,如何能保证自 ...

  4. Android Foreground Service (前台服务)

    一.如何保活后台服务 在Android Services (后台服务) 里面,我们了解了Android四大组件之一的Service,知道如何使用后台服务进行来完成一些特定的任务.但是后台服务在系统内存 ...

  5. android 前台服务不显示通知

    原因可以在哪里写了执行完成后就自动结束的吧 导致前台服务没有出现 如我 @Override public int onStartCommand(Intent intent, int flags, in ...

  6. Android之后台服务判断本应用Activity是否处于栈顶

    在Android开发中,我们经常想知道是否自己的服务处于后台运行中,因为在后台运行的服务器优先级会降低,也就极有可能会被系统给回收掉,有什么好办法呢?Google推荐我们将服务运行到前台,如何知道服务 ...

  7. 适配 通知 Notification 通知渠道 前台服务 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  8. Android客户端与服务端交互之登陆示例

    Android客户端与服务端交互之登陆示例 今天了解了一下android客户端与服务端是怎样交互的,发现其实跟web有点类似吧,然后网上找了大神的登陆示例,是基于IntentService的 1.后台 ...

  9. 服务 IntentService 前台服务 定时后台服务

    Activity public class MainActivity extends ListActivity {     private int intentNumber = 0;     @Ove ...

随机推荐

  1. linux-深度学习环境配置-Centos

    下载Centos 7安装镜像,制作启动优盘. Install CentOS 7 安装CentOS 7. 第一步,配置日期.语言和键盘. 第二步,选择-系统-安装位置,进入磁盘分区界面.选择-其它存储选 ...

  2. 奇异值分解原理及Python实例

    奇异值分解 SVD(Singular Value Decomposition)是一种重要的矩阵分解方法,可以看做是特征分解在任意矩阵上的推广,SVD是在机器学习领域广泛应用的算法. 特征值和特征向量 ...

  3. resourcequota分析(一)-evaluator-v1.5.2

    什么是evaluator 大家都知道,Kubernetes中使用resourcequota对配额进行管理.配额的管理涉及两个步骤:1.计算请求所需要的资源:2.比较并更新配额.所以解读resource ...

  4. 5种方法获取url中文件的扩展名

    /** * strrchr - 查找指定字符在字符串中的最后一次出现 * strrpos — 计算指定字符串在目标字符串中最后一次出现的位置 * end — 将数组的内部指针指向最后一个单元 * pa ...

  5. CSS——NO.8(代码简写)

    */ * Copyright (c) 2016,烟台大学计算机与控制工程学院 * All rights reserved. * 文件名:text.cpp * 作者:常轩 * 微信公众号:Worldhe ...

  6. Docker实战之Redis-Cluster集群

    概述 接上一篇Docker实战之MySQL主从复制, 这里是Docker实战系列的第二篇,主要进行Redis-Cluster集群环境的快速搭建.Redis作为基于键值对的NoSQL数据库,具有高性能. ...

  7. Linux centos7.0 配置防火墙及开放端口

    现在防火墙有两种服务1.service firewalld 2.service iptables 一.就firewalld来说查看开放的端口  netstat  -anp 查询防火墙状态  servi ...

  8. MVC07

    1. 讲解ASP.net MVC的I/O操作 新建一个控制台程序,输入代码如下 using System; using System.IO; namespace IO { class Program ...

  9. 单页面和多页面的网页差别比较(SPA)

      单页面应用(singlePAge Web Application) 多页面应用MultiPage Applicaton,MPA) 组成 一个外壳页面和多个页面片段组成 多个完整的页面组成 资源公用 ...

  10. 研究开源源码之Myrmec

    好久没写博客了,自己也弄不清是懒了还是忙了.毕竟白天需要工作,晚上有时候看看资料,有时候陪家人,有时候约朋友......更加累了,可能由于累了就懒得总结了. 今天有同事问我关于代码检查文件类型的问题. ...