向用户发送提醒
服务可以通过toast或者状态条通知的方式来提醒用户。
通常,当某个后台工作已经完成(如文件下载完毕),用户可以进行下一步操作,这时候状态栏通知是最佳的方案。点选通知之后,可以启动一个活动(比如浏览下载的文件)。
在前台运行一个服务
前台服务:
- 用户有意识的关注,不能作为系统为释放内存而关闭的备选项目。
- 前台任务必须提供一个状态栏通知,放置在“ongoing”栏目下面——这里意味着此项通知不能被清除掉,除非服务终止或者从前台移除。
- 例如:通过服务播放姻缘必须在前台执行。因为用户明确的关注这项操作。通知可以指出当前播放的歌曲,并允许用户启动一个活动来痛音乐播放器交互。
通过调用startForeground()来使服务运行于前台,传入两个参数:
- 一个唯一标识通知的整数
- 通知本身
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);
- 要从前台移除服务,应当调用gstopForeground()。该方法接受一个布尔值,指出是否从状态栏移除对应的提醒项。
- For more information about notifications, see Creating Status Bar Notifications.
管理服务的生命周期
服务可以有两种不同的生命轨迹:
- 启动服务
- 绑定服务
这两条路径并非完全隔绝。可以绑定到一个已经启动的服务。如后台音乐服务可以由被一个intent启动。稍后,如果用户想要对播放施加控制或者查看信息,那么可以通过一个活动绑定到这个服务。绑定之后,stopSelf()或者stopService()就不会真正的终止服务了。
实现生命周期回调:
public class ExampleService extends Service {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used
@Override
public void onCreate
() {
// The service is being created
}
@Override
public int onStartCommand
(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
@Override
public IBinder onBind
(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
@Override
public boolean onUnbind
(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
@Override
public void onRebind
(Intent intent) {
// A client is binding to the service with bindService()
,
// after onUnbind() has already been called
}
@Override
public void onDestroy
() {
// The service is no longer used and is being destroyed
}
}
与Activity不同,在实现服务的生命周期回调时,不必调用父类。
通过实现生命周期回调,你可以监测两种嵌入的循环:
- 整体生命周期:
> onCreate()之始到onDestroy()返回之间。
- 活跃生命周期:
> 自onStartCommand()或onBind()的调用开始,结束于onStartCommand()或onUnBind()返回
===========================
关于绑定服务,继续阅读文档: