2012-04-30 51 views
2

我有一个应用程序在后台运行,需要知道何时连接了特定的蓝牙设备。 可以说我希望我的应用在背景上运行,并在设备连接到车载蓝牙时执行某些操作。 谢谢!如何知道特定的蓝牙设备正在连接?

+0

特定设备例如一个确切的独特装置或特定于装置等级的装置。耳机还是车载信息娱乐系统? –

+0

你在车上的特定之一。我会让我的应用程序让你从配对列表中选择至少一个蓝牙设备,你的手机具有的是你的车载蓝牙,而不是当我的手机连接到手机时想做些什么。希望我清楚:) – roiberg

回答

2

下面的代码给予其所连接

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

代码装置:

public void onCreate() { 
    ... 
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); 
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); 
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); 
    this.registerReceiver(mReceiver, filter1); 
    this.registerReceiver(mReceiver, filter2); 
    this.registerReceiver(mReceiver, filter3); 
} 

//The BroadcastReceiver that listens for bluetooth broadcasts 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      ... //Device found 
     } 
     else if (BluetoothAdapter.ACTION_ACL_CONNECTED.equals(action)) { 
      ... //Device is now connected 
     } 
     else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
      ... //Done searching 
     } 
     else if (BluetoothAdapter.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { 
      ... //Device is about to disconnect 
     } 
     else if (BluetoothAdapter.ACTION_ACL_DISCONNECTED.equals(action)) { 
      ... //Device has disconnected 
     }   
    } 
};