Reputation: 7572
I have an app that gets GPS co-ordinates. It works fine but i want to test from within the calling activity if the service is running. I have the following code that i thought would check but it is returning false when the GPS icon in the notification bar is still flashing. Has anyone any ideas why? Thanks in advance
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));
Upvotes: 3
Views: 2294
Reputation: 2163
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;
}
Upvotes: 2
Reputation: 2348
this method works fine for me and is easy to use:
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;
}
Upvotes: 1
Reputation: 30385
You should compare against LocationService.class.getName()
, instead of using a hard coded value. Also, the value that you are using corresponds to the Class#getSimpleName() which is probably not what you want here.
Upvotes: 3