Service Intent must be explicit

来源:互联网 发布:淘宝的旺旺名怎么修改 编辑:程序博客网 时间:2024/04/29 14:54
Android5.0中service的intent一定要显性声明

[java] view plain copy
  1. final Intent intent = new Intent(this,BindService.class);  
  2. bindService(intent,coon,Service.BIND_AUTO_CREATE)  

可以将隐性调用变成显性调用。先定义一个函数:

[java] view plain copy
  1. /*** 
  2.      * Android L (lollipop, API 21) introduced a new problem when trying to invoke implicit intent, 
  3.      * "java.lang.IllegalArgumentException: Service Intent must be explicit" 
  4.      * 
  5.      * If you are using an implicit intent, and know only 1 target would answer this intent, 
  6.      * This method will help you turn the implicit intent into the explicit form. 
  7.      * 
  8.      * Inspired from SO answer: http://stackoverflow.com/a/26318757/1446466 
  9.      * @param context 
  10.      * @param implicitIntent - The original implicit intent 
  11.      * @return Explicit Intent created from the implicit original intent 
  12.      */  
  13.     public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {  
  14.         // Retrieve all services that can match the given intent  
  15.         PackageManager pm = context.getPackageManager();  
  16.         List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);  
  17.    
  18.         // Make sure only one match was found  
  19.         if (resolveInfo == null || resolveInfo.size() != 1) {  
  20.             return null;  
  21.         }  
  22.    
  23.         // Get component info and create ComponentName  
  24.         ResolveInfo serviceInfo = resolveInfo.get(0);  
  25.         String packageName = serviceInfo.serviceInfo.packageName;  
  26.         String className = serviceInfo.serviceInfo.name;  
  27.         ComponentName component = new ComponentName(packageName, className);  
  28.    
  29.         // Create a new intent. Use the old one for extras and such reuse  
  30.         Intent explicitIntent = new Intent(implicitIntent);  
  31.    
  32.         // Set the component to be explicit  
  33.         explicitIntent.setComponent(component);  
  34.    
  35.         return explicitIntent;  
  36.     }  

然后调用

[java] view plain copy
  1. final Intent intent = new Intent();  
  2. intent.setAction("com.example.user.firstapp.FIRST_SERVICE");  
  3. final Intent eintent = new Intent(createExplicitFromImplicitIntent(this,intent));  
  4. bindService(eintent,conn, Service.BIND_AUTO_CREATE);