start Service by service class - Android android.app

Android examples for android.app:Service

Description

start Service by service class

Demo Code


import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.view.View;

public class Main{
    private static final String TAG = PublicUtils.class.getSimpleName();
    //w  ww  . j a  va 2 s.co  m
    public static void startService(Activity act,
            Class<? extends Service> serviceClass) {
        if (!isServiceRunning(act, serviceClass)) {
            Logger.d(TAG, serviceClass.getName() + " is not running");
            act.startService(new Intent(act, serviceClass));
        } else {
            Logger.d(TAG, serviceClass.getName() + " is running");
        }
    }
    
    public static boolean isServiceRunning(Activity act,
            Class<? extends Service> serviceClass) {
        ActivityManager manager = (ActivityManager) act
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo rsinfo : manager
                .getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName()
                    .equals(rsinfo.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}

Related Tutorials