在前台运行Service

一个前台的 service是被用户强烈关注的从而不会在内存低时被系统杀死.前台 service必须在状态栏上提供一个通知,这个通知被放在"正在进行"区域中,这表示这个通知不能被解除,除非服务停止了或者从前台移除了.


  例如,一个从service播放音乐的音乐播放器,应被设置为前台运行,因为用户会明确地注意它的运行.在状态栏中的通知可能会显示当前的歌曲并且允许用户启动一个activity来与音乐播放器交互.

  1. Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),  
  2.         System.currentTimeMillis());  
  3. Intent notificationIntent = new Intent(this, ExampleActivity.class);  
  4. PendingIntent pendingIntent = PendingIntent.getActivity(this0, notificationIntent, 0);  
  5. notification.setLatestEventInfo(this, getText(R.string.notification_title),  
  6.         getText(R.string.notification_message), pendingIntent);  
  7. startForeground(ONGOING_NOTIFICATION, notification);  
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);

  要请求你的service运行于前台,调用startForeground().此方法有两个参数:一个整数唯一的标识一个通知,和这个用于状态栏的通知,例如:


  要从前台移除service,调用stopForeground().这个方法有boolean型参数,表明是否也从状态栏删除对应的通知.这个方法不会停掉service.然而,如果你停止了正在前台运行的service,这个通知也会被删除.


  注意:方法startForeground()和方法stopForeground()是从Android2.0 (API Level 5)引入的.为了在早期版本是于前台运行你的service,你必须使用以前的那个setForeground()方法—见startForeground()API文档查看如何提供与旧版本的兼容性.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值