为什么“msg.sendToTarget”会停止循环?

时间:2013-05-17 15:00:54

标签: java android handler

Handler hnd = new Handler(){

    @Override
    public void handleMessage(Message msg) {

        int id = sequence.get(msg.arg1);

        if(msg.arg1 % 2 == 0) {
            sq.get(id-1).setBackgroundResource(R.drawable.square_show);
        } else {
            sq.get(id-1).setBackgroundResource(R.drawable.square);
        }
    }
};

@Override
public void onResume() {
    super.onResume();

    Thread background = new Thread(new Runnable() {
        public void run() {
            try {
                for(int i = 0; i <= sequence.size()-1; i++) {
                    Thread.sleep(200);
                    Message msg = hnd.obtainMessage();
                    msg.arg1 = i;
                    msg.setTarget(hnd); // EDITED
                    msg.sendToTarget();
                    record_tv.setText(""+i);
                }
            } catch(Throwable t) {

            }
        }
    });

    background.start();
}

代码到达msg.sendToTarget(),做了它的事情,然后再也没有回来

1 个答案:

答案 0 :(得分:2)

sendToTarget();抛出一个空指针异常,你没有设置setTarget(Handler)的接收器。

另外,在你的代码中我看到了

record_tv.setText(""+i);

这一行,你的线程内部会抛出一个

android.view.ViewRoot$CalledFromWrongThreadException