How to get reference to running service?

后端 未结 2 522
半阙折子戏
半阙折子戏 2021-01-04 19:28

There is a one problem - my main activity starts the service and be closed then. When the application starts next time the application should get reference to this service a

相关标签:
2条回答
  • 2021-01-04 19:39
    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("your.service.classname".equals(service.service.getClassName())) {
                return false;
            }
        }
        return true;
    }
    
    if(isMyServiceRunning()) {
        stopService(new Intent(ServiceTest.this,MailService.class));
    }
    
    0 讨论(0)
  • 2021-01-04 19:49

    This answer is based on the answer by @DawidSajdak. His code is mostly correct, but he switched the return statements, so it gives the opposite of the intended result. The correct code should be:

    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("your.service.classname".equals(service.service.getClassName())) {
                return true; // Package name matches, our service is running
            }
        }
        return false; // No matching package name found => Our service is not running
    }
    
    if(isMyServiceRunning()) {
        stopService(new Intent(ServiceTest.this,MailService.class));
    }
    
    0 讨论(0)
提交回复
热议问题