Android calling AsyncTask right after an another finished

后端 未结 7 2190
萌比男神i
萌比男神i 2020-11-28 06:15

I have some problem with Android AsyncTask. There is an Activity which contains some TextView a button and a picture. When an user entered this activity I start an asynctask

7条回答
  •  迷失自我
    2020-11-28 06:17

    I have solved this kind of problem when i had to download something from a database before login in the user into the app, with this i fixed this problem.

    To use ObservableInteger you can do this

    first declare it

    private ObservableInteger mObsInt;
    

    then in your onCreate you will have a listener waiting for the values of the mObsInt to change, after those values change you can do anything you want

    //Listener
            mObsInt = new ObservableInteger();
            mObsInt.set(0);
    
            mObsInt.setOnIntegerChangeListener(new OnIntegerChangeListener()
            {
                @Override
                public void onIntegerChanged(int newValue)
                {
                    if (mObsInt.get()==1)
                       //Do something if the first asyncTask finishes
                    if (mObsInt.get()==2){
                       //Do something if the second asyncTask finishes, in this case i just go to another activity when both asyncTasks finish
                        Intent mainIntent = new Intent().setClass(LoginActivity.this, Principal.class);
                        startActivity(mainIntent);
                        finish();
                    }
                }
            });
    

    So, how it works

    ObservableInteger will be looking for changes in the variable mObsInt, so lets say if mObsInt is equal to 1 it will do something, if is equal to 2 will do another thing, so, to solve this problem with 2 asynctasks is easy, when one of the asynctasks finishes mObsInt will be equal to 1 , if the other asyncTask finishes so mObsInt will be mObsInt++ , and then your mObsInt will be equal to 2, the listener will be waiting for the values, and then do what you want to do when the values match your if statment at the onCreate method

    now, just in your asynctasks just put in your onPostExecute() method this line

    mObsInt.set(mObsInt.get()+1);
    

    so if the first async finish, mObsint == 1 , if the second finish mObsInt == 2, and then you handle what you want to do in your onCreate method

    hope this helps for you, it helped me

    You can get more info at this doc : https://developer.android.com/reference/android/databinding/ObservableInt.html

    happy coding !

提交回复
热议问题