我将如何使这个 Handler class 静态化?

How would I go about making this Handler class static?

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 class 静态化,但我真的不知道怎么做。

我收到的消息:

此处理程序 class 应该是静态的,否则可能会发生泄漏 (null)

这里是 Logcat 抱怨:

第 1 部分:pastebin。com/xwy2zEPh

第 2 部分:pastebin。com/9UBSWyr2

如果我明白你用 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 的评论

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

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

    }