Calling an AsyncTask from another AsyncTask

后端 未结 4 510
一向
一向 2020-12-05 17:41

At a certain point of my AsyncTask, after some validations have been done, I need to spawn off another thread to do some other work. So I\'d like two background threads at t

4条回答
  •  感情败类
    2020-12-05 18:21

    This can be done using message passing concurrency and a single handler. Proof of concept code follows:

    private Handler myHandler= new Handler(){
        @Override
        public void  handleMessage(Message msg){         
            switch(msg.what){
                case 0:
                    Toast.makeText(Main.this,"Message0", Toast.LENGTH_SHORT).show();
                    Thread thread= new Thread( new Runnable() {
                        public void run() {
                            try {
                                Thread.sleep(3000);
                            }
                            catch(Exception e){}
                            myHandler.sendEmptyMessage(2);
                        }       
                    });
                    thread.setDaemon(true); // <== I am a service provider. KILL ME if the non-daemon thread ConfuseText quits
                    thread.start();   
    
                break;
                case 1:
                    Toast.makeText(Main.this,"Message1", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(Main.this,"Message2", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };
    

    I launched the first thread on a button click as in:

     ON CLICK HANDLER
                threadButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Thread thread= new Thread( new Runnable() {
                        public void run() {
                            try {
                            Thread.sleep(1000);
                            }
                            catch(Exception e){ 
                            }
                            myHandler.sendEmptyMessage(0);
                            try {
                            Thread.sleep(3000);
                            }
                            catch(Exception e){ 
                            }
                            myHandler.sendEmptyMessage(1);
                        }
                    });
                    thread.setDaemon(true); // <== I am a service provider. KILL ME if the non-daemon thread ConfuseText quits
                    thread.start();
                }
    });
    

    The calls to thread sleep is to mimic a time intensive task.

提交回复
热议问题