判斷當前手機藍芽是否開啟
阿新 • • 發佈:2019-02-13
眾所周知藍芽是我們手機都有的一個功能
可以利用程式碼來實現管理藍芽的狀態
private BluetoothAdapter adapter;
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//接收藍芽狀態變化的廣播
String action = intent.getAction();
//發現藍芽裝置
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
String name= device.getName();
} else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
//可以在監聽到藍芽狀態是進行操作
switch (device.getBondState()){
case BluetoothDevice.BOND_BONDED:
//已經配對成功
break;
case BluetoothDevice.BOND_BONDING:
//正在連線
break;
case BluetoothDevice.BOND_NONE:
//取消連線
break;
default:
break;
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//藍芽連線裝置增加
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//藍芽連線狀態發生改變
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
//註冊
registerReceiver(receiver, filter);
//獲取藍芽介面卡
adapter = BluetoothAdapter.getDefaultAdapter();
boolean isenable = adapter.isEnabled();
System.out.println(isenable + "<-=-=-=-isenable");
//獲取藍芽是否可用
Toast.makeText(MainActivity.this, isenable + "<-=-=-=-isenable", Toast.LENGTH_SHORT).show();
if (!adapter.isEnabled()) {
//開啟藍芽
adapter.enable();
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//設定你自己的裝置可以被其他裝置搜尋的時間;最大3600
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(intent);
}
//藍芽裝置的地址
String address = adapter.getAddress();
String name = adapter.getName();
Log.d("藍芽", "name=" + name + " address=" + address);
//獲取通過藍芽已經連線的裝置
Set<BluetoothDevice> list = adapter.getBondedDevices();
if (list != null) {
for (BluetoothDevice device : list) {
//裝置名稱
String dname = device.getName();
}
}
//搜尋其他裝置
new Thread() {
@Override
public void run() {
super.run();
//正在搜尋狀態
if (adapter.isDiscovering()) {
adapter.cancelDiscovery();
}
//開始搜尋其他裝置;
adapter.startDiscovery();
}
}.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}