vendredi 8 mai 2015

Memory leaks in Android handler

I am trying to read data from a serial bluetooth stream in my android application. The data is send to a handler to display it. It works fine for a few minutes and then it stops showing data (The app keeps running however). I think it has to do with memory leaks in my handler but I don't know how to solve it..

This is where I found the code

I will be so happy if someone can help me. Thanks in advance

public class MainActivity extends ActionBarActivity {

    static BluetoothAdapter mBluetoothAdapter = null;
    static Handler mHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Does the device support bluetooth?
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Device does not support Bluetooth",Toast.LENGTH_LONG).show();
        }

        //Turn on Bluetooth if disabled
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }

        //Get the Bluetooth module device
        BluetoothDevice mDevice = null;
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                if(device.getName().equals("HC-06")) {
                    mDevice = device;
                }
            }
        }
        if(mDevice == null){
            Toast.makeText(this,"Device not found",Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(this,"connected to " + mDevice.getName(),Toast.LENGTH_LONG).show();

            ConnectThread mConnectThread = new ConnectThread(mDevice);
            mConnectThread.start();

            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    byte[] writeBuf = (byte[]) msg.obj;
                    int begin = (int)msg.arg1;
                    int end = (int)msg.arg2;
                    switch(msg.what) {
                        case 1:
                            String writeMessage = new String(writeBuf);
                            writeMessage = writeMessage.substring(begin, end);

                            ScrollView scrollView1 = (ScrollView) findViewById(R.id.scroll);
                            TextView textView1 = (TextView) findViewById(R.id.statusText);
                            textView1.append(writeMessage + "\n");
                            scrollView1.fullScroll(View.FOCUS_DOWN);

                            break;
                    }
                }
            };
    }
}

Aucun commentaire:

Enregistrer un commentaire