Android Service 前台
来源:互联网 发布:社交网络的好处知乎 编辑:程序博客网 时间:2024/06/05 23:26
Service几乎都是在后台运行的,一直以来它都是默默地做着辛苦的工作。但是Service的系统优先级还是比较低的,当系统出现内存不足情况时,就有可能会回收掉正在后台运行的Service。
如果你希望Service可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,就可以考虑使用前台Service。前台Service和普通Service最大的区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。当然有时候你也可能不仅仅是为了防止Service被回收才使用前台Service,有些项目由于特殊的需求会要求必须使用前台Service。
@Override public void onCreate() { super.onCreate(); Notification notification = new Notification(R.drawable.ic_launcher, "有通知到来", System.currentTimeMillis()); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, "这是通知的标题", "这是通知的内容",pendingIntent); startForeground(1, notification); Log.d(TAG, "onCreate() executed"); }还有新的写法:
@Override public void onCreate() { super.onCreate(); PendingIntent pendingIntent = PendingIntent.getActivity(this,0,new Intent(this, MainActivity.class), 0); // 通过Notification.Builder来创建通知,注意API Level // API16之后才支持 Notification notify = new Notification.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setTicker("TickerText:" + "您有新短消息,请注意查收!") .setContentTitle("Notification Title") .setContentText("This is the notification message") .setContentIntent(pendingIntent).setNumber(1).build(); // 需要注意build()是在API // level16及之后增加的,API11可以使用getNotificatin()来替代 startForeground(1, notify); Log.d(TAG, "onCreate() executed"); }测试,两种方法都是可以的,只是第一种方法的函数已经不推荐使用了。当然,还有其它的方法来写,我们只要会第二种方法就可以了。
0 0
- Android 前台Service实现
- Android前台Service
- Android Service 前台
- Android自定义前台Service
- 如何创建前台Android Service
- Android service(三)前台服务
- Android Service 前台运行与生命期
- Android创建前台运行的Service
- Android中service的使用,前台服务
- Android创建前台运行的Service
- Android创建前台运行的Service
- Android创建前台运行的Service
- Android创建前台运行的Service
- Android四大组件之Service--前台服务
- Android Service详解(八)---前台服务详解
- Android创建前台运行的Service
- Android Service学习笔记--前台服务
- 前台Service
- 使用 Mockito 修改私有属性
- QMUI / QMUI_iOS框架学习(五)
- 菜鸟之路
- 史上最简单的SpringCloud教程 | 第二篇: 服务消费者(rest+ribbon)
- SEO学习笔记
- Android Service 前台
- ListView的简单使用
- java开发面试题
- 让CoreData更简单些
- 第三方很好的Toast
- 史上最简单的SpringCloud教程 | 第三篇: 服务消费者(Feign)
- 06-S3C2440学习之移植2012u-boot到S3C2440(移植过程四)支持Nand Flash+支持DM9000网卡
- Leetcode -- 28. Implement strStr()
- 优先队列