How to stop running services?

戏子无情 提交于 2019-11-28 23:14:31
Simone Casagranda

There is another method that it's called stopService(Intent intent). Inside the service, you can call stopSelf().

use the activity stopService() method:

stopService(new Intent(ActivityName.this, ServiceClassName.class));
Ishu

stopService(Intent intent) is the method to stop any specific service

android.os.Process.killProcess(android.os.Process.myPid());
Elder Bernini

call
stopService(new Intent(YourActivity.this, ServiceClassName.class));
see more about services in https://developer.android.com/guide/components/services.html

Complementing @Makvin answer. Stopping a service outside of it

public static ActivityManager.RunningServiceInfo getRunningServiceInfo(Class serviceClass, Context context) {
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return service;
        }
    }
    return null;
}

And after

new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            final ActivityManager.RunningServiceInfo serviceInfo = getRunningServiceInfo(service, c);
            if (serviceInfo != null) {
                android.os.Process.killProcess(serviceInfo.pid); //Stop the running service
            }
        }
}, 200); 

I'm putting killProcess inside another thread otherwise for some reason all the app is killed. In this way the app is minimized when the process is killed (less bad), suggestions are welcome

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