【发布时间】:2015-01-26 18:55:44
【问题描述】:
Android 新版本 - “Lollipop” (API 21) 带来了很多变化,但如果您希望将应用程序定位到该 API,则需要付出一些代价。
当我们开始使我们的应用适应新的 API 时,我们遇到的第一个问题是IllegalArgumentException: Service Intent must be explicit
如果您遇到了问题,并且您实际上打算以显式方式使用您的意图(这意味着在启动服务时您期望恰好命中 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;
}
应该这样做。请随时发表评论以获取有关此新问题的更多见解。
【问题讨论】:
-
回答你自己的问题就好了。但是把答案放在答案区。
-
要求显式服务意图的全部意义在于确保您真正启动了您认为自己是的服务(而不是碰巧具有相同隐式过滤器的恶意服务)。虽然这种方法解决了表面问题,但它并没有解决根本问题。事实上,如果存在多个服务,您的方法会返回
null,这使得调试变得更加困难,这意味着您的应用可能会根据安装/卸载其他应用的时间停止工作(没有服务启动)。
标签: android android-intent android-service android-5.0-lollipop