zoukankan      html  css  js  c++  java
  • java.lang.IllegalArgumentException: Service Intent must be explicit: Intent

    在Activity中启动Service的时候报错: 服务意图必须是显性声明。 这是为了防止造成冲突(i.e. 有多个Service用同样的intent-filter的情况)

    这是Android 5.0 (Lollipop) 之后的规定。 不能用包名的方式定义Service Intent, 而要用显性声明:

    new Intent(context, xxxService.class);

    如果一定要用隐性声明,可以用下面的方法(Stackoverflow上的回答)

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


  • 相关阅读:
    【BZOJ4566】[HAOI2016]找相同字符
    【BZOJ3238】[AHOI2013]差异
    【BZOJ4698】[SDOI2008]Sandy的卡片
    后缀数组(SA)总结
    【HDU3117】Fibonacci Numbers
    线性常系数齐次递推总结
    【HDU4565】So Easy!
    【BZOJ3144】[HNOI2013]切糕
    【BZOJ1070】[SCOI2007]修车
    【LOJ6433】【PKUSC2018】最大前缀和
  • 原文地址:https://www.cnblogs.com/yidan621/p/5667299.html
Copyright © 2011-2022 走看看