2

我有一个子线程正在运行以无限执行任务。我想(1)不断地将数据发送回UI线程,(2)偶尔向子线程发送数据(对应于按钮)以暂停/继续无限任务。我的问题是子线程卡在looper中,这意味着任务没有执行。

我的问题是:如何让子线程从 UI 线程接收消息而不阻塞无限任务?

这就是我目前所拥有的:对于任务 (1),我的 UI 线程中有一个处理程序,它可以工作,而子线程中有一个无限循环,它发送回一条消息,它自己工作。

在 UI 线程中:

mMainHandler = new Handler() {
    public void handleMessage(Message msg) {
        Bundle b;
        b = msg.getData();
        if (msg.what==1)
            Log.i("main", "from child (running) - " + b.getBoolean("running"));
        else if (msg.what == 2)
            Log.i("main", "from child (count) - " + b.getInt("count"));
    }
};

在子线程中(当前使用一个虚拟任务,直到我完成框架):

while (true) {
    if (running) {
        try {
            curCount += up;
            if (curCount == maxCount)
                up = -1;
            else if (curCount == minCount)
                up = 1;
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Log.e("", "local Thread error", e);
        }

        Bundle b = new Bundle(1);
        b.putInt("count", curCount);
        Message toMain = mMainHandler.obtainMessage();
        toMain.what = 2;
        toMain.setData(b);
        mMainHandler.sendMessage(toMain);
    }
}

对于任务 (2),我的 UI 线程中有一个方法,对应于按下按钮,该方法将消息发送到子线程,它可以工作,并且子线程中有一个处理程序,它自己工作。

在 UI 线程中:

private void sendRunning(boolean running) {
    if (mChildHandler != null) {
        Bundle b = new Bundle(1);
        b.putBoolean("running", running);

        Message msg = mChildHandler.obtainMessage();
        msg.what = 1;
        msg.setData(b);
        mChildHandler.sendMessage(msg);
    }
}

在子线程中:

Looper.prepare();
mChildHandler = new Handler() {
    public void handleMessage(Message msg) {
        Bundle b;
        if (msg.what==1){
            b = msg.getData();
            running = b.getBoolean("running");
            Log.i(INNER_TAG, "from main (running) - " + b.getBoolean("running"));
            Log.i(INNER_TAG, "running - " + running);
            try {
                Message toMain = mMainHandler.obtainMessage();
                toMain.what = 1;
                toMain.setData(b);
                mMainHandler.sendMessage(toMain);
            } finally {}
        }
    }
};
Looper.loop();

这些场景中的每一个都可以单独工作,但同时尝试两者都是问题所在。如果我将无限任务放在 Looper.loop() 之后,则永远无法到达。如果我把它放在 Looper.prepare() 之前,它会运行一次。如果我把它和弯针放在一起,它仍然只运行一次。

任何想法将不胜感激:)

这是我的完整代码(减去包/导入)供参考:

public class MainActivity extends Activity {

Thread thread;
private Handler mMainHandler, mChildHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mMainHandler = new Handler() {
        public void handleMessage(Message msg) {
            Bundle b;
            b = msg.getData();
            if (msg.what==1)
                Log.i("main", "from child (running) - " + b.getBoolean("running"));
            else if (msg.what == 2)
                Log.i("main", "from child (count) - " + b.getInt("count"));
        }
    };

    thread = new ChildThread();
    thread.start();

    // Get a reference to the button
    Button buttonStart = (Button)findViewById(R.id.btnStart);
    Button buttonStop = (Button)findViewById(R.id.btnStop);

    // Set the click listener to run my code
    buttonStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,
                    "Starting...", Toast.LENGTH_SHORT).show();
            sendRunning(true);
        }
    });
    buttonStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,
                    "Stopping...", Toast.LENGTH_SHORT).show();
            sendRunning(false);
        }
    });
}

private void sendRunning(boolean running) {
    if (mChildHandler != null) {
        Bundle b = new Bundle(1);
        b.putBoolean("running", running);

        Message msg = mChildHandler.obtainMessage();
        msg.what = 1;
        msg.setData(b);
        mChildHandler.sendMessage(msg);
    }
}

@Override
protected void onDestroy() {

    Log.i("tag", "stop looping the child thread's message queue");
    mChildHandler.getLooper().quit();

    super.onDestroy();

}

class ChildThread extends Thread {

    private static final String INNER_TAG = "ChildThread";
    private boolean running = true;     
    final int maxCount = 10;
    final int minCount = 0;
    public int curCount = minCount;
    private int up = 1;

    public void run() {

        while (true) {
            if (running) {
                try {
                    curCount += up;
                    if (curCount == maxCount)
                        up = -1;
                    else if (curCount == minCount)
                        up = 1;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Log.e("", "local Thread error", e);
                }

                Bundle b = new Bundle(1);
                b.putInt("count", curCount);
                Message toMain = mMainHandler.obtainMessage();
                toMain.what = 2;
                toMain.setData(b);
                mMainHandler.sendMessage(toMain);
            }

            this.setName("child");
            Looper.prepare();
            mChildHandler = new Handler() {
                public void handleMessage(Message msg) {
                    Bundle b;
                    if (msg.what==1){
                        b = msg.getData();
                        running = b.getBoolean("running");
                        Log.i(INNER_TAG, "from main (running) - " + b.getBoolean("running"));
                        Log.i(INNER_TAG, "running - " + running);
                        try {
                            Message toMain = mMainHandler.obtainMessage();
                            toMain.what = 1;
                            toMain.setData(b);
                            mMainHandler.sendMessage(toMain);
                        } finally {}
                    }
                }
            };

            Log.i(INNER_TAG, "Child handler is bound to - " +
                    mChildHandler.getLooper().getThread().getName());
            Looper.loop();
        }


    }
}

}

4

2 回答 2

0

I ended up just using a variable time for the thread to avoid the situation. Thanks for the advice.

于 2013-10-16T20:55:21.157 回答
0

只需使用 Intent 服务而不是这个线程,这样您就可以管理更新的所有 UI 以及您想在一个广播接收器正在使用的意图服务中对 UI 做什么,并且它很容易处理线程并感染您的 UI 是 nit hand 或在后台进程运行时锁定。

于 2013-10-16T05:33:06.807 回答