unbindService问题

mac2024-05-13  32

Service是Android四大组件之一

相关操作有

//启动服务 public ComponentName startService(Intent service); //停止服务 public boolean stopService(Intent name); //绑定服务 public boolean bindService(Intent service, ServiceConnection conn,int flags); //解绑服务 public void unbindService(ServiceConnection conn);

当没有bindService时,先去执行unbindService的话会报错:

Service not registered:。。。

网上一般的做法是设置一个布尔变量,当绑定服务成功时,设置为true,之后解绑时进行判断。。。

下面是通过反射获取系统相关信息进行判定的方法

解决unbindService异常

try { Field mPackageInfoField = getBaseContext().getClass().getDeclaredField("mPackageInfo"); mPackageInfoField.setAccessible(true); Class<?> LoadedApkClass = Class.forName("android.app.LoadedApk"); Field mServicesField = LoadedApkClass.getDeclaredField("mServices"); mServicesField.setAccessible(true); ArrayMap<Context, Object> mServices = (ArrayMap<Context, Object>) mServicesField.get(mPackageInfoField.get(getBaseContext())); ArrayMap<Object, Object> map = (ArrayMap<Object, Object>) mServices.get(this); //解绑之前进行判定 if (map != null && map.get(this) != null) { unbindService(this); } } catch (Exception e) { System.out.println(e.toString()); }

其中9.0及以上系统需要使用下面代码绕过Android P禁用隐藏API的限制 在attachBaseContext()中调用

void HideApi() { try { if (SDK_INT >= Build.VERSION_CODES.P) { Class<?> VMRuntimeClass = Class.forName("dalvik.system.VMRuntime"); Method getRuntimeMethod = VMRuntimeClass.getDeclaredMethod("getRuntime"); Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class); Method setHiddenApiExemptionsMethod = (Method) getDeclaredMethod.invoke(VMRuntimeClass, "setHiddenApiExemptions", new Class[]{String[].class}); Object runtimeObject = getRuntimeMethod.invoke(null); if (setHiddenApiExemptionsMethod != null && runtimeObject != null) { setHiddenApiExemptionsMethod.invoke(runtimeObject, new Object[]{new String[]{"L"}}); } } } catch (Exception e) { System.out.println(e.toString()); } }
最新回复(0)