最近在使用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) {}}

转载于:https://www.cnblogs.com/duadu/p/6167314.html

【移动开发】startForeground()让服务保持前台级别相关推荐

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

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

  2. golang微服务框架对比_Go语言开发的微服务框架,你了解多少?

    Go语言开发的微服务框架 1.项目名称:Istio 项目简介:Istio是由Google.IBM和Lyft开源的微服务管理.保护和监控框架.使用istio可以很简单的创建具有负载均衡.服务间认证.监控 ...

  3. Android开发 - 线程和服务

    服务吧,在程序即便关闭的时候还是可以回后台运行,不搞情怀了.后台功能属于四大组件之一. 服务是Android中实现程序后台运行的解决方案,很适合执行不需要与用户交互而且长时间运行的任务.不依赖于任何U ...

  4. 微信小程序原生开发集成IM服务出现无法找到模块“tim-wx-sdk”的声明文件问题解决

    微信小程序原生开发集成IM服务出现无法找到模块"tim-wx-sdk"的声明文件问题解决: 通过npm命令安装配置: 在终端进入到小程序项目根目录执行:npm install 未初 ...

  5. Android StudioTV开发教程(十八)建立电视频道,开发电视输入服务

    Android Studio TV开发教程 (转自Android官网https://developer.android.com/training/tv/start) 文章源自:光谷佳武 https:/ ...

  6. 【关于分布式系统开发和微服务架构自我心得小记

    一.一个完整项目为何要分布式开发? 完整项目业务实现是相当庞大,程序员在修改一个业务程序的的代码时,可能会影响整个项目的启动和部署,项目代码一个地方修改会产生很多问题,不利于程序的开发,同时项目的启动 ...

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

    点击上方"方志朋",选择"置顶公众号" 技术文章第一时间送达! 作者:虚无境 cnblogs.com/xuwujing/p/8260935.html 前言 在去 ...

  8. 基于Spring开发的DUBBO服务接口测试

    基于Spring开发的DUBBO服务接口测试 知识共享主要内容: 1. Dubbo相关概念和架构,以及dubbo服务程序开发步骤. 2. 基于Spring开发框架的dubbo服务接口测试相关配置. 3 ...

  9. cxf 服务端soap报文_使用Apache CXF开发SOAP Web服务

    cxf 服务端soap报文 在上一篇文章中,我逐步介绍了使用apache CXF开发简单的RESTFull服务的步骤. 在本文中,我将讨论使用CXF开发SOAP Web服务. 在继续前进之前,让我们先 ...

  10. 使用Apache CXF开发SOAP Web服务

    在上一篇文章中,我逐步介绍了使用apache CXF开发简单的RESTFull服务的步骤. 在本文中,我将讨论使用CXF开发SOAP Web服务. 在继续前进之前,让我们了解构成SOAP Web服务的 ...

最新文章

  1. mac 搭建python+selenium+chromedriver环境
  2. MSER+SIFT 图像的特征向量提取
  3. EWSD命令输入格式解释
  4. 实现MySQL远程连接
  5. mapstruct详解
  6. 20220129--CTF WEB方向刷题-- WP--非常简单的webshell题
  7. Linux基础之命令练习Day2-useradd(mod,del),groupadd(mod,del),chmod,chown,
  8. CSS中height:100%和height:inherit的异同
  9. 用vs编译openssl静态库
  10. 安装win10的笔记本有10个地方需要微调
  11. 计算机英语讲课笔记07
  12. Spring Boot动态修改日志级别
  13. 从发起请求到收到响应,各个阶段的时间损耗是怎么样的?
  14. git merge 的撤销
  15. JavaScript中的标识符(附:关键字表)
  16. python第三方模块
  17. Linux Ruby安装
  18. 蔡甸17万亩粮田丰收 国稻种芯:夏汛蓄洪水护住28天抗旱期
  19. 从一个程序中生成另一个程序(资源法)
  20. day16 正则检测、匹配次数、分组与分支、re模块、匹配参数

热门文章

  1. ASP.NET MVC过滤器
  2. Docker 监控- Prometheus VS Cloud Insight
  3. Pyqt+QRcode 生成 识别 二维码
  4. 用arp-scan扫描局域网IP地址
  5. 内大考研计算机专业课,2019计算机考研专业课核心考点梳理
  6. cfda计算机管理化系统,计算机化系统清单
  7. h264解码延迟优化_OPPO Enco Free真无线双发耳机提速120ms,延迟优于苹果华为
  8. 多线程任务执行后发送通知,CyclicBarrier使用
  9. Windows解除网速限制,Windows性能提升,性能优化
  10. 面试题--------10、索引是什么,有什么作用和优缺点