android Service的stopSelf

来源:互联网 发布:标签设计软件 编辑:程序博客网 时间:2024/06/12 01:28

startId:代表启动服务的次数,由系统生成。

stopSelf(int startId):

在其参数startId跟最后启动该service时生成的ID相等时才会执行停止服务。

stopSelf():直接停止服务。

使用场景:

如果同时有多个服务启动请求发送到onStartCommand(),不应该在处理完一个请求后调用stopSelf();因为在调用此函数销毁service之前,可能service又接收到新的启动请求,如果此时service被销毁,新的请求将得不到处理。此情况应该调用stopSelf(int startId)。

而且stopSelf是会调用Destroy方法的。

 

需要注意的是,如果是前台服务,你就必须要调到startForeground和stopForeground。如果仅仅是一个Notifaction,设置的flags是FLAG_FOREGROUND_SERVICE,这样是没有意义的,并且调用cancel方法是无法取消这个通知的,这个时候可以设置成FLAG_ONGOING_EVENT

public int onStartCommand(Intent intent, int flags, int startId) {    PendingIntent notifIntent;    Intent notificationIntent = new Intent();  // fill up yourself    notifIntent = PendingIntent.getActivity();  // fill up yourself    Notification note = new Notification();  // fill up yourself    note.setLatestEventInfo(context, getString(R.string.app_name), Message, notifIntent);      startForeground(yourOwnNumber, note);  // fill up yourself    displayYourNotification();    // Fill up the rest yourself.}
public void onDestroy() {    stopForeground();  // fill up yourself}public void displayYourNotification() {    Intent notificationIntent = new Intent();  // fill up yourself    notifIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);    Notification note = new Notification();  // fill up yourself    note.flags = Notification.FLAG_FOREGROUND_SERVICE;    note.setLatestEventInfo(context, TITLE, Message, notifIntent);      notifManager.notify(ID, note);}
0 0
原创粉丝点击