我从 Android 开发开始,我试图在我的 android 手机和微控制器 (PSoC4BLE) 之间建立一个简单的蓝牙低功耗连接,以在其中一个微控制器特性中写入一个值。
正如我已经知道微控制器 MAC 以及服务和特征 UUID 一样,我只想在我的 android 应用程序打开后立即连接到微控制器而无需任何用户交互,并且当我按下按钮时,应用程序会写入一个值变成一个特征。
问题是当我运行它时我的应用程序崩溃了,在调整代码的情况下我让它工作,它没有连接到微控制器,我做错了什么?
这是代码:
public class MainActivity extends Activity {
// bluetooth variables
private BluetoothAdapter mBluetoothAdapter;
private BluetoothGatt mBluetoothGatt;
private BluetoothGattCharacteristic mMyCharacteristic;
private static final UUID CAR_SERVICE = UUID.fromString("00000000-0000-1000-1000-100000000000");
private static final UUID CAR_CHARACTERISTIC = UUID.fromString("00000000-0000-2000-2000-200000000000");
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize bluetooth adapter
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// create a device that represents the bluetooth device and assign it's known MAC address
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("00:A0:50:0F:13:1C");
// make the connection to the device
mBluetoothGatt = device.connectGatt(MainActivity.this, false, mGattCallback);
// get a reference to my user interface button
Button btnWrite = (Button)findViewById(R.id.BtnWrite);
// define the button behaviour
btnWrite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// create the characteristic variable
byte[] value = new byte[1];
value[0] = (byte) 1;
mMyCharacteristic.setValue(value);
// set the service UUID and the characteristic UUID
mMyCharacteristic = mBluetoothGatt.getService(CAR_SERVICE).getCharacteristic(CAR_CHARACTERISTIC);
// write the characteristic en the device
mBluetoothGatt.writeCharacteristic(mMyCharacteristic);
}
});
}
}
更新 1 最后我得到一个 logcat,它说:
java.lang.RuntimeException: 无法启动活动 ComponentInfo{lenovo.car/lenovo.car.MainActivity}: java.lang.NullPointerException: 尝试调用虚拟方法 'android.bluetooth.BluetoothDevice android.bluetooth.BluetoothAdapter.getRemoteDevice(java. lang.String)' 在空对象引用上 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'android.bluetooth.BluetoothDevice android.bluetooth.BluetoothAdapter.getRemoteDevice(java.lang.String)'
请问,有什么想法吗?我发现应用程序崩溃
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("00:A0:50:0F:13:1C");