1. Are you ready for the Galaxy S20? Here is everything we know so far!

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

Discussion in 'Android Development' started by Daronee, Nov 12, 2020.

  1. Daronee

    Daronee Lurker
    Thread Starter

    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 (Text):
    1.  
    2. class ControlActivity: AppCompatActivity() {
    3.  
    4.    companion object {
    5.        var m_myUUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
    6.        var m_bluetoothSocket: BluetoothSocket? = null
    7.        lateinit var m_progress: ProgressDialog
    8.        lateinit var m_bluetoothAdapater: BluetoothAdapter
    9.        var m_isConnected: Boolean = false
    10.        lateinit var  m_address: String
    11.        private const val TAG = "MY_APP_DEBUG_TAG"
    12.        const val MESSAGE_READ: Int = 0
    13.        const val MESSAGE_WRITE: Int = 1
    14.        const val MESSAGE_TOAST: Int = 2
    15.        private lateinit var handler: Handler
    16.    }
    17.    var mMediaPlayer: MediaPlayer? = null
    18.    override fun onCreate(savedInstanceState: Bundle?) {
    19.  
    20.        super.onCreate(savedInstanceState)
    21.        setContentView(R.layout.control_layout)
    22.        m_address = intent.getStringExtra(SettingsActivity.EXTRA_ADDRESS)!!
    23.        ConnectToDevice(this).execute()
    24.  
    25.        control_led_on.setOnClickListener { sendCommand("1") }
    26.        control_led_off.setOnClickListener { sendCommand("0") }
    27.        control_led_disconnect.setOnClickListener { disconnect() }
    28.    }
    29.  
    30.    private fun sendCommand(input: String){
    31.        if (m_bluetoothSocket != null){
    32.            try {
    33.                m_bluetoothSocket!!.outputStream.write(input.toByteArray())
    34.                Log.i("data", "sending..")
    35.            } catch (e: IOException) {
    36.                e.printStackTrace()
    37.                Log.i("data", "couldn't send")
    38.                }
    39.                return
    40.  
    41.            }
    42.  
    43.    }
    44.    private fun disconnect(){
    45.        if (m_bluetoothSocket != null){
    46.            try {
    47.                m_bluetoothSocket!!.close()
    48.                m_bluetoothSocket = null
    49.                m_isConnected = false
    50.            } catch (e: IOException) {
    51.                e.printStackTrace()
    52.            }
    53.        }
    54.        finish()
    55.    }
    56.  
    57.    private class ConnectedThread(private val mmSocket: BluetoothSocket?, c : Context) : Thread() {
    58.        private val mmBuffer: ByteArray = ByteArray(10) // mmBuffer store for the stream
    59.        var mMediaPlayer: MediaPlayer? = null
    60.        var context: Context
    61.        init{
    62.            this.context = c
    63.        }
    64.        override fun run() {
    65.            var numBytes: Int = 0// bytes returned from read()
    66.            //var begin: Int = 0
    67.            // Keep listening to the InputStream until an exception occurs.
    68.            while (true) {
    69.                // Read from the InputStream.
    70.                try {
    71.                    numBytes =
    72.                        mmSocket!!.inputStream.read(mmBuffer, numBytes, mmBuffer.size - numBytes)
    73.  
    74.  
    75.                } catch (e: IOException) {
    76.                    Log.d(TAG, "Input stream was disconnected", e)
    77.                    break
    78.                }
    79.  
    80.                playNote(context)
    81.  
    82.                println(numBytes)
    83.                println(String(mmBuffer))
    84.  
    85.  
    86.  
    87.  
    88.  
    89.            }
    90.        }
    91.        fun playNote(c: Context) {
    92.            if (mMediaPlayer == null) {
    93.                mMediaPlayer = MediaPlayer.create(c, R.raw.c3)
    94.                mMediaPlayer!!.start()
    95.            } else if (mMediaPlayer != null) {
    96.                mMediaPlayer!!.stop()
    97.                mMediaPlayer!!.release()
    98.                mMediaPlayer = null
    99.            } else mMediaPlayer!!.start()
    100.        }
    101.  
    102.    }
    103.  
    104.  
    105.  
    106.  
    107.    private class ConnectToDevice(c: Context) : AsyncTask<Void, Void, String>(){
    108.        private var connectSuccess: Boolean = true
    109.        private val context: Context
    110.  
    111.        init {
    112.            this.context = c
    113.        }
    114.        override fun onPreExecute() {
    115.            super.onPreExecute()
    116.            m_progress = ProgressDialog.show(context, "Connecting...", "please wait")
    117.        }
    118.        override fun doInBackground(vararg p0: Void?) : String? {
    119.            try {
    120.                if (m_bluetoothSocket == null || !m_isConnected){
    121.                    m_bluetoothAdapater = BluetoothAdapter.getDefaultAdapter()
    122.                    val device: BluetoothDevice = m_bluetoothAdapater.getRemoteDevice(m_address)
    123.                    m_bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(m_myUUID)
    124.                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery()
    125.                    m_bluetoothSocket!!.connect()
    126.  
    127.                }
    128.            } catch (e: IOException){
    129.                connectSuccess = false
    130.                e.printStackTrace()
    131.            }
    132.            return null
    133.        }
    134.        override fun onPostExecute(result: String?) {
    135.            super.onPostExecute(result)
    136.            if(!connectSuccess){
    137.                Log.i("data", "couldn't connect")
    138.            } else {
    139.                m_isConnected = true
    140.                var connectedthread= ConnectedThread(m_bluetoothSocket, context)
    141.                connectedthread.start()
    142.                Log.i("data", "connected")
    143.            }
    144.            m_progress.dismiss()
    145.  
    146.  
    147.        }
    148.  
    149.    }
    150. }
    151.  
    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?
     


    #1 Daronee, Nov 12, 2020
    Last edited: Nov 13, 2020

    1. Download the Forums for Android™ app!


      Download

       
Loading...
Similar Threads - Android Studio Beginner
  1. shyriu42
    Replies:
    0
    Views:
    164
  2. Mohamed13
    Replies:
    6
    Views:
    497
  3. dariussiriuse
    Replies:
    0
    Views:
    241
  4. Mickey2021
    Replies:
    3
    Views:
    299
  5. Steven Hauberg
    Replies:
    2
    Views:
    531
  6. AlexEv
    Replies:
    0
    Views:
    614
  7. WolfSpyryt
    Replies:
    1
    Views:
    531
  8. mikewax
    Replies:
    1
    Views:
    339
  9. EndritR
    Replies:
    0
    Views:
    218
  10. RLScott
    Replies:
    2
    Views:
    360

Share This Page

Loading...