Search code examples
androidhandler

Android - Why my handler cannot receive message


I new a Thread in my CountService to make the variable "count" to ++ . Now I want to send message from the thread, and I would like to use Handler to do this. But I found that my handler cannot receive the message. Let me put the main code in CountService:

This is the onStartCommand(), and in it is a timerStart() to count and send message:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    timerStart();
    return super.onStartCommand(intent, flags, startId);
}

public void timerStart(){
    Thread thread = new Thread(){
        public void run(){
            try{
                while (true){
                    sleep(1000);
                    count++;
                    Log.d(TAG, String.valueOf(count));
                    Message msg = handler.obtainMessage();
                    msg.what=UPDATE_COUNT;
                    msg.arg1=count;
                    handler.sendMessage(msg);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    };
    thread.start();
}

and here is the handler:

private Handler handler = new Handler() {
    public void handlerMessage(Message msg){
        switch (msg.what){
            case UPDATE_COUNT:
                int notification_count = msg.arg1; 
                manager.notify(NOTIFY_ID, notification);
                break;
            default:
                break;
        }
    }
};

All these above happens when i click the "Start" button, and here is the onClick()

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.mini_button_start:
            Intent startIntent = new Intent(this, CountService.class);
            startService(startIntent);
            break;
        case R.id.mini_button_stop:
            Intent stopIntent = new Intent(this, CountService.class);
            stopService(stopIntent);
            break;
        default:
            break;
    }
}

So what happened to the handler?


Solution

  • You missed the override method, that's why your handleMessage not called

        private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPDATE_COUNT:
                    int notification_count = msg.arg1;
                    Log.d(TAG, "onStartCommand: "+  notification_count);
                default:
                    break;
            }
        }
    
    };