在前台运行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文档查看如何提供与旧版本的兼容性.

原文地址:https://www.cnblogs.com/james1207/p/3343395.html