【问题标题】:Android thread handler not receiving messageAndroid线程处理程序未收到消息
【发布时间】:2012-04-03 11:06:38
【问题描述】:

我遇到了一个线程处理程序接收消息的问题。我实施此模式的所有其他线程都可以正常工作。这是我的代码:

启动线程

InternalScoresThread t = new InternalScoresThread(
    this.game.getApplicationContext(),
    this.map.fileName, this.map.getCurrentTime(),
    new Handler() {

        @Override
        public void handleMessage(Message msg) {

            Log.d("DEBUG", "message received");

            if (msg.getData().getBoolean("record")) {

                Player.this.showtRecordMessage();

            } else {

                Player.this.showtFinishMessage();
            }

            Player.this.showTimeMessage();
            Player.this.showRestartMessage();
        }
});

t.start();

线程类

public class InternalScoresThread extends Thread {

    private Handler handler;
    private String map;
    private float time;
    private Context context;

    public InternalScoresThread(Context context, String map, float time, Handler handler) {

        this.context = context;
        this.handler = handler;
        this.map = map;
        this.time = time;
    }

    @Override
    public void run() {         

        Log.d("DEBUG", "thread started");

        Database db = Database.getInstance(this.context);
        float bestTime = db.getBestTime(this.map);
        db.addRace(this.map, this.time);

        Log.d("DEBUG", "race added");

        Message msg = new Message();
        Bundle b = new Bundle();
        b.putBoolean("record", this.time < bestTime || bestTime == 0);
        msg.setData(b);
        this.handler.sendMessage(msg);

        Log.d("DEBUG", "message sent");
    }
}

“线程已启动”、“已添加竞争”和“已发送消息”日志显示在 logcat 中,但未显示“已接收消息”在处理程序中。

【问题讨论】:

    标签: android multithreading handler


    【解决方案1】:

    嗯,我不知道为什么,但是 dispatchMessage() 而不是 sendMessage() 解决了问题...

    【讨论】:

    • 您对为什么会发生这种情况有任何其他解释吗?我大约有 50% 的时间看到这个问题
    • dispatchMessage() 直接在同一个线程中调用handleMessage(),所以并没有真正解决线程间通信的问题。
    • @Memetic 所说的是正确的。如果您计划在收到消息时更新任何 UI,使用 dispatchMessage(Message) 将立即引发错误。您可以尝试使用sendMessageAtFrontOfQueue(Message)。就我而言,我一个接一个地调用了两个都使用消息传递的方法。使用倒数计时器将第二个方法调用延迟 3 秒即可解决问题。
    【解决方案2】:

    我知道这是一个老问题,但谷歌。

    问题是您在 UI 线程中创建了处理程序。然后它在该线程上接收消息。您需要在新线程中创建 Handler:

    public void run() {
        Log.d("DEBUG", "creating Handler in thread " + Thread.currentThread().getId());
        Looper.prepare();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.d("DEBUG", "message received");
            }
        };
        Looper.loop();
    

    【讨论】:

    • 为什么这是个问题?他想要 UI 线程中的处理程序,因为他必须更新 UI。
    • 也许我的回答可以措辞更好。关键是他在同一个线程上发送和接收消息。处理程序不是在新线程上侦听,而是在创建它的旧线程上(稍后发送消息)。我很确定他正在尝试向新线程发送消息。
    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多