开发者

Progress dialog problem

Actually i have a problen while using progress dialog.The problem is not with the progress dialog.What i find difficult is.

I call a function onPause() of an activty say

public void onPause()
{
   super.onPause();
   setData();
}

Now onBackpressed() method i display an progressdialog, and the code i have use is

public void onBackPressed() 
{           
    final ProgressDialog progressDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
    Thread reminderThread = new Thread() 
    {
        public void run()
        {
            try
            {
                Thread.sleep(3 * 1000);
                ReminderForm.this.finish();
                progressDialo开发者_运维技巧g.dismiss();                           
            } 
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    };reminderThread.start();
 }

Now my problem is that when i enter Data and call setData() on the onPause() method it takes times to exit from at that activity.So during that time i display the progress bar when the user click back button.so these work fine but when the user enter no data then i want the progress bar to show but with less time as shown when the user enter data and call the setData() method of onPause() method.But in my case whether the user enter data or not the progressBar will take 3 sec.So is there any way where i can get the time of first thread and put that time in my second thread.


Handler.postDelayed method would be your friend in this case. Instead of spawning a new thread and executing code to perform a delay, Handler.postDelayed will allow you to set the amount of time to wait and pass in a Runnable to be executed on the UI thread.

http://developer.android.com/reference/android/os/Handler.html#postDelayed%28java.lang.Runnable,%20long%29

EDIT

Actually, I take that back. After re-reading, it seems what you want to do is save state when the user presses the back button, show a dialog during this time, and then dismiss the dialog and finish the activity when done. This is what you need:

@Override
public void onBackPressed() {
    new SaveStateTask().execute();
}

protected void saveMyActivityState() {
    // Do your stuff for however long it takes...
    // This is executing on a background thread...
}

class SaveStateTask extends AsyncTask<Void, Void, Void>
{
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(NameOfYourActivity.this, "", "Loading. Please wait...", true);
    }

    @Override
    protected void onPostExecute(Void result) {
        progressDialog.dismiss();
        NameOfYourActivity.this.finish();
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        saveMyActivityState();

        return null;
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜