l want to check if a service is running l wrote this code
public class startServiceOrNo {
public static void startServiceIfItsNotRuning(Class<?> class1, Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (class1.getName().equals(service.service.getClassName())) {
Lg.d("servisstart SERVICE ALREADY START" + class1.getName());
return;
}
}
Lg.d("servisstart SSERVICE NEW SERVIS " + class1.getName());
context.startService(new Intent(context, class1));
}
and use it startServiceOrNo.startServiceIfItsNotRuning(OfflineChopsMonitor.class,this)
if l check service from one class its work, but if l check same service from different class, its check don't work
1.) In Activity class:
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
2.) In Non-Activity class (BroadcastReceiver):
private boolean isMyServiceRunning(Class<?> serviceClass,Context context) {
ActivityManager manager = (ActivityManager)context. getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i("Service already","running");
return true;
}
}
Log.i("Service not","running");
return false;
}
Why don't you let the Service itself figure that out?
public class MyService extends Service
{
private boolean mRunning;
@Override
public void onCreate()
{
super.onCreate();
mRunning = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (!mRunning) {
mRunning = true;
// do something
}
return super.onStartCommand(intent, flags, startId);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With