安卓L(API 21)- java.lang.IllegalArgumentException: Service Intent必须是明确的。

3

安卓新版本 - "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;
    }

那就这样吧。如果您对这个新问题有任何其他见解,请随意发表评论。

5
回答自己的问题是可以的,但请将答案放在答案区域。 - weston
1
要求明确的服务意图的整个目的是确保您实际上启动了您认为的服务(而不是具有相同隐式过滤器的恶意服务)。虽然这种方法解决了表面问题,但并没有解决潜在问题。事实上,它使调试变得更加困难,因为如果存在多个服务,则您的方法将返回null,这意味着基于其他应用程序的安装/卸载时间,您的应用程序可能会停止工作(没有服务被启动)。 - ianhanniballake
可能是[Google In-App计费,IllegalArgumentException:Service Intent必须是显式的,在升级到Android L Dev Preview之后]的重复问题(https://dev59.com/p2Af5IYBdhLWcg3wmzlL) - regisd
1个回答

5

显式启动服务

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

或者在隐式意图中明确提供包名

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接