Service官方教程(5)后台服务发送通知、把服务变前台服务。

1.Sending Notifications to the User (发送通知)

  Once running, a service can notify the user of events using Toast Notifications or Status Bar Notifications.

  A toast notification is a message that appears on the surface of the current window for a moment then disappears, while a status bar notification provides an icon in the status bar with a message, which the user can select in order to take an action (such as start an activity).

  Usually, a status bar notification is the best technique when some background work has completed (such as a file completed downloading) and the user can now act on it. When the user selects the notification from the expanded view, the notification can start an activity (such as to view the downloaded file).

  See the Toast Notifications or Status Bar Notifications developer guides for more information.

2.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:

 startForeground()方法可以让service变前台。
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_ID, notification);
 Caution: The integer ID you give to startForeground() must not be 0.

  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.

  For more information about notifications, see Creating Status Bar Notifications.

 

 

posted @ 2016-09-23 12:03  f9q  阅读(505)  评论(0编辑  收藏  举报