Android 新版本 - “Lollipop”(API 21) 带来了相当多的变化,但如果您希望将您的应用程序定位到该 API,它会带来一些代价。
当我们开始调整我们的应用以适应新的 API 时,我们遇到的第一个问题是 IllegalArgumentException: Service Intent must be explicit
如果您遇到了这个问题,并且您实际上打算以显式方式使用您的 Intent (这意味着在启动服务时您期望恰好命中 1 个服务操作),这里有一个转换为隐式的快速修复 -->明确的:
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 显式提供包
intent = new Intent("com.example.intent.ACTION");
intent.setPackage("com.example")
关于安卓 L (API 21) - java.lang.IllegalArgumentException : Service Intent must be explicit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27183164/