我的android studio在清单中有蓝牙权限, 这是我的代码:
private BluetoothManager bluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private static final long SCAN_PERIOD = 1000000; //10 seconds 搜尋頻率 1S:1000
private Handler mHandler;
private NotificationManager notificationManager;
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//推播接收媒介
mHandler = new Handler();
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
//檢查是否支援藍芽
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "硬體不支援", Toast.LENGTH_SHORT).show();
}
// 檢查手機是否開啟藍芽裝置
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Toast.makeText(this, "請開啟藍芽裝置", Toast.LENGTH_SHORT).show();
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
} else {
scanLeDevice(true);
}
};
@Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
//判斷是否有重新申請推播的必要
//BEACON 取其名稱
notificationManager.cancelAll();//清理舊的通知資料
prb=device.getName().toString();
noti.addJavascriptInterface(new JsOperation(),"test1");
}
};
};
我测试了mBluetoothAdapter.startLeScan(mLeScanCallback);, 结果是真的,但不能进入onLeScan, 我很确定BLE设备有标志。 请帮帮我。
答案 0 :(得分:0)
除了android.permission.BLUETOOTH之外,你还需要清单中的android.permission.ACCESS_COARSE_LOCATION。确保使用权限API提示用户获取BLUETOOTH权限。
在发现设备之前,您的代码不会进入aria-hidden="true"
。使用nRF Connect验证您周围是否有可发现的蓝牙LE设备。