解决Service Intent must be explicit错误

来源:互联网 发布:网络教育学历学费贵 编辑:程序博客网 时间:2024/05/18 23:53

在启动或绑定Service的时候,在一个手机上使用的好好的,而换了一个手机则出现Service Intent must be explicit错误,导致整个程序崩溃。这个错误多半是系统版本不同而引起的。

Android5.0以上的系统启动或绑定Service的时候,必须是显性启动,而通常我们直接使用Action来启动。在Android5.0及以上的手机中,如还使用此方式的话,就会出现Service Intent must be explicit的错误。


使用显性启动即可解决。


隐性启动:

        Intent intent = new Intent(service_action_name);//        startService(intent);        bindService(intent, conn, Service.BIND_AUTO_CREATE);        

显性启动方法一:

        Intent intent = new Intent(service_action_name);        intent.setPackage(service_packageName);//        startService(intent);        bindService(service, conn, Service.BIND_AUTO_CREATE);


显性启动方法二:

1.增加以下方法

/***      * Android L (lollipop, API 21) introduced a new problem when trying to invoke implicit intent,      * "java.lang.IllegalArgumentException: Service Intent must be explicit"      *      * If you are using an implicit intent, and know only 1 target would answer this intent,      * This method will help you turn the implicit intent into the explicit form.      *      * Inspired from SO answer: http://stackoverflow.com/a/26318757/1446466      * @param context      * @param implicitIntent - The original implicit intent      * @return Explicit Intent created from the implicit original intent      */      public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {          // Retrieve all services that can match the 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 create ComponentName          ResolveInfo serviceInfo = resolveInfo.get(0);          String packageName = serviceInfo.serviceInfo.packageName;          String className = serviceInfo.serviceInfo.name;          ComponentName component = new ComponentName(packageName, className);             // Create a new intent. Use the old one for extras and such reuse          Intent explicitIntent = new Intent(implicitIntent);             // Set the component to be explicit          explicitIntent.setComponent(component);             return explicitIntent;      }  

2.使用createExplicitFromImplicitIntent方法来实例化Intent

        Intent intent = new Intent(service_action_name);        Intent intent2 = new Intent(createExplicitFromImplicitIntent(this,intent));//        startService(intent2);        bindService(intent2, conn, Service.BIND_AUTO_CREATE);




0 0