Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SDK - running functions in the background

I have a function which can vary in the time it takes to finish. I would like to display a progress dialog whilst this function is operating.

I am aware that you can use a 'Thread' to achieve this. Can someone point me in the right direction for doing this ?

EDIT: Here is the code I am using:

private class LongOperation extends AsyncTask<String, Void, String> 
{
    ProgressDialog dialog;
    public Context context;
    @Override
    protected String doInBackground(String... params) {
        if (!dialog.isShowing())
            dialog.show(); // Just in case
        return null;
    }

    /* (non-Javadoc)
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(String result) {
        dialog.dismiss();
    }

    /* (non-Javadoc)
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() 
    {
        dialog = ProgressDialog.show(context, "Working", "Getting amenity information", true);
    }

    /* (non-Javadoc)
     * @see android.os.AsyncTask#onProgressUpdate(Progress[])
     */
    @Override
    protected void onProgressUpdate(Void... values) {
      // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
     }
}

this is the Asnyc class. The user selects an option from the menu, and this is then executed:

longOperation.execute(""); // Start Async Task

GetAmenities(Trails.UserLocation); // Long function operation
like image 234
Jamie Avatar asked Apr 12 '26 16:04

Jamie


2 Answers

You should use AsyncTask for this purpose. See Android developers website and How to use AsyncTask.

Some sample code:

private class LongRunningTask extends AsyncTask<Void, Boolean, Boolean> {

    private ProgressDialog progress;

    protected void onPreExecute() {
        progress = ProgressDialog.show(yourContext, "Title", "Text");
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        return true;
    }

    protected void onPostExecute(Boolean result) {
        if(result) {
           progress.dismiss();
        }
    }

}
like image 196
Wroclai Avatar answered Apr 15 '26 05:04

Wroclai


Take a look at this page:

Progress Bar Reference

Greetings

like image 27
xlarsx Avatar answered Apr 15 '26 06:04

xlarsx