3

我有一个获取 GPS 坐标的应用程序。它工作正常,但如果服务正在运行,我想从调用活动中进行测试。我有以下我认为会检查的代码,但是当通知栏中的 GPS 图标仍在闪烁时,它返回 false。有谁知道为什么?提前致谢

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));
4

3 回答 3

3

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

于 2013-10-17T14:38:42.847 回答
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;
    }
于 2014-07-05T05:35:49.583 回答
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;   
}
于 2013-10-17T14:43:03.697 回答