why handleMessage run in ui thread While I created handler with background thread looper?

Viewed 481

why handleMessage run in ui thread while I created handler with background thread looper? this looper does not belong to the ui thread but alertdialog is shown correctly and without crashing, while an error should be given.

Excuse me if the question is not clear, because I do not know English well

public class ToastService extends Service {

    private HandlerThread thread;
    private Looper looper;
    ServiceHandler handler;
    public static int num=0;
    int idd=0;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("say","created");
        thread=new HandlerThread("mhm", Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
        looper=thread.getLooper();
        handler=new ServiceHandler(looper);
    }

    @Override
        public int onStartCommand(Intent intent, int flags, int startId) {




        int messageIntent=0;
        if (intent!=null){
            messageIntent=intent.getIntExtra("myMessage",0);
            Log.i("sayonStartCommand",messageIntent+"");
        }

        Toast.makeText(this, "ook", Toast.LENGTH_SHORT).show();
        Message message=new Message();
        idd=messageIntent;
        message.what=0;
        message.arg1=startId;

        Bundle bundle=new Bundle();
        bundle.putInt("say",messageIntent);
        message.setData(bundle);

        handler.sendMessage(message);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.i("say","finish xxxxxxxxxxxxxxxxxx");
        super.onDestroy();
    }

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }
        @Override
        public void handleMessage(Message msg) {
           new AlertDialog.Builder(MainActivity.mcontext)
                .setTitle("ok")
                .setMessage("message").show();
            int i=msg.getData().getInt("say");
            Log.i("say",i+"");
            if (idd==3){
                stopSelf(msg.arg1);
            }
        }
    }
}
1 Answers

looper=thread.getLooper(); this looper still runs on the main thread. So the Handler created with that looper also handles message in the main thread.

If you want to create a Handler that handles messages in the background thread.

 class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }
Related