码迷,mamicode.com
首页 > 编程语言 > 详细

java.lang.IllegalArgumentException: Service Intent must be explicit: Intent

时间:2016-07-13 19:43:21      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

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


java.lang.IllegalArgumentException: Service Intent must be explicit: Intent

标签:

原文地址:http://www.cnblogs.com/yidan621/p/5667299.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!