Android L(API 21) – java.lang.IllegalArgumentException:Service Intent必须是显式的

Android新版本 – “Lollipop”(API 21)带来了不less变化,但是如果您希望将应用程序定位到该API,则会带来一些价格。

当我们开始将我们的应用程序调整到新的API时,我们遇到的第一个问题是IllegalArgumentException: Service Intent must be explicit

如果你遇到了这个问题,而且你实际上打算以明确的方式使用你的意图(这意味着当启动这个服务的时候,你只需要执行一个服务动作),下面是一个快速修复的例子,

 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; } 

这应该做到这一点。 请随时就这个新问题发表评论。

明确启动服务

 intent = new Intent(context, Service.class); 

或者用一个软件包来解决这个限制

 intent = new Intent("com.example.intent.ACTION"); intent.setPackage("com.example") 

更新 :新版本修复了这个问题! YouTubeAndroidPlayerApi-1.2.1

下载
参考