2013-10-17 133 views
2

我有一个获取GPS坐标的应用程序。它工作正常,但我想从调用活动内测试如果服务正在运行。我有以下代码,我认为会检查,但当通知栏中的GPS图标仍然闪烁时,它会返回false。有没有人有任何想法?在此先感谢android如何检查服务是否正在运行

private boolean isGpsServiceRunning() { 
      ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE); 
      for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 
      if ("LocationService".equals(service.service.getClassName())) { 
       return true; 
      } 
      } 
      return false; 
     } 

LocalBroadcastManager.getInstance(getApplicationContext()) 
          .registerReceiver(
            locationChangereceiver, 
            new IntentFilter(
              LocationChangeIntent.ACTION_LOCATION_CHANGE)); 
        startService(new Intent(this, LocationService.class)); 
+0

是否还回是真的吗?您是否尝试打印所有正在运行的服务,以确认您没有查找错误的值。另外,我会建议使用LocationService.class.getSimpleName()而不是硬编码它。 –

+0

只是修复它,我也需要把包名称。和你说的一样。创造一个答案,我会接受。谢谢 – turtleboy

+0

好吧,完成:) –

回答

3

您应该与LocationService.class.getName()进行比较,而不是使用硬编码值。此外,您使用的值对应于Class#getSimpleName(),这可能不是您想要的。

1

这种方法工作正常,我和易于使用:

private boolean isMyServiceRunning() { 
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); 

    Log.i(TAG,"MyService.class.getName() = "+ButtonOnBootService.class.getName());    

    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 

     Log.i(TAG,"service.getClassName() = " +service.service.getClassName()); 

     if (ButtonOnBootService.class.getName().equals(service.service.getClassName())) { 
      return true; 
     } 
    } 
    return false; 
} 
+1

您可能想要添加一个如下所示的检查:service.uid == Process.myUid()。这将加快搜索速度,避免在另一个进程中找到服务,尽管我不太可能同时运行相同的应用程序免费/付费版本。 – 3c71

+0

谢谢。我会仔细看看的。以任何方式加速Android听起来很有用:-) – bofredo

2
public boolean check(){ 
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) 
      { 
       if ("com.example.yourpackagename.YourserviceName" 
         .equals(service.service.getClassName())) 
       { 
        return true; 
       } 
      } 
     return false; 
    } 
相关问题