2012-04-09 142 views
1

我想構建一個小應用程序,它可以識別任何藍牙耳機連接和斷開連接並將其寫入日誌文件。檢測藍牙連接(android sdk ICS)

我試圖使用android SDK example來檢測藍牙連接,但它不工作。 當我的應用程序正在加載時,我正在調用OnServiceConnected,就是這樣。當我通過藍牙耳機連接和斷開連接時,沒有其他的OnServiceConnected或OnServiceDisconnected調用(我累了多一次)。

我寫了OnCreate函數中的所有代碼。

也許問題是與Android 4? 還是別的嗎?

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

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

private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() { 
    public void onServiceConnected(int profile, BluetoothProfile proxy) { 
     // Write to log - OnServiceConnected 
    } 
    public void onServiceDisconnected(int profile) { 
     // Write to log - OnServiceDisconnected 
    } 
}; 

回答

3

好的,找到它了。

這裏是:

getApplicationContext().registerReceiver(receiver, 
        new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED)); 
getApplicationContext().registerReceiver(receiver, 
        new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)); 

private final BroadcastReceiver mReceiver = new BroadcastReceiver() 
    { 
     @Override 
     public void onReceive(Context context, Intent intent) 
     { 
      if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) 
      { 
       // LOG - Connected 
      } 
      else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) 
      { 
       // LOG - Disconnected 
      } 
     } 
    } 
+1

你的答案是正確的我依然會增加你的答案需要藍牙權限添加到Android清單。 '' – alexm 2014-04-09 14:00:30

+0

'action'是什麼? – msysmilu 2015-09-29 14:38:35

+0

'action'是'String action = intent.getAction();' – msysmilu 2015-09-29 14:45:05