この記事はAndroidスマホ用のアプリ開発の中で、
今後の開発で再使用性が高いと思われるコーディングをまとめたものです。
Javaの開発経験、XML構文規則、Androidのアプリ開発経験がある方を対象としています。
Androidのアプリ開発でお役にたててれば、嬉しいです。
(これからAndroidのアプリ開発やJavaでの開発を始めたい方への案内は、記事の最後で紹介します)
Android13で非推奨になったBluetoothGatt.writeCharacteristicに対応する
ポイント
BLEのGATT通信でキャラクタリスティックに書き込むwriteCharacteristicですが、Andorid13で非推奨となりました。
今回は、非推奨になったwriteCharacteristicをAndroid13以降に対応する実装方法を紹介いたします。
BluetoothGatt.writeCharacteristic
BluetoothGatt.writeCharacteristic
GATT通信で使用するBluetoothGattのgetServiceでBluetoothGattCharacteristicを取得します。
BluetoothGattCharacteristicに対して、writeCharacteristicで値を書き込みます。
Android13以降では、writeCharacteristicに値を直接設定できるよう、引数が追加されました。
Android12までの実装
BluetoothGattCharacteristicに値をセットして、writeCharacteristicで値を書き込みます。
:
public void writeCharacteristic(UUID uuid_service, UUID uuid_characteristic, String string) {
if (bluetoothGatt != null) {
BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGatt.getService(uuid_service).getCharacteristic(uuid_characteristic);
bluetoothGattCharacteristic.setValue(string);
bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
}
}
:Android13以降の実装
BluetoothGattCharacteristicに値をセットしないで、writeCharacteristicで値を指定して書き込みます。
Android112以下に対応する場合、Build.VERSION.SDK_INTで分岐させて、それぞれ処理します。
:
public void writeCharacteristic(UUID uuid_service, UUID uuid_characteristic, String string) {
if (bluetoothGatt != null) {
BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGatt.getService(uuid_service).getCharacteristic(uuid_characteristic);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
bluetoothGatt.writeCharacteristic(
bluetoothGattCharacteristic,
string.getBytes(),
bluetoothGattCharacteristic.getWriteType()
);
} else {
bluetoothGattCharacteristic.setValue(string);
bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
}
}
}
:今回は、ここまでです。
非推奨のwriteCharacteristicに対応しているAndroidアプリです。
誤字脱字、意味不明でわかりづらい、
もっと詳しく知りたいなどのご意見は、
このページの最後にあるコメントか、
こちらから、お願いいたします♪
ポチッとして頂けると、
次のコンテンツを作成する励みになります♪
これからAndroidのアプリ開発やJavaでの開発を始めたい方へ
アプリケーション開発経験がない方や、アプリケーション開発経験がある方でも、JavaやC#などのオブジェクト指向言語が初めての方は、Androidのアプリ開発ができるようになるには、かなりの時間がかかります。
オンラインスクールでの習得を、強くおススメします。
未経験者からプログラマーを目指すのに最適です。まずは無料カウンセリングから♪

ゲーム系に強いスクール、UnityやUnrealEngineを習得するのに最適です。まずは無料オンライン相談から♪

参考になったら、💛をポッチとしてね♪


コメント欄