I have two methods in a non-ui thread(SomeThread), and triggering these methods via a handler(SomeHandler). I'm starting the thread and then sending messages via handler to be invoked methods of SomeThread.
The problem is, after invoking startWork method, handler never handle messages again, as a result i cant run stopWork method
Question : How i can run stopWork method ?
My thread
private static class SomeThread extends Thread {
private boolean mWorking;
private volatile SomeHandler mHandler;
public SomeHandler getHandler(){
return mHandler;
}
@Override
public void run() {
Looper.prepare();
mHandler = new SomeHandler(this);
Looper.loop();
}
private void startWork(){
mWorking = true;
while(mWorking){
// Doing heavy job
}
}
private void stopWork(){
mWorking = false;
}
}
My handler
private static class SomeHandler extends Handler {
private static final int MSG_START = 0;
private static final int MSG_STOP = 1;
private final WeakReference<SomeThread> mThreadRef;
public SomeHandler (SomeThread thread){
mThreadRef = new WeakReference<>(thread);
}
public void sendPlay(){
sendEmptyMessage(MSG_START);
}
public void sendStop(){
sendEmptyMessage(MSG_STOP);
}
@Override
public void handleMessage(Message msg) {
SomeThread mThread = mThreadRef.get();
if(mThread == null) return;
switch (msg.what){
case MSG_START:
mThread.startWork();
break;
case MSG_STOP:
mThread.stopWork();
break;
}
}
}
Usage of them
SomeThread mThread = new SomeThread();
mThread.start();
// This is working
SomeHandler mHandler = mThread.getHandler();
mHandler.sendPlay();
// This is not working
SomeHandler mHandler = mThread.getHandler();
mHandler.sendStop();