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

时间:2012-04-03 11:06:39

标签: android multithreading 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();

主题类

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中,但不会出现在处理程序中的”消息“。

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

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

问题是您在UI线程中创建了Handler。然后它在该线程上接收消息。您需要在新线程中创建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();