Reputation: 12721
i ahve a problem with a thread handler receiving a message. all other thread i implemnted this pattern works fine. here my code:
Start thread
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 class
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");
}
}
The "thread started, "race added" and "message sent" logs appear in logcat, but not the "message received" in the handler.
Upvotes: 3
Views: 4941
Reputation: 301
I know this is an old question, but Google.
The problem is that you created the Handler in the UI thread. It then receives messages on that thread. You need to create the Handler in the new thread:
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();
Upvotes: 2
Reputation: 12721
well, I dunno why, but dispatchMessage() instead of sendMessage() solved the problem...
Upvotes: 6