I'm writing a simple socket client app for android, here is my handler class:
static Handler IncomingHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (flag) {
kq += msg.obj.toString() + "\r\n";
textResponse.setText(kq);
}
}
};
This handler has a "should be static or leaks may occur" warning, and it did. It keeps running in a loop, using 40% CPU.
According to this question, I changed my handler class to
static class IncomingHandler extends Handler {
private final WeakReference<MainActivity> mService;
IncomingHandler(MainActivity service) {
mService = new WeakReference<MainActivity>(service);
}
@Override
public void handleMessage(Message msg)
{
MainActivity service = mService.get();
if (service != null) {
if (flag) {
kq += msg.obj.toString() + "\r\n";
textResponse.setText(kq);
}
}
}
}
It doesn't have "leaks may occur" warning anymore, but now a new problem appeared: I can't refer IncomingHandler from another class
public class ClientTask extends AsyncTask<String, String, String> implements
OnListener {
////Some random code
void sendMessage(String msg) {
try {
if (!msg.equals("bye"))
MainActivity.IncomingHandler.obtainMessage(0, 0, -1, "Me: " + msg)
.sendToTarget();
else
MainActivity.IncomingHandler.obtainMessage(0, 0, -1,
"Disconnecting!").sendToTarget();
} catch (Exception ioException) {
ioException.printStackTrace();
}
}
Now it says "non-static method obtainMessage cannot be referenced from a static context”. But making IncomingHandler non-static makes the whole thing pointless. Is there anyway I can use obtainMessage from a static context?
EDIT1: I tried to add static IncomingHandler incoming = new IncomingHandler(MainActivity.this);
and used MainActivity.incoming.obtainMessage();
but it said "MainActivity.this cannot be referenced from a static context" so commenters' suggestions don't work for me.
EDIT2: I was dumb, I forgot to remove "MainActivity" from MainActivity.incoming.obtainMessage()
. The problem is still there though.