重复的处理程序消息?

时间:2012-07-01 10:11:02

标签: android duplicates handler

当我在后台多次调用addAdapter()时,有时会收到一些重复的消息。例如当我调用addAdapter(item1,item2,item3 ...)时,它会打印item1,item2,item2 ......

ExaminationItem currentAddItem = null;


private void addAdapter(ExaminationItem item)
{
    currentAddItem = item;
    addhandler.sendEmptyMessage(1);
}

private Handler addhandler = new Handler() {
    @Override
    public void handleMessage(Message msg)
    {
        switch (msg.what) {
        case 1:
            if (currentAddItem != null) {
                _adapter.add(currentAddItem);
                Log.i(getClass().getName(), "---------------------------addhandler: currentAddItem._itemName = " + currentAddItem._itemName);
            }
            break;
        default:
            break;
        }

    }
};

2 个答案:

答案 0 :(得分:1)

这并不奇怪。每次调用sendEmptyMessage()时,都会向线程的消息队列添加消息。您不是要将项目添加到队列中,而是只是向处理程序发送一条消息,以便在处理程序处理消息时访问currentAddItem的任何值。它无法看到您发送邮件时的值。因此,您可能会看到跳过的项目和重复的项目。

答案 1 :(得分:0)

private void addAdapter(ExaminationItem item)
{
    Message message = addhandler.obtainMessage();
    message.what = 1;
    message.obj = item;
    addhandler.sendMessage(message);
}

private Handler addhandler = new Handler() {
    public void handleMessage(Message msg)
    {
        switch (msg.what) {
        case 1:
            if (msg.obj != null) {
                _adapter.add((ExaminationItem) msg.obj);
                examination_scanner_detail_tv.setText("detect to keep fit.");
                Log.i(getClass().getName(), "addhandler: msg.obj = " + msg.obj);
            }
            break;
        default:
            break;
        }
    }
};