开发者

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


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

}


Take a look at this page:

Progress Bar Reference

Greetings


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜