BluetoothHeadsetClient:无法使用Intent绑定到蓝牙耳机客户端服务

时间:2015-07-27 15:25:43

标签: android reflection bluetooth android-bluetooth android-framework

我想使用BluetoothHeadsetClient。为了使用这个隐藏的SDK代码我使用反射。

我想打电话

mBluetoothAdapter.getProfileProxy(this, mHeadsetProfileListener, BluetoothProfile.HEADSET_CLIENT);

但BluetoothProfile.HEADSET_CLIENT隐藏在BluetoothProfile.java中。为了解决这个问题,我运行以下代码

protected BluetoothProfile.ServiceListener mHeadsetProfileListener = new  BluetoothProfile.ServiceListener()
{
    @Override
    public void onServiceDisconnected(int profile) {            

    }

    @Override
    public void onServiceConnected(int profile, BluetoothProfile proxy)
    {

        mlisten = mHeadsetProfileListener;
        mHeadSetCleintObj = proxy;

        // reflection for getting the HEADSET_CLIENT type
        try {

            Class classRef = Class.forName("android.bluetooth.BluetoothProfile");
            Field field = classRef.getField("HEADSET_CLIENT");                
            if(profile == BluetoothProfile.HEADSET ) {
                mBluetoothAdapter.getProfileProxy(getApplicationContext(), mHeadsetProfileListener, field.getInt(proxy));
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }

        mBluetoothHeadset.getConnectedDevices();

    }
};


@Override
public void onDestroy() {
    unregisterReceiver(mPairReceiver);

    super.onDestroy();
}

field.getInt(proxy)value == 16 - >我想要的是BluetoothProfile.HEADSET_CLIENT。但是当我运行

mBluetoothAdapter.getProfileProxy(getApplicationContext(), mHeadsetProfileListener, field.getInt(proxy));

我看到以下错误

E/BluetoothHeadsetClient﹕ Could not bind to Bluetooth Headset Client Service with Intent { act=android.bluetooth.IBluetoothHeadsetClient }

你知道如何解决这类错误吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

我从robolectric找到了一个API,它使API的隐藏部分可见。您可以将它与build.gradle中提供的范围一起使用。

provided 'org.robolectric:android-all:5.0.0_r2-robolectric-1'

不幸的是,我也无法获得工作代理,但调试到BluetoothHeadsetClient表明doBind已成功调用。就我而言,从不调用来自BluetoothProfile.ServiceListener的onServiceConnected,因此"工作"代理永远不会返回我的活动。

答案 1 :(得分:0)

问题可能是从mBluetoothAdapter.getProfileProxy(getApplicationContext(), mHeadsetProfileListener, field.getInt(proxy));内部调用BluetoothProfile.ServiceListener.onServiceConnected

以下作品:

try {
  final int Bluetooth_Profile_HEADSET_CLIENT = 
      (int) BluetoothProfile.class.getField("HEADSET_CLIENT").get(null);

  BluetoothProfile.ServiceListener mProfileListener = 
     new BluetoothProfile.ServiceListener() {
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
          if (profile == Bluetooth_Profile_HEADSET_CLIENT) {
              //proxy is BluetoothHeadsetClient
          }
       }

       public void onServiceDisconnected(int profile) {

       }
 };

  BluetoothAdapter
          .getDefaultAdapter()
          .getProfileProxy(this, mProfileListener, Bluetooth_Profile_HEADSET_CLIENT);
}catch(Exception ex) {}