解决ServiceIntent must be explicit

来源:互联网 发布:大学生应知相关法律 编辑:程序博客网 时间:2024/06/18 04:24


1       目的

解决Android 5.0中出现的警告:Service Intent must be explicit。

 

使用Service的时需要采用隐私启动的方式,从Android 5.0后,其中有个特性就是Service Intent  must beexplitict,service必须采用显示方式启动。

据官网https://developer.android.com/guide/components/intents-filters.html#Types介绍:

注意:为了确保应用的安全性,启动 Service 时,请始终使用显式 Intent,且不要为服务声明 Intent 过滤器。使用隐式 Intent 启动服务存在安全隐患,因为您无法确定哪些服务将响应 Intent,且用户无法看到哪些服务已启动。从 Android 5.0(API 级别 21)开始,如果使用隐式 Intent 调用 bindService(),系统会引发异常。

2       解决方法

//方法1:final Intent intent = new Intent();intent.setAction(SERVICE_ACTION_NAME); intent.setPackage(SERVICE_PACKAGE_NAME);bindService(intent, conn,Context.BIND_AUTO_CREATE); //方法2://调用createExplicitFromImplicitIntent,传入隐式Intent,得到显示Intent,//通过显示Intent启动ServiceIntentintent = new Intent(SERVICE_ACTION_NAME);finalIntent eintent = new Intent(createExplicitFromImplicitIntent(mContext,intent));mContext.bindService(eintent,scc,Service.BIND_AUTO_CREATE);      public static IntentcreateExplicitFromImplicitIntent(Context context, Intent implicitIntent) {        // Retrieve all services that can matchthe given intent        PackageManager pm =context.getPackageManager();        List<ResolveInfo> resolveInfo =pm.queryIntentServices(implicitIntent, 0);         // Make sure only one match was found        if (resolveInfo == null ||resolveInfo.size() != 1) {            return null;        }         // Get component info and createComponentName        ResolveInfo serviceInfo =resolveInfo.get(0);        String packageName =serviceInfo.serviceInfo.packageName;        String className =serviceInfo.serviceInfo.name;        ComponentName component = newComponentName(packageName, className);         // Create a new intent. Use the old onefor extras and such reuse        Intent explicitIntent = newIntent(implicitIntent);         // Set the component to be explicit        explicitIntent.setComponent(component);         return explicitIntent;    }


 

0 0
原创粉丝点击