Question

I've been trying to create a function in my app that consist in a bluetooth RFID scanner, it's paired to my device and I have it working and all.

I can receive the text and log it in the console, when I compile the activity, everything goes fine, the stick reads the code, and then appends the text into an EditText, but if I go back and enter the activity again, I can see the code in the log, but the text doesn't go to the Edittext.

I tried a lot of different approaches, but nothing seems to work :/

here's the code I have:

 /**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bluetooth);


    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> bondedSet = mBluetoothAdapter.getBondedDevices();


    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available.", Toast.LENGTH_LONG).show();

    }

    if (!mBluetoothAdapter.isEnabled()) {
        Toast.makeText(this, "Please enable your BT and re-run this program.", Toast.LENGTH_LONG).show();
        finish();
    }
    if (mBluetoothAdapter.isEnabled()) {
        if(bondedSet.size() == 1){
            for(BluetoothDevice device : bondedSet){
                address = device.getAddress();
                Log.d("bt:", address);
            }
        }
    }
    String address = "00:A0:96:2A:0A:1B";
    out = (EditText) findViewById(R.id.output);

    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    Log.d(TAG, device.getName() + " connected");
    myConnection = new ConnectThread(device);
    myConnection.start();

}
private class ConnectThread extends Thread {
    private final BluetoothSocket mySocket;
    Message msg;

    public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;

        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Log.d(TAG, "CONNECTION IN THREAD DIDNT WORK");
        }
        mySocket = tmp;
    }

    Handler uiThreadHandler = new Handler() {
        public void handleMessage(Message msg) {
            out = (EditText) findViewById(R.id.output);
            Object o = msg.obj;
            out.append(o.toString().trim());
            Log.d("handler", o.toString());
        }
    };

    public void run() {
        out = (EditText) findViewById(R.id.output);

        Log.d(TAG, "STARTING TO CONNECT THE SOCKET");
        setName("My Connection Thread");
        InputStream inStream = null;
        boolean run = false;
        mBluetoothAdapter.cancelDiscovery();

        try {
            mySocket.connect();
            run = true;
        } catch (IOException e) {
            Log.d(TAG, this.getName() + ": CONN DIDNT WORK, Try closing socket");
            try {
                mySocket.close();
                Log.d(TAG, this.getName() + ": CLOSED SOCKET");
            } catch (IOException e1) {
                Log.d(TAG, this.getName() + ": COULD CLOSE SOCKET", e1);
                this.destroy();
            }
            run = false;
        }

        synchronized (BluetoothActivity.this) {
            myConnection = null;
        }

        byte[] buffer = new byte[1024];
        int bytes;
        // handle Connection
        try {
            inStream = mySocket.getInputStream();
            while (run) {
                try {
                    bytes = inStream.read(buffer);
                    readMessage = new String(buffer, 0, bytes);
                    msg = uiThreadHandler.obtainMessage();
                    msg.obj = readMessage;
                    uiThreadHandler.sendMessage(msg);
                    Log.d(TAG, "Received: " + readMessage);
                } catch (IOException e3) {
                    Log.d(TAG, "disconnected");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
Was it helpful?

Solution

My guess is that this has something to do with the Thread itself. When you start your Activity for the first time, you also call .start() on the Thread, that would work fine.

The problem is when you leave your Activity and open it up again. In that case, one of onStop() or onPause() is called (depending on situation), and onRestart() or onResume() will be called afterwards respectively.

The trick comes now: Meanwhile all that process, your Thread is still running. As you show your code, it has not been stopped/paused, and keeps running all the time. So basically my tip is that there's something you do within your onCreate() method of your Activity that should also be done in your onPause() and onStop() events, and my another tip it's somewhere within your ConnectThread(BluetoothDevice device) method.

To know how to procceed, I'd firstly define both onStop() and onPause() methods within your Activity and see which is fired, log every attribute to see its value/state, and that way you'll be able to debug what is failing.

There's a diagram of the Activity lifecycle.

OTHER TIPS

Problem was solved, the code works, and the TextView get the inputstream, the problem was when i left the activity, the thread continued to work, so far, no problem at all, after TONS of hours spent on this, i turn the TextView a static var and it worked :)

If anyone reads this, i hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top