有一个问题 - 我的主要活动启动服务然后关闭.当应用程序下次启动时,应用程序应该引用此服务并将其停止.但我不知道如何获得对正在运行的服务的引用.拜托,我希望你能帮助我.谢谢.
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));
}
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));
}
| 归档时间: | 
 | 
| 查看次数: | 4526 次 | 
| 最近记录: |