【问题标题】:Android L (API 21) - java.lang.IllegalArgumentException: Service Intent must be explicitAndroid L (API 21) - java.lang.IllegalArgumentException: Service Intent must be explicit
【发布时间】: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


【解决方案1】:

显式启动服务

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

或以隐式意图显式提供包

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

【讨论】:

    猜你喜欢
    • 2015-01-26
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2014-10-25
    • 1970-01-01
    • 2020-06-14
    相关资源
    最近更新 更多