我有一个可以获得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));
答案 0 :(得分:3)
您应该与LocationService.class.getName()
进行比较,而不是使用硬编码值。此外,您使用的值对应于Class#getSimpleName(),这可能不是您想要的。
答案 1 :(得分: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;
}
答案 2 :(得分: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;
}