Android线程处理程序未收到消息

问题描述 投票:3回答:3

我在线程处理程序收到消息时遇到了问题。我实现该模式的所有其他线程都工作正常。这是我的代码:

启动线程

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
3个回答
6
投票

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


1
投票

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

问题是您在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();
© www.soinside.com 2019 - 2024. All rights reserved.