use*_*715 13 android android-service
我想检查服务是否正在运行l写了这段代码
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));
}
Run Code Online (Sandbox Code Playgroud)
并使用它startServiceOrNo.startServiceIfItsNotRuning(OfflineChopsMonitor.class,this)
如果我检查来自一个类的服务它的工作,但如果我检查来自不同类的相同服务,它的检查不起作用
Mad*_*ddy 33
1.)在Activity类中:
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;
}
Run Code Online (Sandbox Code Playgroud)
2.)在非活动类(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;
}
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 31
你为什么不让服务本身弄明白呢?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Elt*_*sta 10
我在活动中使用以下内容:
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;
}
Run Code Online (Sandbox Code Playgroud)