• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
james1207

博客园    首页    新随笔    联系   管理    订阅  订阅

在前台运行Service

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


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

[java] view plain copy print ?
  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(this, 0, 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文档查看如何提供与旧版本的兼容性.

 

posted @ 2013-09-27 19:23  Class Xman  阅读(835)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3