スマホでのBluetooth通信(検出)

■Bluetooth通信の試し。
NFCの記事の近くにBluetooth通信の記事もあったので、ついでにそれも試してみた。Bluetoothは、2.4GHzの帯域で対象機器とペアリングして使う近距離通信。

そのため、まずは接続可能なBluetooth機器を探して、それに接続する必要がある。ウェブからサンプルコードを探してボタンから探すように修正。

Button bt = findViewById(R.id.button);
   bt.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
      int blueperm = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_SCAN);
      if (blueperm != PackageManager.PERMISSION_GRANTED) {
         ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_SCAN}, 100);
         requestPermissions(new String[]{Manifest.permission.BLUETOOTH_SCAN}, 100);
      } else {
         bta.startDiscovery();
      }
   }
});

ここで、startDiscovery のときに Bluetooth の SCAN の権限がないとエラーが出る(java.lang.SecurityException: Need android.permission.BLUETOOTH_SCAN permission for android.content.)。権限について、AndroidManifest.xml ファイルに下のコードを追記するだけではダメなよう。実行時にも権限付与するようコードを入れておかないといけない。

  <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
  <uses-permission android:name="android.permission.BLUETOOTH_SCAN"
        android:usesPermissionFlags="neverForLocation" />

上のコードの実行時に Request の部分で下のような権限を許可する画面が出るので、これを許可するとSCANができる。


startDiscovery で通信可能な機器が見つかったときに、下の onReceive メソッドが実行されるよう。

public void onReceive(Context context, Intent intent) {

   int blueperm2 = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT);

   String action = intent.getAction();
   String deviceName = null;
   String deviceHardwareAddress = null;
   if (blueperm2 != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 101);
      requestPermissions(new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 101);
   } else {
      if (BluetoothDevice.ACTION_FOUND.equals(action)) {
         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
         deviceName = device.getName();
         deviceHardwareAddress = device.getAddress();
      }
      TextView tv = findViewById(R.id.textView);
      tv.setText(deviceName + ":" + deviceHardwareAddress);
   }
}

ここでも同様に BLUETOOTH の CONNECT の権限がないと getName あたりでエラーが出る(java.lang.SecurityException: Need android.permission.BLUETOOTH_CONNECT permission for android.content.)。

得られた通信可能な機器の名前やMACアドレスをテキストビューへ追加して表示する。プリンタやPCなどが表示された。PCのものとして表示されたMACアドレスを確認すると、イーサネット アダプター Bluetooth ネットワーク接続のものだった。

これでスマホアプリから接続ができたと思う。Bluetoothで何ができるか試していく。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です