2012-04-03 105 views
3

我收到消息的线程处理程序存在问题。我实现这个模式的所有其他线程工作正常。在这里我的代码:Android线程处理程序未收到消息

启动线程

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(); 

Thread类

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的,但而不是处理器中的“收到的消息”。

回答

6

嗯,我不知道为什么,但dispatchMessage()inste sendMessage()的广告解决了这个问题...

+0

您对此有何发生的原因有任何其他解释吗?我在50%的时间里看到这个问题 – JuJoDi 2013-12-27 16:52:56

+1

dispatchMessage()直接调用同一线程中的handleMessage(),所以它并不真正解决线程间通信的问题。 – Memetic 2014-07-29 00:06:26

1

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

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

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(); 
+0

为什么这是一个问题?他想要UI线程中的处理程序,因为他必须更新UI。 – 2017-05-04 23:07:45

+1

也许我的回答可能更好。重点是他在同一个线程上发送和接收消息。该处理程序不在新线程上进行侦听,而是在创建它的旧线程上(稍后发送该消息)。我很确定他正在尝试将消息发送到新线程。 – Memetic 2017-05-05 21:31:22