Androidから別端末へBluetooth接続し、メッセージを送信するアプリケーションを作成しています。
AndroidアプリのSerial Bluetooth Terminal
を使用すると端末に接続できるのですが、自作アプリだと接続できないのでご助力お願いします。
Serial Bluetooth Terminal
では機器をスキャンした後に以下の内容で接続すると、通信を開始できました。
ITEM | VALUE |
---|---|
MAC ADDRESS | 90:FD:9F:A5:F4:2A |
Service UUID | 4880c12c-fdcb-4077-8920-a450d7f9b907 |
Read characteristic UUID | fec26ec4-6d71-4442-9f81-55bc21d658d6 |
Write characteristic UUID | fec26ec4-6d71-4442-9f81-55bc21d658d6 |
以下ソースコードです。ボタンを押したら接続を開始します。
MainActivity.kt
kotlin
1 2class MainActivity : AppCompatActivity() { 3 4 companion object { 5 const val MAC_ADDRESS = "90:FD:9F:A5:F4:2A" 6 const val SERVICE_UUID = "4880c12c-fdcb-4077-8920-a450d7f9b907" 7 const val READ_CHARACTERISTIC_UUID = "fec26ec4-6d71-4442-9f81-55bc21d658d6" 8 const val WRITE_CHARACTERISTIC_UUID = "fec26ec4-6d71-4442-9f81-55bc21d658d6" 9 } 10 11 override fun onCreate(savedInstanceState: Bundle?) { 12 // Setup the window 13 super.onCreate(savedInstanceState) 14 setContentView(R.layout.activity_main) 15 setResult(Activity.RESULT_CANCELED) 16 17 button_connect.setOnClickListener { 18 bt_connect() 19 } 20 } 21 22 private fun bt_connect(){ 23 24 val btAdapter = BluetoothAdapter.getDefaultAdapter() 25 26 //端末がBluetoothに対応しているか 27 if (btAdapter == null) { 28 Toast.makeText(this, "Bluetooth対応機器ではありません", Toast.LENGTH_SHORT).show() 29 return 30 } 31 //Bluetoothが有効であるか 32 if (!btAdapter.isEnabled) { 33 Toast.makeText(this, "BluetoothをONにします", Toast.LENGTH_SHORT).show() 34 btAdapter.enable() 35 } 36 37 // Device検索 38 val btDevice = btAdapter.getRemoteDevice(MAC_ADDRESS) 39 40 //接続確立待機 41 try { 42 Thread.sleep(2000) 43 } catch (e: InterruptedException) { 44 e.printStackTrace() 45 return 46 } 47 48 // 接続 49 var btSocket: BluetoothSocket? = null 50 try { 51 btSocket = btDevice.createRfcommSocketToServiceRecord(UUID.fromString(SERVICE_UUID)) 52 btSocket.connect() 53 } catch (e: IOException) { 54 Toast.makeText(applicationContext, "接続失敗しました", Toast.LENGTH_SHORT).show() 55 e.printStackTrace() 56 return 57 } 58 59 // メッセージ送信 60 try{ 61 val outputStream : OutputStream = btSocket.outputStream 62 outputStream.write("Test".toByteArray()) 63 } catch (e: IOException) { 64 Toast.makeText(applicationContext, "送信失敗しました", Toast.LENGTH_SHORT).show() 65 e.printStackTrace() 66 return 67 } 68 69 Toast.makeText(applicationContext, "送信しました", Toast.LENGTH_SHORT).show() 70 } 71}
activity_main.xml
xml
1<?xml version="1.0" encoding="utf-8"?> 2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="wrap_content" 6 android:layout_margin="10dp" 7 android:orientation="vertical"> 8 9 <Button 10 android:id="@+id/button_connect" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:text="Connect" 14 android:textSize="18sp"/> 15</LinearLayout>
あなたの回答
tips
プレビュー