Android SDK - running functions in the background

北慕城南 提交于 2019-12-10 18:16:40

问题


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

回答1:


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

}



回答2:


Take a look at this page:

Progress Bar Reference

Greetings




回答3:


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

    }
  }).start();
}

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



来源:https://stackoverflow.com/questions/5168748/android-sdk-running-functions-in-the-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!