Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

android - 在Android OS销毁服务时删除通知(Remove notification when service destroyed by android OS)

I created an app which shows Notification when Service.onStartCommand() method executed and hide notification when Service.onDestroy() is called.

(我创建了一个应用,该应用在执行Service.onStartCommand()方法时显示通知,并在调用Service.onDestroy()时隐藏通知。)

Its works fine for normal calls to startService() and stopService().

(对于正常调用startService()和stopService()而言,它的效果很好。)

Service Code:

(服务代码:)

@Override
public IBinder onBind(Intent intent) 
{
    return null;
}
@Override
public void onCreate() 
{
    super.onCreate();
    nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    //Some  code here
    showNotification();
    return START_NOT_STICKY; 
}

@Override
public void onDestroy() 
{
    super.onDestroy();
    nm.cancel(R.string.service_started);
}

Problem: When my service is destroyed by android OS() (In case when onDestroy() not called) then notification not removed.

(问题:当我的服务被android OS()销毁时onDestroy()未调用onDestroy() ),则通知未删除。)

So how to remove notification when Service is destroyed by android OS itself?

(那么,当服务被Android OS本身销毁时,如何删除通知?)

  ask by user1041858 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

您应该在要停止服务的任何地方使用它,这将关闭您的通知并终止服务。

stopService(new Intent(MainActivity.this,MyService.class));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...