Android stream handler not receiving message

I have a problem with a thread handler receiving a message. all other threads I have implemented work well. here's my code:

Initial flow

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

      

Theme 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");
    }
}

      

"Starting stream", "race added", and "sent messages" appear in logarithm, but not "message received" in the handler.

+3


source to share


2 answers


well i dont know why but dispatchMessage () instead of sendMessage () solved the problem ...



+6


source


I know this is an old question, but google.

The problem is that you have created a handler on the UI thread. It then receives messages on that thread. You need to create a handler on a 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();

      

+1


source







All Articles