处理程序无法处理消息

时间:2016-03-08 11:11:45

标签: java android multithreading handler

我在非ui线程(SomeThread)中有两个方法,并通过处理程序(SomeHandler)触发这些方法。我启动线程然后通过处理程序发送消息来调用SomeThread的方法。

问题是,在调用 startWork 方法后,处理程序再也不会处理消息,因此我无法运行 stopWork 方法

问题:我如何运行 stopWork 方法?

我的主题

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;
    }
}

我的处理程序

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;
        }
    }
}

使用它们

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();

0 个答案:

没有答案