我試圖用廣播接收器捕獲藍牙狀態更改。Android廣播接收器藍牙事件捕獲
我的清單:
<uses-permission android:name="android.permission.BLUETOOTH" />
<application>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BluetoothBroadcastReceiver"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
<action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
</receiver>
</application>
接收onReceive
方法:
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("BroadcastActions", "Action "+action+"received");
int state;
BluetoothDevice bluetoothDevice;
switch(action)
{
case BluetoothAdapter.ACTION_STATE_CHANGED:
state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
if (state == BluetoothAdapter.STATE_OFF)
{
Toast.makeText(context, "Bluetooth is off", Toast.LENGTH_SHORT).show();
Log.d("BroadcastActions", "Bluetooth is off");
}
else if (state == BluetoothAdapter.STATE_TURNING_OFF)
{
Toast.makeText(context, "Bluetooth is turning off", Toast.LENGTH_SHORT).show();
Log.d("BroadcastActions", "Bluetooth is turning off");
}
else if(state == BluetoothAdapter.STATE_ON)
{
Log.d("BroadcastActions", "Bluetooth is on");
}
break;
case BluetoothDevice.ACTION_ACL_CONNECTED:
bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context, "Connected to "+bluetoothDevice.getName(),
Toast.LENGTH_SHORT).show();
Log.d("BroadcastActions", "Connected to "+bluetoothDevice.getName());
break;
case BluetoothDevice.ACTION_ACL_DISCONNECTED:
bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context, "Disconnected from "+bluetoothDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
}
}
我啓動應用程序,然後按Home鍵最小化。轉到設置並打開藍牙,但沒有任何反應。雖然我期望吐司和logcat消息。這裏有什麼問題?
不確定,這可能是因爲廣播註冊的方式。我會嘗試在服務器上註冊,而不是在運行時註冊,看看是否有改變。 –
@VladimirLichonos是的,我試圖添加服務,我註冊接收器。它看起來像這樣'IntentFilter fltr = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); fltr.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); fltr.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); fltr.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(brecv,fltr);'其中'brecv'是CustomBluetoothReceiver的一個對象。沒有任何變化。 –
你是否在某個地方開始服務? – osayilgan