来自 Looper.getMainLooper 的处理程序未收到消息



我在其onCreate函数中创建了一个活动和一个处理程序,如下所示:

private Handler mHandler;
private Button helloBtn;
private TextView helloText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(...);

    helloBtn = (Button)findViewById(R.id.hello);
    helloBtn.setOnClickListener(this);
    helloText = (TextView)findViewById(R.id.text);
    mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_REPORT_PROGRESS:
                    int progress = msg.arg1;
                    seekBar.setProgress(progress);
                    break;
                case MSG_HELLO:
                    helloText.setText("hello world");
                    break;
            }
        }
    };
}
public void onClick(View view) {
    if(view == helloBtn)
    {
        Handler mainHanlder = new Handler(Looper.getMainLooper());
        Message msg = new Message();
        msg.what = MSG_HELLO;
        mainHandler.sendMessage(msg);
    }
}

当 helloBtn 被点击时,mainHandler 没有收到消息。为什么?如果我直接使用 mHandler 来替换 mainHandler,它就可以工作,为什么?

使用以下

代码...并让我知道反馈。要显示文本,不需要处理程序。

/** The m handler. */
private Handler mHandler;
/** The hello btn. */
private Button helloBtn;
/** The hello text. */
private TextView helloText;
/** The msg hello. */
private final int MSG_HELLO = 2;
/*
 * (non-Javadoc)
 * 
 * @see android.app.Activity#onCreate(android.os.Bundle)
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    helloBtn = (Button) findViewById(R.id.btn_hello);
    helloBtn.setOnClickListener(this);
    helloText = (TextView) findViewById(R.id.txt_hello);
    mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_HELLO:
                helloText.setText("hello world");
                break;
            }
        }
    };
}
/*
 * (non-Javadoc)
 * 
 * @see android.view.View.OnClickListener#onClick(android.view.View)
 */
public void onClick(View view) {
    if (view.getId() == R.id.btn_hello) {
        Message msg = new Message();
        msg.what = MSG_HELLO;
        mHandler.sendMessage(msg);
    }
}

类 Message 有一个字段"target",用于存储用于发送消息的处理程序。调用处理程序的 sendMessage(msg) 方法时,处理程序的引用将存储在消息中。当 Looper 调度你的消息时,它会调用 msg.target.dispatchMessage(msg),这意味着你的 msg 将被调度到你用来发送它的同一个处理程序。方法dispatchMessage(msg)最终将调用handleMessage(msg)。

您可以使用广播接收器来解决您的问题。在将来要更新的活动中注册广播接收器,并从应用的其他部分向其发送广播。

相关内容

最新更新