为什么handleMessage在ui线程中运行当我使用后台线程循环程序创建处理程序时?

时间:2019-06-29 09:39:40

标签: java android multithreading

当我使用后台线程循环程序创建处理程序时,为什么handleMessage在ui线程中运行?该循环程序不属于ui线程,但是alertdialog正确显示并且没有崩溃,但是应该给出错误。

请问如果问题不清楚,因为我不太会英语

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 个答案:

答案 0 :(得分:0)

looper=thread.getLooper();,此循环程序仍在主线程上运行。因此,使用该循环程序创建的Handler还会处理主线程中的消息。

如果您要创建一个Handler来处理后台线程中的消息。

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