MultiThreading issues while programing for android

后端 未结 4 569
名媛妹妹
名媛妹妹 2020-12-06 04:11

I am developing on Android but the question might be just as valid on any other Java platform.

I have developed a multi-threaded app. Lets say I have a first class t

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 04:14

    If you want to use threads rather than an AsyncTask you could do something like this:

    private static final int STEP_ONE_COMPLETE = 0;
    private static final int STEP_TWO_COMPLETE = 1;
    
    ...
    
    private doBackgroundUpdate1(){
        Thread backgroundThread = new Thread() {
            @Override
            public void run() {
                // do first step
    
                // finished first step
                Message msg = Message.obtain();
                msg.what = STEP_ONE_COMPLETE;
                handler.sendMessage(msg);
            }
        }
        backgroundThread.start();
    }
    private doBackgroundUpdate2(){
        Thread backgroundThread = new Thread() {
            @Override
            public void run() {
                // do second step
    
                // finished second step
                Message msg = Message.obtain();
                msg.what = STEP_TWO_COMPLETE;
                handler.sendMessage(msg);
            }
        }
        backgroundThread.start();
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
            case STEP_ONE_COMPLETE:
                doBackgroundUpdate2();
                break;
            case STEP_TWO_COMPLETE:
                // do final steps;
                break;
            }
        }
    }
    

    You would kick it off by calling doBackgroundUpdate1(), when this is complete it sends a message to the handler which kicks off doBackgroundUpdate2() etc.

提交回复
热议问题