简体   繁体   中英

Display progress dialog till a condition will be true or time ended

I have an app that user submit the log in form , when it sent the data to server and create a connection for its account.

In this connection i have an integer field named as state .
the state value is : 1 for connecting , 2 for connected and 0 for failed .

I want to show a dialog to user show is Connecting ... and then check the state of connection if its return 0 or 2 dismiss the dialog and show the related message else if it doesn't change after 15 sec dismiss dialog and change the state to 0 !

How can i do this logic ?

I am assuming to make the network all you are using an Asynctask. In this case you can use the methods onPreExecute and onPostExecute.

For more information about network calls and Asynctasks, please read http://developer.android.com/training/basics/network-ops/connecting.html . I've given a brief explanation below though.

If you create a dialog or initialise it in your onCreate method (or something similar), you can call the below methods to show and hide the dialog when the call starts and finishes

onPreExecute() {
    dialog.show();
}

onPostExecute(Object result) {
    dialog.dismiss();
}

You can also modify the UI from doInBackground through the use of onProgressUpdate(). This will allow you to call to the dialog whilst performing the logic in doInBackground by calling the method publishProgress(). The exact place you should call the method I'm not sure of because I don't fully understand your bigger picture but I hope this helps you along the way

This is one way.You could also use AsyncTask.onCancelled()

public class TestActivity extends Activity{
    private Dialog dialog;
@override
protected void onCreate(Bundle bundle){
    //relevant activity code.
    TestAsync ta=new TestAsync().execute();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            ta.cancel();
            if(dialog!=null)
                dialog.dismiss();
        }
    }15*1000);

}


public class TestAsync extends AsyncTask<Void, Void, Void> {




@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    //create your dialog here

}

@Override
protected void onPostExecute(Void result) {

    if(dialog!=null){
        dialog.dismiss();
    }
}

@Override
protected Void doInBackground(Void... params) {
    //relevant AsyncTask code
}


}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM