2

I'm still new to Android development but I am currently working on a project that requires the Bluetooth interface to be in constant communication with a Bluetooth-device. I've been reading up on Service, IntentService & AsynTask but I am still confused. I think I should not be using AsyncTask as it is meant for processing a very short task? If I use IntentService, how do I spawn multiple threads to check if the Bluetooth device is connected, sending and receiving?

I'm using the BluetoothViewer as my reference. In it connectThread is a thread which, when connected to the Bluetooth device, would then start the connectedThread.

Thanks

Ken

Benjamin Leinweber
  • 2,774
  • 1
  • 24
  • 41
Ken K.
  • 23
  • 1
  • 5

1 Answers1

1

I use an ACTION_REQUEST_ENABLE intent to startActivityForResult(). This then results in a call to:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == imu.requestCode) {
            if (resultCode == RESULT_OK) {
            getPairedDevice();  // my function 
            initializeConnection(); // my function
        }
    }
}

initializeConnection() creates a new thread that initializes my input socket, creates yet another thread for Bluetooth input processing, and creates my output thread. Snippets from those functions include:

myServerSocket = dev.createInsecureRfcommSocketToServiceRecord(uuid); 
myBluetooth.cancelDiscovery();
myServerSocket.connect();
myBluetoothInputThread = new BluetoothInputThread(myServerSocket, handler);                    myBluetoothInputThread.setPriority(Thread.MAX_PRIORITY); 
myBluetoothInputThread.start();
myBluetoothSocketOutputStream = myServerSocket.getOutputStream();

BluetoothInputThread extends Thread to create a separate process for monitoring the input stream. This class communicates with its parent class via the Handler.sendMessage

MikeS
  • 26
  • 2