【移动开发】startForeground()让服务保持前台级别
最近在使用android 4.1系统的时候,发现在手机休眠一段时间后(1-2小时),后台运行的服务被强行kill掉,有可能是系统回收内存的一种机制,要想避免这种情况可以通过startForeground让服务前台运行,当stopservice()的时候通过stopForeground()去掉。
Running a Service in the Foreground
A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.
For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an activity to interact with the music player.
To request that your service run in the foreground, call startForeground()
. This method takes two parameters: an integer that uniquely identifies the notification and the Notification
for the status bar. For example:
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
To remove the service from the foreground, call stopForeground()
. This method takes a boolean, indicating whether to remove the status bar notification as well. This method does not stop the service. However, if you stop the service while it's still running in the foreground, then the notification is also removed.
Note: The methods startForeground()
and stopForeground()
were introduced in Android 2.0 (API Level 5). In order to run your service in the foreground on older versions of the platform, you must use the previoussetForeground()
method—see the startForeground()
documentation for information about how to provide backward compatibility.
For more information about notifications, see Creating Status Bar Notifications.
要想实现需求,我们只需要在onStartCommand里面调用 startForeground,然后再onDestroy里面调用stopForeground即可!
实际情况就譬如手机里面的音乐播放器一样,不管手机如何休眠,只要开始播放音乐了,就不会kill掉这个服务,一旦停止播放音乐,服务就可能被清掉。
/**
* Make this service run in the foreground, supplying the ongoing
* notification to be shown to the user while in this state.
* By default services are background, meaning that if the system needs to
* kill them to reclaim more memory (such as to display a large page in a
* web browser), they can be killed without too much harm. You can set this
* flag if killing your service would be disruptive to the user, such as
* if your service is performing background music playback, so the user
* would notice if their music stopped playing.
*
* <p>If you need your application to run on platform versions prior to API
* level 5, you can use the following model to call the the older {@link #setForeground}
* or this modern method as appropriate:
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/ForegroundService.java
* foreground_compatibility}
*
* @param id The identifier for this notification as per
* {@link NotificationManager#notify(int, Notification)
* NotificationManager.notify(int, Notification)}.
* @param notification The Notification to be displayed.
*
* @see #stopForeground(boolean)
*/
public final void startForeground(int id, Notification notification) {
try {
mActivityManager.setServiceForeground(
new ComponentName(this, mClassName), mToken, id,
notification, true);
} catch (RemoteException ex) {
}
}
/**
* Remove this service from foreground state, allowing it to be killed if
* more memory is needed.
* @param removeNotification If true, the notification previously provided
* to {@link #startForeground} will be removed. Otherwise it will remain
* until a later call removes it (or the service is destroyed).
* @see #startForeground(int, Notification)
*/
public final void stopForeground(boolean removeNotification) {
try {
mActivityManager.setServiceForeground(
new ComponentName(this, mClassName), mToken, 0, null,
removeNotification);
} catch (RemoteException ex) {
}
}
【移动开发】startForeground()让服务保持前台级别的更多相关文章
- 使用C#开发计划任务调度服务
在系统运维中常常需要定期去跑一些计划任务,比如扫描服务器监控其性能.检查SQL Server作业是否正常.监控MQ队列是否存在堵塞现象等.如果使用Windows计划任务调度,一来管理起来就比较松散,二 ...
- 打通C/4HANA和S/4HANA的一个原型开发:智能服务创新案例
今年6月SAP发布C/4HANA之后,有顾问朋友们在微信公众号后台留言,询问C/4HANA如何同SAP的数字化核心S/4HANA系统结合起来,从而打通企业的前后端业务,帮助企业实现数字化转型. 有的顾 ...
- OpenResty从入门到开发一个网关服务(使用etcd作为注册中心)
简介 OpenResty(也称为 ngx_openresty)是一个全功能的 Web 应用服务器.它打包了标准的 Nginx 核心,很多的常用的第三方模块,以及它们的大多数依赖项. 通过揉和众多设计良 ...
- PHP 开发社区微信服务号实战图解
本博文就月初刚上线的微信服务号,图文进行总结分享给大家. 去年年底,我所在的团队讨论要开发微信号,话题由此拉开: 原来有一个3年前注册的微信号,但是后台操作无法从“订阅号”变更为“服务号”,随即找腾讯 ...
- Linux服务和运行级别科普
在Linux中,列出所有的系统服务 chkconfig --list 输入以上命令可以看到类似以下的结果 sysstat :关闭 :关闭 :启用 :启用 :关闭 :启用 :关闭 tcsd :关闭 :关 ...
- 开发工具及服务年度大奖评选 I Bugtags 荣获最具成长潜力奖
作为全球最大中文 IT 社区和服务平台.中国最大技术管理者平台的 CSDN 在中国北京总部举办了一场 2015 年开发工具及服务年度大奖评选活动,此次活动目的在于推动开发服务及工具质量的提升,提高行业 ...
- 基于SpringBoot开发一个Restful服务,实现增删改查功能
前言 在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练. ...
- Topshelf 一个简化Windows服务开发的宿主服务框架
Topshelf是 基于.net框架开发的宿主服务框架.该框架简化了服务的创建,开发人员只需要使用 Topshelf编写一个控制台程序,就能安装为Windows服务.之所以这样原因非常简单:调试一个控 ...
- Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务
Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务,Spring Cloud是一个基于Spring Boot实现的云应用开发工具:Spr ...
随机推荐
- 【BZOJ1040】【ZJOI2008】骑士
Description Z国的骑士团是一个很有势力的组织,帮会中汇聚了来自各地的精英.他们劫富济贫,惩恶扬善,受到社会各界的赞扬. 最近发生了一件可怕的事情,邪恶的Y国发动了一场针对Z国的侵略战争.战 ...
- hdu 5869 区间不同GCD个数(树状数组)
Different GCD Subarray Query Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K ( ...
- ESLint规范
配置如下:{ // 环境定义了预定义的全局变量. "env": { //环境定义了预定义的全局变量.更多在官网查看 "browser":true, " ...
- C++ 实参和形参
形参:在函数没有调用的时候,函数的形参并不占据实际的内存空间,也没有实质的值,--正如字面意思那样,"形式"参数,只是一个"形式. 实参:当函数被调用的时候,系统会为形式 ...
- Requests库介绍
Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTT ...
- c语言第三次作业。
---恢复内容开始--- (一)改错题 计算f(x)的值:输入实数x,计算并输出下列分段函数f(x)的值,输出时保留1位小数. 源代码 : 第一次编译: 错误原因:if 后面有分号 改正方法:去掉分号 ...
- python2.7入门---条件语句
前段时间呢,把MongoDB的基础内容了解的差不多了.接下来,就开始学习python2.7的基础内容喽.接着前面的知识点来学习.首先,来看一下条件语句.Python条件语句是通过一条或多条语句 ...
- Lock锁子类了解一下
前言 回顾前面: 多线程三分钟就可以入个门了! Thread源码剖析 多线程基础必要知识点!看了学习多线程事半功倍 Java锁机制了解一下 AQS简简单单过一遍 只有光头才能变强! 上一篇已经将Loc ...
- pentaho cde 自定义复选下拉框 checkbox select
pentaho 自带的component 虽多,但是当用户需要在一个表格中查看多个组别的数据时,pentaho自带的单选框就不能实现了,所以复选下拉框势在必行,实现效果如下: 实现原理是借用了jqu ...
- 使用RedisDesktopManager工具,解决连接失败问题
今天在云服务器上搭建好了redis环境,想用RedisDesktopManager工具去连接一下,结果连接不上,显示如下图: 我确保了服务器防火墙关闭,又在redis配置文件中设置了requirepa ...