Android线程处理程序没有收到消息

And*_*den 3 multithreading android handler

我遇到一个接收消息的线程处理程序的问题.我实现的所有其他线程这种模式工作正常.我的代码:

启动线程

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();
Run Code Online (Sandbox Code Playgroud)

线程类

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

"线程已启动",种族添加"和"消息发送"日志出现在logcat中,但不是"处理器中收到的"消息".

And*_*den 6

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

  • dispatchMessage()在同一个线程中直接调用handleMessage(),所以并没有真正解决线程间的通信问题。 (2认同)