最近在使用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. [bzoj省选十连测推广赛2]T2七彩树

    抄自:http://blog.csdn.net/coldef/article/details/61412577 当时看了就不会,看了别人的题解不懂怎么维护,最后抄了个代码....... 给定一棵n个点 ...

  2. Spring boot结合Maven实现不同环境的配置

    配置文件层次: pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http ...

  3. Intellij Error:Cannot build Artifact 'XXX:war exploded' because it is included into a circular dependency

    外网的流程是这样的. 1: 2: 3: 4: 基本按这个来就好了 如果到了build artfact哪里按钮是灰色 就要手动建了 https://jingyan.baidu.com/album/0a5 ...

  4. SSH上一个随笔的基础上添加上hibernate支持

    配置文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.o ...

  5. 线性表 linear_list 顺序存储结构

    可以把线性表看作一串珠子 序列:指其中的元素是有序的 注意last和length变量的内在关系 注意:将元素所占的空间和表长合并为C语言的一个结构类型 静态分配的方式,分配给一个固定大小的存储空间之后 ...

  6. 网易笔试题:浏览器中输入一个url后回车到返回页面信息的过程

    You enter a URL into the browser输入一个url地址 The browser looks up the IP address for the domain name浏览器 ...

  7. webpack require.ensure 按需加载

    使用 vue-cli构建的项目,在 默认情况下 ,会将所有的js代码打包为一个整体比如index.js.当使用存在多个路由代码的时候,index.js可能会超大,影响加载速度. 这个每个路由页面除了i ...

  8. Android studio安装和问题

    一.Android studio的安装 [提示]A.以下Android studio2.2.2版本.(也有新版本) B.以下是用Android studio自带的sdk ①双击安装文件进行安装 ②如果 ...

  9. 反射 类的加载 Schema DOM 解析方式和解析器 命名空间

    Day15 反射 1.1 类的加载 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三步来实现对这个类进行初始化. l 加载 就是指将class文件读入内存,并为之创建 ...

  10. iOS多线程编程--NSOperation(转)

    这篇文章写得非常不错,基础用法都涉及到了,我把文章提到的例子都写到了demo里面, 原文地址: iOS多线程--彻底学会多线程之『NSOperation』 demo下载:https://github. ...