最近在使用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()让服务保持前台级别的更多相关文章

  1. 使用C#开发计划任务调度服务

    在系统运维中常常需要定期去跑一些计划任务,比如扫描服务器监控其性能.检查SQL Server作业是否正常.监控MQ队列是否存在堵塞现象等.如果使用Windows计划任务调度,一来管理起来就比较松散,二 ...

  2. 打通C/4HANA和S/4HANA的一个原型开发:智能服务创新案例

    今年6月SAP发布C/4HANA之后,有顾问朋友们在微信公众号后台留言,询问C/4HANA如何同SAP的数字化核心S/4HANA系统结合起来,从而打通企业的前后端业务,帮助企业实现数字化转型. 有的顾 ...

  3. OpenResty从入门到开发一个网关服务(使用etcd作为注册中心)

    简介 OpenResty(也称为 ngx_openresty)是一个全功能的 Web 应用服务器.它打包了标准的 Nginx 核心,很多的常用的第三方模块,以及它们的大多数依赖项. 通过揉和众多设计良 ...

  4. PHP 开发社区微信服务号实战图解

    本博文就月初刚上线的微信服务号,图文进行总结分享给大家. 去年年底,我所在的团队讨论要开发微信号,话题由此拉开: 原来有一个3年前注册的微信号,但是后台操作无法从“订阅号”变更为“服务号”,随即找腾讯 ...

  5. Linux服务和运行级别科普

    在Linux中,列出所有的系统服务 chkconfig --list 输入以上命令可以看到类似以下的结果 sysstat :关闭 :关闭 :启用 :启用 :关闭 :启用 :关闭 tcsd :关闭 :关 ...

  6. 开发工具及服务年度大奖评选 I Bugtags 荣获最具成长潜力奖

    作为全球最大中文 IT 社区和服务平台.中国最大技术管理者平台的 CSDN 在中国北京总部举办了一场 2015 年开发工具及服务年度大奖评选活动,此次活动目的在于推动开发服务及工具质量的提升,提高行业 ...

  7. 基于SpringBoot开发一个Restful服务,实现增删改查功能

    前言 在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练. ...

  8. Topshelf 一个简化Windows服务开发的宿主服务框架

    Topshelf是 基于.net框架开发的宿主服务框架.该框架简化了服务的创建,开发人员只需要使用 Topshelf编写一个控制台程序,就能安装为Windows服务.之所以这样原因非常简单:调试一个控 ...

  9. Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务

    Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务,Spring Cloud是一个基于Spring Boot实现的云应用开发工具:Spr ...

随机推荐

  1. 注意类型转换——Effective C++

    注意类型转换: C++提供了四种新式类型转换: const_cast<T>(expression); static_cast<T>(expression); dynamic_c ...

  2. linux内核中的链表

    1.内核中的链表 linux内核链表与众不同,他不是把将数据结构塞入链表,而是将链表节点塞入数据,在2.1内核中引入了官方链表,从此内核中所有的链表使用都采用此链表,千万不要在重复造车轮子了!链表实现 ...

  3. mac下IDLE无法输入中文的问题

    解决方法是下载安装新版本的 Tcl/Tk 下载地址:http://www.activestate.com/activetcl/downloads 注意要下最新的8.5.18.0版本,安装好了再重启ID ...

  4. 非Unicode编码的软件如何在Windows系统上运行

    我们常常会遇到这样一种情况:点开某些日文软件(我不会说就是galgame( ╯□╰ ))会出现乱码或者直接无法运行. 出现乱码的原因很简单:编码与译码的方式不一致!!!!!!!!!!! 首先大家需要知 ...

  5. SpringMVC 环境搭建(HelloWorld)

    SpringMVC 入门案例 环境 * springMVC * web 构建文件目录结构 修改dispatcher-servlet.xml文件 修改web.xml

  6. IOS JavaScriptCore介绍

    本文主要转自:https://www.jianshu.com/p/cdaf9bc3d65d http://blog.csdn.net/u011993697/article/details/515772 ...

  7. CentOS7.2安装jdk7u80

    1.cd /usr/local 2.tar zxvf jdk-7u80-linux-x64.tar.gz 3.vi /etc/profile 4.输入i 加入内容如下: export JAVA_HOM ...

  8. JS的事件模型

    之前对事件模型还是比较清楚的,许多概念都清晰映射在脑海中.工作之后,一方面使用的局限性,二是习惯于用框架中的各种事件监听方式,简单即方便,久而久之,事件的一些概念开始淡出记忆中,就像我现在已经开始淡忘 ...

  9. angular-cli学习笔记 快速创建代码模板

    组件: ng g component component/demo 服务: ng g service service/news 然后在app.module.ts里引入 ng g service ser ...

  10. FJUT寒假作业第二周C题解(位运算)

    题目来源:http://210.34.193.66:8080/vj/Contest.jsp?cid=161#P2 题意比较好理解.如果直接按题目要求一步一解.一定超时.作为一个懒人也不会这么暴力一个肯 ...