Call onDestroy() of Service

时光毁灭记忆、已成空白 提交于 2019-12-01 21:32:51

From within the Service class, call:

stopSelf();

From within another class, like your MainActivity for example:

Intent i = new Intent(this, ServiceName.class); stopService(i);

Both of these will stop your service. Make sure you are returning START_NOT_STICKY so that the service doesn't start back up again.

When you want to stop your service then simply fire an intent to stop the service as shown below.

Intent intent = new Intent();
intent.setClass(getApplicationContext(), YourService.class);
stopService(intent);

This is to stop service forcefully.When you stop service in this manner it's guaranteed that onDestroy method is called by android framework.

Hope this helps to solve you issue.

My God

I want to call onDestroy() method of Service in android.

  • Do not call this method directly

public void onDestroy ()

Called by the system to notify a Service that it is no longer used and is being removed. The service should clean up any resources it holds (threads, registered receivers, etc) at this point. Upon return, there will be no more calls in to this Service object and it is effectively dead. Do not call this method directly.

However you can check if the service is running or not.

I need to find out when service stop? and need to stop music and remove notification.

Use the following way -

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

Then call it using - isMyServiceRunning(MyService.class).

Reference:

1) Service onDestroy().

2) how-to-check-if-a-service-is-running-in-android.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!