如何将应用程序连接到蓝牙耳机

时间:2015-03-03 13:48:37

标签: android bluetooth

我正在尝试将我的应用程序连接到蓝牙耳机,但我收到mProfileListener的错误。我不知道在哪里以及如何申报mProfileListener。  这是我的代码:

// Get the default adapter
   BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


// Establish connection to the proxy.
   mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.HEADSET);

   private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
       public void onServiceConnected(int profile, BluetoothProfile proxy) {
           if (profile == BluetoothProfile.HEADSET) {
               mBluetoothHeadset = (BluetoothHeadset) proxy;
               Log.d("TAGP","BLuetooth Headset: "+mBluetoothHeadset);
               Log.d("TAGP ","Proxy: "+proxy);
           }
       }
       public void onServiceDisconnected(int profile) {
           if (profile == BluetoothProfile.HEADSET) {
               mBluetoothHeadset = null;
           }
       }
   };

   // ... call functions on mBluetoothHeadset

   // Close proxy connection after use.
   mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);

}

1 个答案:

答案 0 :(得分:0)

您可以在类范围中声明mProfileListener实例,如下所示:

private BluetoothProfile.ServiceListener mProfileListener;

然后在你的“连接”蓝牙堆栈方法中,你可以像你的代码一样初始化这个mProfileListener实例。