• 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

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?

Returning a bitmap from a video properly

Using:

Code:
 static int i=0;

int index = 4 * ( x + width * y );
unsigned char red = pixelsp[i]>>16 ;
unsigned char green = pixelsp[i]>>8;
unsigned char blue = pixelsp[i];
unsigned char alpha = pixelsp[i] >> 24;

pixelsp[index]=red;
pixelsp[index+1]=green;
pixelsp[index+2]=blue;
pixelsp[index+3]=alpha;

i++;

instead of:

Code:
int index = 4 * ( x + width * y );
            unsigned char red = pixelsp[index]>>16 ;
            unsigned char green = pixelsp[index+1 ]>>8;
            unsigned char blue = pixelsp[index+2];
            unsigned char alpha = pixelsp[index+3] >> 24;
            bitmap[index]=red;
            bitmap[index+1]=green;
            bitmap[index+2]=blue;
            bitmap[index+3]=alpha;


solved the problem.

Help file transfer on Android 10

Tell me how to do.
You bet! :)

First, you need a good file manager on Android; my hands-down favorite is MiXplorer Silver. Please see this post and thread for more info, including pics of MiXplorer giving me access to my computers.

Your computer(s) and Android device(s) must be on the same Wi-Fi network.

Your computer(s) must be networked, i.e., their drive(s) must be shared. I only use Linux so someone else will have to step in if you're in need of help with that.

That's it! You're good to go. As you'll see in my pics, my computers' drives are available to me in my file manager just as if they were local. Also, some file managers give you a completely separate way of transferring files; in this case, they're more like Airdroid, using a web browser on the computer to connect to the FM on Android. I never use that method as it's unnecessary for me, but if you have problems networking your computer(s), this would be a viable alternative.

Trichrome alert

I don't really trust them. I don't use chrome, either. What's really bothering me about this phone is its inability to transfer any files to sd. I have tried moving images, videos, downloads, etc. I have looked under all the possible categories. I posted screenshots which I hope will show the problem. Maybe I'll just have to call Samsung and/or Sandisk.

Help Installing Android on empty phone

@ocnbrze
I got an Coolpad Porto S (E570). Yes it's a china phone^^

Okay the situation just changed. I tried installing android again but this time I skipped the Wifi part. Therefore (i assume) it didn't try to install google play services and actually gave me a home screen (previously it failed to install google play services and didn't boot therefore).

Now the play store still doesn't work but at least I can activate developer mode. I'll try installing another android version on it. I will post here further updates.

Thanks for the help so far!

Help Moto G4 Play, no longer has calls after carrier switch

I've done the reset through "back and reset" and through the recovery mode. Since I've done the recovery 6-7 times I feel a bit of fatique so have only put google login and MinMobile back on the phone. I get email notifications but looks like I no longer get text.

Now I'm just wondering how I can move forward. I'm hoping to recover my phone number to maybe a flip phone? Without my phone I'm being locked out of Microsoft. Will this nightmare stop.

Filter

Back
Top Bottom