Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if service is running on Android?

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

like image 985
user2542715 Avatar asked Jul 11 '13 08:07

user2542715


2 Answers

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;
    }
like image 148
Maddy Avatar answered Sep 25 '22 03:09

Maddy


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);
    }
}
like image 44
jfs Avatar answered Sep 24 '22 03:09

jfs