これは、サービスを検索するための私の方法です
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)
この方法を使用するのは賢いですか。サービスが実行されているかどうかを確認したい。そうでない場合は、手動で実行します。