Android通知栏前台服务
一、前台服务的简单介绍
前台服务是那些被认为用户知道且在系统内存不足的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在运行(Ongoing)标题之下——这就意味着通知只有在这个服务被终止或从前台主动移除通知后才能被解除。
最常见的表现形式就是音乐播放服务,应用程序后台运行时,用户可以通过通知栏,知道当前播放内容,并进行暂停、继续、切歌等相关操作。
二、为什么使用前台服务
后台运行的Service系统优先级相对较低,当系统内存不足时,在后台运行的Service就有可能被回收,为了保持后台服务的正常运行及相关操作,可以选择将需要保持运行的Service设置为前台服务,从而使APP长时间处于后台或者关闭(进程未被清理)时,服务能够保持工作。
三、前台服务的详细使用
- 创建服务内容,如下(四大组件不要忘记清单文件进行注册,否则启动会找不到服务);
public class ForegroundService extends Service {
private static final String TAG = ForegroundService.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
}
}
- 创建服务通知内容,例如音乐播放,蓝牙设备正在连接等:
/**
* 创建服务通知
*/
private Notification createForegroundNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 唯一的通知通道的id.
String notificationChannelId = "notification_channel_id_01";
// Android8.0以上的系统,新建消息通道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//用户可见的通道名称
String channelName = "Foreground Service Notification";
//通道的重要程度
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
notificationChannel.setDescription("Channel description");
//LED灯
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
//震动
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId);
//通知小图标
builder.setSmallIcon(R.drawable.ic_launcher);
//通知标题
builder.setContentTitle("ContentTitle");
//通知内容
builder.setContentText("ContentText");
//设定通知显示的时间
builder.setWhen(System.currentTimeMillis());
//设定启动的内容
Intent activityIntent = new Intent(this, NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
//创建通知并返回
return builder.build();
}
- 启动服务时,创建通知:
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
// 获取服务通知
Notification notification = createForegroundNotification();
//将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
startForeground(NOTIFICATION_ID, notification);
}
- 停止服务时,移除通知:
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
// 标记服务关闭
ForegroundService.serviceIsLive = false;
// 移除通知
stopForeground(true);
super.onDestroy();
}
- 判断服务是否启动及获取传递信息:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
// 标记服务启动
ForegroundService.serviceIsLive = true;
// 数据获取
String data = intent.getStringExtra("Foreground");
Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
以上就是前台服务的创建过程,相关注释已经很明白了,具体使用可以查看文末的Demo。
服务创建完毕,接下来就可以进行服务的启动了,启动前不要忘记在清单文件中进行前台服务权限的添加:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
- 服务的启动和停止
//启动服务
if (!ForegroundService.serviceIsLive) {
// Android 8.0使用startForegroundService在前台启动新服务
mForegroundService = new Intent(this, ForegroundService.class);
mForegroundService.putExtra("Foreground", "This is a foreground service.");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(mForegroundService);
} else {
startService(mForegroundService);
}
} else {
Toast.makeText(this, "前台服务正在运行中...", Toast.LENGTH_SHORT).show();
}
//停止服务
mForegroundService = new Intent(this, ForegroundService.class);
stopService(mForegroundService);
关于前台服务的介绍及使用就到这里了,相关使用已上传至Github开发记录,欢迎点击查阅及Star,我也会继续补充其它有用的知识及例子在项目上。
欢迎点赞、评论,你们的赞同和鼓励是我写作的最大动力!
欢迎关注公众号:几圈年轮,查看更多有趣的技术、工具、闲言、资源。
Android通知栏前台服务的更多相关文章
- android: 使用前台服务
9.5.1 使用前台服务 服务几乎都是在后台运行的,一直以来它都是默默地做着辛苦的工作.但是服务的系统 优先级还是比较低的,当系统出现内存不足的情况时,就有可能会回收掉正在后台运行的服 务.如果 ...
- Android 前台服务
Android 前台服务 学习自 https://blog.csdn.net/guolin_blog/article/details/11952435#t3 前台服务漫谈 我们之前学习的Service ...
- Android开发之如何保证Service不被杀掉(前台服务)
序言 最近项目要实现这样一个效果:运行后,要有一个service始终保持在后台运行,不管用户作出什么操作,都要保证service不被kill.参考了现今各种定制版的系统和安全厂商牛虻软件,如何能保证自 ...
- Android Foreground Service (前台服务)
一.如何保活后台服务 在Android Services (后台服务) 里面,我们了解了Android四大组件之一的Service,知道如何使用后台服务进行来完成一些特定的任务.但是后台服务在系统内存 ...
- android 前台服务不显示通知
原因可以在哪里写了执行完成后就自动结束的吧 导致前台服务没有出现 如我 @Override public int onStartCommand(Intent intent, int flags, in ...
- Android之后台服务判断本应用Activity是否处于栈顶
在Android开发中,我们经常想知道是否自己的服务处于后台运行中,因为在后台运行的服务器优先级会降低,也就极有可能会被系统给回收掉,有什么好办法呢?Google推荐我们将服务运行到前台,如何知道服务 ...
- 适配 通知 Notification 通知渠道 前台服务 MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- Android客户端与服务端交互之登陆示例
Android客户端与服务端交互之登陆示例 今天了解了一下android客户端与服务端是怎样交互的,发现其实跟web有点类似吧,然后网上找了大神的登陆示例,是基于IntentService的 1.后台 ...
- 服务 IntentService 前台服务 定时后台服务
Activity public class MainActivity extends ListActivity { private int intentNumber = 0; @Ove ...
随机推荐
- DIY电压基准测万用表
| 分类 日志 | 手里有三个常用的手持表,UT61E四位半,优利德明星产品:福禄克F117C,换挡快,单手操作还带LoZ:UT210E小钳表能够通过修改EEPROM更改电表配置,已经刷了6000字 ...
- Event Loop事件循环,GET!
JS中比较让人头疼的问题之一要算异步事件了,比如我们经常要等后台返回数据后进行dom操作,又比如我们要设置一个定时器完成特定的要求.在这些同步与异步事件里,异步事件肯定是在同步事件之后的,但是异步事件 ...
- 使用hexo,创建博客
下载hexo工具 1 npm install hexo-cli -g 下载完成后可以在命令行下生成一个全局命令hexo搭建博客可用thinkjs 创建一个博客文件夹 1 hexo init 博客文件夹 ...
- 安卓权威编程指南-笔记(第24章 Looper Handler 和 HandlerThread)
AsyncTask是执行后台线程的最简单方式,但它不适用于那些重复且长时间运行的任务. 1. Looper Android中,线程拥有一个消息队列(message queue),使用消息队列的线程叫做 ...
- HTML标签学习总结(1)
1. <em>和<strong>标签是为了强调一段话中的关键字时使用,它们的语义是强调. 2. <span>标签是没有语义的,它的作用就是为了设置单独的样式用的. ...
- 图解Python网络编程
返回目录 本篇索引 (1)基本原理 (2)socket模块 (3)select模块 (4)asyncore模块 (5)asynchat模块 (6)socketserver模块 (1)基本原理 本篇指的 ...
- opencv +数字识别
现在很多场景需要使用的数字识别,比如银行卡识别,以及车牌识别等,在AI领域有很多图像识别算法,大多是居于opencv 或者谷歌开源的tesseract 识别. 由于公司业务需要,需要开发一个客户端程序 ...
- Git将文件上传至Github过程
1.安装Git工具(在这里就不多说了) 2.我们需要先创建一个本地的版本库(其实也就是一个文件夹). 你可以直接在桌面右击新建文件夹,也可以右击打开Git bash命令行窗口通过命令来创建. 现在我通 ...
- python入门到放弃-基本数据类型之tuple元组
#概述 元组俗称不可变的列表,又称只读列表,是python的基本数据类型之一, 用()小括号表示,里面使用,逗号隔开 元组里面可以放任何的数据类型的数据,查询可以,循环可以,但是就是不能修改 #先来看 ...
- 简单易懂的Servlet路径问题
关于servlet路径,我看了一下网上别人的博客园,发现都有一个通病,讲的太专业了,又抓不住关键部分,往往看一眼就不想看第二眼.所以我特地准备了初学者所通识的servlet路径问题. 1.标识符 /j ...