如何使用异步任务

时间:2014-04-01 11:24:56

标签: android

我正在尝试使用一个线程在后台做一些工作,这需要几秒钟。 我试图显示一个进度对话框,但它根本没有显示。

我认为最好使用Async任务但是每当我尝试时我都无法使用它,主要是因为我无法访问我需要在Async任务中修改的变量。

这是我单击按钮时调用的线程:

  Thread thread = new Thread()
        {
            @Override
            public void run() {
                try {

                    for (String s : dLinks) {
                        String pathToFile =  s.substring(1));
                        dURLs.add(dFs.fetchLink(pathToFile, false).toString());
                    }

                } catch (DbxException e) {
                    dURL = null;
                    e.printStackTrace();
                }
            }
        };

        thread.start();
        try {
            thread.join(); // I added this as the next part of my code was executing before the thread was finished
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

我可以将其移动到异步任务,更新进度条或至少显示微调器并将数组dURL传回主线程吗?

3 个答案:

答案 0 :(得分:0)

你可以像这样使用:

 public class web_api_get_thread  extends AsyncTask<String, String, String> {

    private ProgressDialog progressDialog = new ProgressDialog(context);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {

        progressDialog.show();
        progressDialog.setCancelable(true);

    }

    @Override
    protected String doInBackground(String... params) {

        StringBuilder builder = new StringBuilder();
        //do your work
        return builder.toString(); 
    } // protected Void doInBackground(String... params)


        protected void onPostExecute(String string) {
 this.progressDialog.dismiss();
            // see your result here  
        }  

}

答案 1 :(得分:0)

这里我们使用活动的上下文 this 调用AsyncTask,它将提供给AsyncTask以在这些Activity中显示ProgressDialog,而AsyncTask在后​​台运行。

public void onCreate(Bundle savedInstanceState)
{
 SpinnerDataTask spinnerDataTask = new SpinnerDataTask(this);
 spinnerDataTask.execute(null);
}

AsyncTask具有用于在doInBackground()中执行后台工作并将结果发布在onPostExecute()中的方法。要在AsyncTask开始工作时显示视图,onPreExecute()非常适合显示某些内容在后台工作。


private class SpinnerDataTask extends AsyncTask<Void Void, Void>
{
    Context context;
    public SpinnerDataTask(Context context) {
        // TODO Auto-generated constructor stub
        this.context = context;
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {
                for (String s : dLinks) {
                    String pathToFile =  s.substring(1));
                    dURLs.add(dFs.fetchLink(pathToFile, false).toString());
                }

            } catch (DbxException e) {
                dURL = null;
                e.printStackTrace();
            }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
           if (pDialog.isShowing())
           {
                pDialog.dismiss();
           }
    }
}

答案 2 :(得分:0)

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import de.vogella.android.asyntask.R;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class ReadWebpageAsyncTask extends Activity {
  private TextView textView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView = (TextView) findViewById(R.id.TextView01);
  }

  private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      return response;
    }

    @Override
    protected void onPostExecute(String result) {
      textView.setText(result);
    }
  }

  public void onClick(View view) {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] { "http://www.vogella.com" });

  }
} 

创建以下布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/readWebpage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Load Webpage" >
    </Button>

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Placeholder" >
    </TextView>

</LinearLayout>

请参阅:http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html