我将如何使这个Handler类保持静态?

时间:2016-02-17 15:11:05

标签: java android android-studio android-logcat

Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        Log.i(tag, "in handler");
        super.handleMessage(msg);
        switch (msg.what) {
            case SUCCESS_CONNECT:
                // DO something
                ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket) msg.obj);
                Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();
                String s = "successfully connected";
                connectedThread.write(s.getBytes());
                Log.i(tag, "connected");
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                String string = new String(readBuf);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
                break;
        }
    }
};

我需要一些帮助使这个Handler类保持静态,但我真的不知道如何。

我得到的消息:

此Handler类应该是静态的,否则可能会发生泄漏(null) Image

这是Logcat的抱怨:

第1部分:pastebin.com/xwy2zEPh

第2部分:pastebin.com/9UBSWyr2

2 个答案:

答案 0 :(得分:0)

如果我用 static (这可能不是正确的术语)得到你的意思,你想要创建一个不同的文件,例如MyHandler.java,你把它放在

public class MyHandler implements Handler {

 private final ApplicationContext context;

 public MyHandler(final ApplicationContext context) {
    // Add Pre Condition for context not null
    this.context = context;
 }

 @Override
 public void handleMessage(Message msg) {
    // TODO Auto-generated method stub
    Log.i(tag, "in handler");
    super.handleMessage(msg);
    switch (msg.what) {
        case SUCCESS_CONNECT:
            // DO something
            ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket) msg.obj);
            Toast.makeText(context, "CONNECT", Toast.LENGTH_SHORT).show();
            String s = "successfully connected";
            connectedThread.write(s.getBytes());
            Log.i(tag, "connected");
            break;
        case MESSAGE_READ:
            byte[] readBuf = (byte[]) msg.obj;
            String string = new String(readBuf);
            Toast.makeText(context, string, Toast.LENGTH_LONG).show();
            break;
    }
 }
}

然后

 final ApplicationContext context = getApplicationContext();
 Handler mHandler = new MyHandler(context);

N.B。我假设Handler是一个接口...

已编辑由于Andy的评论

答案 1 :(得分:0)

我解决了这个问题。它崩溃的原因是因为我忘了添加

@Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, filter);

    }