解决Service Intent must be explicit错误

在启动或绑定Service的时候,在一个手机上使用的好好的,而换了一个手机则出现Service Intent must be explicit错误,导致整个程序崩溃。这个错误多半是系统版本不同而引起的。

Android5.0以上的系统启动或绑定Service的时候,必须是显性启动,而通常我们直接使用Action来启动。在Android5.0及以上的手机中,如还使用此方式的话,就会出现Service Intent must be explicit的错误。


使用显性启动即可解决。


隐性启动:

        Intent intent = new Intent(service_action_name);
//        startService(intent);
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
        

显性启动方法一:

        Intent intent = new Intent(service_action_name);
        intent.setPackage(service_packageName);
//        startService(intent);
        bindService(service, conn, Service.BIND_AUTO_CREATE);


显性启动方法二:

1.增加以下方法

/*** 
     * Android L (lollipop, API 21) introduced a new problem when trying to invoke implicit intent, 
     * "java.lang.IllegalArgumentException: Service Intent must be explicit" 
     * 
     * If you are using an implicit intent, and know only 1 target would answer this intent, 
     * This method will help you turn the implicit intent into the explicit form. 
     * 
     * Inspired from SO answer: http://stackoverflow.com/a/26318757/1446466 
     * @param context 
     * @param implicitIntent - The original implicit intent 
     * @return Explicit Intent created from the implicit original intent 
     */  
    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;  
    }  

2.使用createExplicitFromImplicitIntent方法来实例化Intent

        Intent intent = new Intent(service_action_name);
        Intent intent2 = new Intent(createExplicitFromImplicitIntent(this,intent));
//        startService(intent2);
        bindService(intent2, conn, Service.BIND_AUTO_CREATE);




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值