这个问题已经在这里有一个答案:
我想使用蓝牙我在清单中加入这个
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
接下来我这样做:
String uid = "0000111f-0000-1000-8000-00805f9b34fb";
UUID uuid = UUID.fromString(uid.toUpperCase()); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
但在这儿 ;
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
我有这样的错误
va.lang.NullPointerException:尝试调用虚拟方法“android.bluetooth.BluetoothSocket上一个空对象引用
您mmDevice
不正确实例化,这就是为什么你要NullPointerException
。简单nullcheck防止这种情况:if(mmDevice!=null)
。
private void checkPermissions() {
ArrayList<String> permissions = ArrayList();
if (checkSelfPermission(applicationContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
permissions.add(ACCESS_FINE_LOCATION);
if (checkSelfPermission(applicationContext, BLUETOOTH) != PackageManager.PERMISSION_GRANTED)
permissions.add(BLUETOOTH);
if (checkSelfPermission(applicationContext, BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED)
permissions.add(BLUETOOTH_ADMIN);
if (permissions.isNotEmpty())
requestPermissions(permissions.toTypedArray(), REQUEST_PERMISSIONS);
else {
startBluetoothService();
}
}
BluetoothManager mBluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = mBluetoothManager.adapter;
//check if bluetooth is enabled
if (mBluetoothAdapter.isEnabled){
mBluetoothAdapter.startDiscovery();
//make sure you register this receiver to properly receive callbacks
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
doThingsWithDevice();
}
}
}
};
或者,如果你知道设备address
,您可以使用mBluetoothManager.adapter.getRemoteDevice("deviceAddress")
方法。