theblitz
theblitz

Reputation: 6881

Thread or Asynctask for Bluetooth?

I am writing a program that uses Bluetooth to connect between 2 or more devices. I used the BluetoothChat as an example.

Problem is that when it reaches the "read" command in the "connected" thread it seems to freeze the whole program.

I think that that is what is happening because the command after the myThread.run() is not reached but the command inside the thread is.

Am I doing something wrong?

Should I be switching to AsyncTask in place of Thread?

I tried reading some of the other posts about the subject but found them hard to follow. Specifically, if I should be using the AsyncTask then why does the example program use Threads?

This is the code in the connected thread:

    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;

        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream
                Log.d(TAG,"Server - BTConnectedThreadServer - run() - before read");
                bytes = mmInStream.read(buffer);
                Log.d(TAG,"Server - BTConnectedThreadServer - run() - after read");

                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(BluetoothConstants.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
                Log.d(TAG,"Server - BTConnectedThreadServer - run() - after send");
            } catch (IOException e) {
                Log.d(TAG,"Server - BTConnectedThreadServer - run() - disconnected", e);
                e.printStackTrace();
                BluetoothConstants.connectionLost(mHandler);

                break;
            }
        }
        Log.d(TAG,"Server - BTConnectedThreadServer - run() - Exited Loop");
    }

The "before read" Log note comes up but nothing else does. It never returns to the main thread.

Upvotes: 1

Views: 3209

Answers (2)

FunkTheMonk
FunkTheMonk

Reputation: 10938

myThread.run() will still run on the same thread, you want myThread.start() and if that doesnt fix it, show some code

Upvotes: 2

Eng.Fouad
Eng.Fouad

Reputation: 117597

You should use myThread.start() not myThread.run() to start the thread.

Upvotes: 1

Related Questions