Android SDK - running features in the background

I have a function that can vary depending on the time it takes to complete. I would like to display a progress dialog while this function works.

I know that you can use "Thread" to achieve this. Can someone point me in the right direction for this?

EDIT: Here is the code I'm 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 done:

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

GetAmenities(Trails.UserLocation); // Long function operation
+3
source share
3 answers

For this purpose you must use AsyncTask. See Android Developer Website and How to Use AsyncTask .

Code example:

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();
        }
    }

}
+6
source

:

+1
public void onClick(View v) {
  new Thread(new Runnable() {
    public void run() {
      Bitmap b = loadImageFromNetwork();

    }
  }).start();
}

taken here http://developer.android.com/resources/articles/painless-threading.html

-1
source

Source: https://habr.com/ru/post/1795752/


All Articles