• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Android Studio Beginner: Questions and problems regarding reading data from bluetooth

Daronee

Lurker
Nov 12, 2020
1
0
Hello! I am currently working on acheiving certain tasks depending on the data received from a Bluetooth module using the input buffer. Currently I am trying to play a sound depending on the input using MediaPlayer.Create, but only seems to work when I have the device plugged in and hit "Apply Changes and Restart Activity." It does not seem to work if I were to just open the app and test, only after going through the process stated before. Is there a better way of reading the inputstream and handling that data? Is there also a better way to go about how I am playing a sound in the run() function of the ConnectedThread thread? This is my current code. I am also thinking of switching from MediaPlayer to SoundPool because I would like to play multiple sounds simultaneously, would that also be a good option?

Code:
class ControlActivity: AppCompatActivity() {

   companion object {
       var m_myUUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
       var m_bluetoothSocket: BluetoothSocket? = null
       lateinit var m_progress: ProgressDialog
       lateinit var m_bluetoothAdapater: BluetoothAdapter
       var m_isConnected: Boolean = false
       lateinit var  m_address: String
       private const val TAG = "MY_APP_DEBUG_TAG"
       const val MESSAGE_READ: Int = 0
       const val MESSAGE_WRITE: Int = 1
       const val MESSAGE_TOAST: Int = 2
       private lateinit var handler: Handler
   }
   var mMediaPlayer: MediaPlayer? = null
   override fun onCreate(savedInstanceState: Bundle?) {

       super.onCreate(savedInstanceState)
       setContentView(R.layout.control_layout)
       m_address = intent.getStringExtra(SettingsActivity.EXTRA_ADDRESS)!!
       ConnectToDevice(this).execute()

       control_led_on.setOnClickListener { sendCommand("1") }
       control_led_off.setOnClickListener { sendCommand("0") }
       control_led_disconnect.setOnClickListener { disconnect() }
   }

   private fun sendCommand(input: String){
       if (m_bluetoothSocket != null){
           try {
               m_bluetoothSocket!!.outputStream.write(input.toByteArray())
               Log.i("data", "sending..")
           } catch (e: IOException) {
               e.printStackTrace()
               Log.i("data", "couldn't send")
               }
               return

           }

   }
   private fun disconnect(){
       if (m_bluetoothSocket != null){
           try {
               m_bluetoothSocket!!.close()
               m_bluetoothSocket = null
               m_isConnected = false
           } catch (e: IOException) {
               e.printStackTrace()
           }
       }
       finish()
   }

   private class ConnectedThread(private val mmSocket: BluetoothSocket?, c : Context) : Thread() {
       private val mmBuffer: ByteArray = ByteArray(10) // mmBuffer store for the stream
       var mMediaPlayer: MediaPlayer? = null
       var context: Context
       init{
           this.context = c
       }
       override fun run() {
           var numBytes: Int = 0// bytes returned from read()
           //var begin: Int = 0
           // Keep listening to the InputStream until an exception occurs.
           while (true) {
               // Read from the InputStream.
               try {
                   numBytes =
                       mmSocket!!.inputStream.read(mmBuffer, numBytes, mmBuffer.size - numBytes)


               } catch (e: IOException) {
                   Log.d(TAG, "Input stream was disconnected", e)
                   break
               }

               playNote(context)

               println(numBytes)
               println(String(mmBuffer))





           }
       }
       fun playNote(c: Context) {
           if (mMediaPlayer == null) {
               mMediaPlayer = MediaPlayer.create(c, R.raw.c3)
               mMediaPlayer!!.start()
           } else if (mMediaPlayer != null) {
               mMediaPlayer!!.stop()
               mMediaPlayer!!.release()
               mMediaPlayer = null
           } else mMediaPlayer!!.start()
       }

   }




   private class ConnectToDevice(c: Context) : AsyncTask<Void, Void, String>(){
       private var connectSuccess: Boolean = true
       private val context: Context

       init {
           this.context = c
       }
       override fun onPreExecute() {
           super.onPreExecute()
           m_progress = ProgressDialog.show(context, "Connecting...", "please wait")
       }
       override fun doInBackground(vararg p0: Void?) : String? {
           try {
               if (m_bluetoothSocket == null || !m_isConnected){
                   m_bluetoothAdapater = BluetoothAdapter.getDefaultAdapter()
                   val device: BluetoothDevice = m_bluetoothAdapater.getRemoteDevice(m_address)
                   m_bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(m_myUUID)
                   BluetoothAdapter.getDefaultAdapter().cancelDiscovery()
                   m_bluetoothSocket!!.connect()

               }
           } catch (e: IOException){
               connectSuccess = false
               e.printStackTrace()
           }
           return null
       }
       override fun onPostExecute(result: String?) {
           super.onPostExecute(result)
           if(!connectSuccess){
               Log.i("data", "couldn't connect")
           } else {
               m_isConnected = true
               var connectedthread= ConnectedThread(m_bluetoothSocket, context)
               connectedthread.start()
               Log.i("data", "connected")
           }
           m_progress.dismiss()


       }

   }
}

I feel like the problem I have might be the way I am passing the context to the MediaPlayer in the ConnectedThread thread, but I'm honestly not too sure because i just started learning kotlin. What other options do I have for evaluating the bytearray being sent from the Bluetooth?
 
Last edited:

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones