android 解决5.0以上不支持隐式启动服务
android 5.0以上不支持隐式启动服务,有常用的两种解决办法。
1 将隐式启动转换为显式启动,兼容编译sdk5.0以后版本
示例调用:
context.bindService(getExplicitIntent(mContext,new Intent(GPSBOARDCONTROL)), serviceConnection, Context.BIND_AUTO_CREATE);
转换代码
//将隐式启动转换为显式启动,兼容编译sdk5.0以后版本 public Intent getExplicitIntent(Context context,Intent implicitIntent){ PackageManager pm = context.getPackageManager(); List<ResolveInfo> resolveInfos = pm.queryIntentServices(implicitIntent, 0); if (resolveInfos == null || resolveInfos.size()!= 1) { return null; } Intent explicitIntent = null; ResolveInfo info = resolveInfos.get(0); String packageName = info.serviceInfo.packageName; String className = info.serviceInfo.name; ComponentName component = new ComponentName(packageName,className); explicitIntent = new Intent(implicitIntent); explicitIntent.setComponent(component); return explicitIntent; }
2 直接写上包名以及标志
Intent intent = new Intent("com.gnss.GNSSService"); intent.setAction(GPSBOARDCONTROL);//Service能够匹配的Action intent.setPackage("com.gnss.ssserver");//应用的包名 context.bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);
3 判断应用是否安装
//判断应用是否安装 public boolean isAppInstalled(Context context, String packageName) { final PackageManager packageManager = context.getPackageManager(); List<PackageInfo> pinfo = packageManager.getInstalledPackages(0); if (pinfo != null) { for (int i = 0; i < pinfo.size(); i++) { if (pinfo.get(i).packageName.contains(packageName)) { return true; } } } return false; }