第一次請求BLUETOOTH_ADMIN
權限。
然後,讓您的設備可發現:
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
然後創建一個廣播接收器從系統中收聽到行動:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
//Found, add to a device list
}
}
};
,並開始註冊這個BoardcastReceiver搜索設備:
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
設備來自的BroadcastReceiver到一個列表後,從列表中createBond()
這種選擇您的設備:
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
然後使用上面的代碼與綁定設備進行管理。
您是否要求BLUETOOTH_ADMIN權限? – nhoxbypass
是的,我請求 – Kirchhoff1415
你有沒有嘗試過:https://stackoverflow.com/questions/14228289/android-pair-devices-via-bluetooth-programmatically – nhoxbypass