[Flutter] Android端末で、Bluetoothペアリング済みの端末の情報を取得する方法
はじめに
Flutterアプリで、Android端末とペアリング済みの端末の情報(端末名、macアドレス)を取得する方法について調べていたのですが、 MethodChannelを利用して、Kotlin側から取得する方法が楽に実装できそうだったので、その際の手順を残そうと思います。
※iOSでの実装は今回触れません。
実装
まずはDart側から実装していきます。 MethodChannelを使い任意のタイミングでKotlin側のプログラムを呼び出します。
main.dart
Future<dynamic> getPairingDeviceInfo() { var res = MethodChannel('com.sample_project/bluetooth') .invokeMethod('get_pairing_device_info', {}); return res; }
続いてKotlin側で、Dart側から呼び出されるMethodChannelを作成していきます。 Bluetoothペアリング済みの端末情報を取得し、Dart側に返します。
MainActivity.kt
class MainActivity : FlutterActivity() { private lateinit var channel: EventChannel override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine) var channelBrother = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.sample_project/bluetooth") // dart側で設定したチャンネル名と同じにする。 channelBrother.setMethodCallHandler { methodCall: MethodCall, result: MethodChannel.Result -> when (methodCall.method) { "get_pairing_device_info" -> { val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter(); val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices val deviceName = pairedDevices?.first()?.name // デバイス名 val deviceHardwareAddress = pairedDevices?.first()?.address // macアドレス result.success(deviceName.toString()) } } } }
採用に関して
弊社では、現在、エンジニアを募集しております。 物流に興味・関心がある方はもちろん、 Flutterやモバイル開発に強みがある方、心よりお待ちしております!