有一个问题 - 我的主要活动启动服务然后关闭。当应用程序下次启动时,应用程序应该引用此服务并停止它。但我不知道如何获得对正在运行的服务的引用。拜托,我希望你能帮助我。谢谢。
答案 0 :(得分:11)
此答案基于answer by @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));
}
答案 1 :(得分:-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));
}