如何获得对运行服务的引用?

use*_*635 9 java android

有一个问题 - 我的主要活动启动服务然后关闭.当应用程序下次启动时,应用程序应该引用此服务并将其停止.但我不知道如何获得对正在运行的服务的引用.拜托,我希望你能帮助我.谢谢.

mal*_*ave 11

这个答案是基于@DawidSajdak回答.他的代码大多是正确的,但他改变了return陈述,因此它与预期结果相反.正确的代码应该是:

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));
}
Run Code Online (Sandbox Code Playgroud)

  • 这只是检查服务是否正在运行我可以获得服务的实例 (2认同)

Daw*_*dak -1

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));
}
Run Code Online (Sandbox Code Playgroud)

  • 你的例子是错误的。返回值需要交换。 (6认同)
  • 嗯..那是相当多余的。只需调用“stopService”,无论您的“Service”是否正在运行 - 如果没有运行也没有什么坏处 - “stopService”只会返回“false”。 (4认同)