1

私は Android の開発から始めており、Android フォンとマイクロコントローラー (PSoC4BLE) の間に単純な Bluetooth Low Energy 接続を作成して、マイクロコントローラーの特性の 1 つに値を書き込もうとしています。

マイクロコントローラーの 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: Unable to start activity ComponentInfo{lenovo.car/lenovo.car.MainActivity}: java.lang.NullPointerException: 仮想メソッド 'android.bluetooth.BluetoothDevice android.bluetooth.BluetoothAdapter.getRemoteDevice(java. lang.String)' が null オブジェクト参照で発生しました原因: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothDevice android.bluetooth.BluetoothAdapter.getRemoteDevice(java.lang.String)' on null object reference

お願いします、何かアイデアはありますか?アプリがクラッシュすることがわかりました final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("00:A0:50:0F:13:1C");

4

1 に答える 1