[英]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;
}
}
};
I need some help making this Handler class static, but I don't really know how. 我需要一些帮助使此Handler类变为静态,但我真的不知道如何。
Message I get: 我收到的消息:
This Handler class should be static or leaks might occur (null) 该处理程序类应该是静态的,否则可能会发生泄漏(空)
Here's Logcat complaining: 这是Logcat的抱怨:
Part 1: pastebin.com/xwy2zEPh 第1部分:pastebin.com/xwy2zEPh
Part 2: pastebin.com/9UBSWyr2 第2部分:pastebin.com/9UBSWyr2
If I get what you mean with static (which is probably not the right term) you want to create a different file, eg MyHandler.java, where you put 如果我对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;
}
}
}
and then 接着
final ApplicationContext context = getApplicationContext();
Handler mHandler = new MyHandler(context);
NB I made the assumption that Handler is an interface... 注意我假设Handler是一个接口...
Edited Due to Andy's comment 由于安迪的评论而编辑
I fixed the issue. 我解决了这个问题。 The reason it was crashing allot was because I forgot to add 分配失败的原因是我忘记添加
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, filter);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.