bindService失败的解决办法

在android5.0以下版本:

 Intent i = new Intent(Consts.MY_SERVICE);
 boolean bindResult =
        mContext.bindService(i, conn, Activity.BIND_AUTO_CREATE);

是可以直接绑定成功的
但是5.0以上的Android手机则会报错:

java.lang.IllegalArgumentException: Service Intent must be explicit

尝试一:用以下两种方式处理Intent

  public static Intent getExplicitIntent(Context context, Intent implicitIntent) {
    // Retrieve all services that can match the given intent
    PackageManager pm = context.getPackageManager();
    List 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;
  }

或者

intent.setPackage(Consts.SERVICE_PACKAGE_NAME);

则程序不会报错,但是bindService 返回 false ,也就是说没有bind成功
并且 ServiceConnection 的:onServiceDisconnectedonServiceConnected 不会得到调用。

尝试二:在 AndroidManifest 添加service的声明:

<service android:name="com.test.service.MyService">
  <intent-filter>
    <action android:name="com.test.service.MyService"/>
  intent-filter>
service>

结果还是失败,又进行如下尝试:

尝试三:getApplicationContext

mContext.getApplicationContext 然后在进行bind

mContext.getApplicationContext().bindService(i, conn, Activity.BIND_AUTO_CREATE);

依然失败 - -!

最终解决方法

因为本服务是用aidl方式提供的
最后查看手机应用,将提供者app设置允许所有权限,信任该应用,允许关联启动之后,程序终于跑通了! 华为荣耀6Plus,你够狠!

你可能感兴趣的:(历史文章)