0

这是我搜索服务的方法

public static boolean isServiceRunning(String serviceClassName, Context context) {
        ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager == null) {
            return false;
        }

        List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (services.isEmpty()) {
            return false;
        }

        for (RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(serviceClassName)) {
                return true;
            }
        }

        return false;
    }

但有时我会收到此错误:

java.lang.RuntimeException: Unable to instantiate receiver com.xx.xx.receiver.BluetoothReceiver: java.lang.ClassNotFoundException: com.xx.xx.receiver.BluetoothReceiver
01-06 17:39:38.990: E/AndroidRuntime(7259):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2111)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at android.app.ActivityThread.access$1500(ActivityThread.java:127)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at android.os.Looper.loop(Looper.java:137)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at android.app.ActivityThread.main(ActivityThread.java:4511)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at java.lang.reflect.Method.invokeNative(Native Method)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at java.lang.reflect.Method.invoke(Method.java:511)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at dalvik.system.NativeStart.main(Native Method)
01-06 17:39:38.990: E/AndroidRuntime(7259): Caused by: java.lang.ClassNotFoundException: com.xx.x.receiver.BluetoothReceiver
01-06 17:39:38.990: E/AndroidRuntime(7259):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
01-06 17:39:38.990: E/AndroidRuntime(7259):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2106)

使用这种方法是否聪明。我想查找服务是否正在运行。如果没有,我手动运行它。

4

1 回答 1

1

但有时我会收到此错误:

该错误似乎与您显示的代码无关。

我想查找服务是否正在运行。如果没有,我手动运行它。

只需启动服务。如果它已经在运行,什么都不会发生,只是会onStartCommand()再次调用它。如果它尚未运行,将创建一个服务实例,用 调用onCreate(),然后用 调用onStartCommand()

于 2013-01-06T18:00:37.113 回答