此处理程序可能是静态的,或者蓝牙处理程序可能会发生泄漏

时间:2015-12-23 02:43:14

标签: java android memory-leaks bluetooth

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


        txtString = (TextView) findViewById(R.id.txtString);
        txtStringLength = (TextView) findViewById(R.id.testView1);
        sensorView0 = (TextView) findViewById(R.id.sensorView0);
        sensorView1 = (TextView) findViewById(R.id.sensorView1);
        sensorView2 = (TextView) findViewById(R.id.sensorView2);
        sensorView3 = (TextView) findViewById(R.id.sensorView3);

     bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == handlerState) {
                String readMessage = (String) msg.obj;
                recDataString.append(readMessage);
                int endOfLineIndex = recDataString.indexOf("~");
                if (endOfLineIndex > 0) {
                    String dataInPrint = recDataString.substring(0, endOfLineIndex);
                    txtString.setText("Data Received = " + dataInPrint);
                    int dataLength = dataInPrint.length();
                    txtStringLength.setText("String Length = " + String.valueOf(dataLength));

                    if (recDataString.charAt(0) == '#')
                    {
                        String sensor0 = recDataString.substring(1, 5);
                        String sensor1 = recDataString.substring(6, 10);
                        String sensor2 = recDataString.substring(11, 15);
                        String sensor3 = recDataString.substring(16, 20);

                        sensorView0.setText(" Sensor 0 Voltage = " + sensor0 + "V");
                        sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
                        sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
                        sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
                    }
                    recDataString.delete(0, recDataString.length());

                }
            }
        }
    };
  }

嗨,我得到处理程序的警告可能是静态的,或者可能发生泄漏。我看过其他帖子,但它并没有帮助我解决我的问题。 :(警告发生在bluetoothIn的开头到最后。

rederror after moving out of on create handler is in grey

1 个答案:

答案 0 :(得分:0)

可能重复此question。所以解决方案如下:

    static class BluetoothInHandler extends Handler {
            private final WeakReference<YourActivityName> mActivity; 

            IncomingHandler(YourActivityName activity) {
                mActivity= new WeakReference<YourActivityName>(activity);
            }
            @Override
            public void handleMessage(Message msg)
            {
                final YourActivityName thizz = mActivity.get();
                if (thizz == null) {
                    return;
                 }
                if (msg.what == thizz.handlerState) {
                  // Do what you need
                 }
            }
    }