检查服务是运行在Android上?Android

由网友(不归路。)分享简介:→要检查服务是否运行升写这篇code l want to check if a service is runningl wrote this codepublic class startServiceOrNo {public static void startServiceIfItsNotRuning(Clas...

→要检查服务是否运行升写这篇code

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));
}

和使用它 startServiceOrNo.startServiceIfItsNotRuning(OfflineChopsMonitor.class,这一点)

and use it startServiceOrNo.startServiceIfItsNotRuning(OfflineChopsMonitor.class,this)

如果l检查服务从一类的工作,但如果从不同的L类检查同样的服务,其检查不工作

if l check service from one class its work, but if l check same service from different class, its check don't work

推荐答案

为什么你不让服务本身可以认识到这一点?

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);
    }
}
阅读全文

相关推荐

最新文章