这是我搜索服务的方法
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)
使用这种方法是否聪明。我想查找服务是否正在运行。如果没有,我手动运行它。