Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/205.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何使用异步任务_Android - Fatal编程技术网

Android 如何使用异步任务

Android 如何使用异步任务,android,Android,我正在尝试使用一个线程在后台做一些需要几秒钟的工作。 我试图显示一个进度对话框,但它根本不显示 我认为使用异步任务会更好,但无论何时尝试,我都无法让它工作,主要是因为我无法访问需要在异步任务中修改的变量 以下是我的线程,单击按钮时调用该线程: Thread thread = new Thread() { @Override public void run() { try {

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

我认为使用异步任务会更好,但无论何时尝试,我都无法让它工作,主要是因为我无法访问需要在异步任务中修改的变量

以下是我的线程,单击按钮时调用该线程:

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

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

您可以这样使用:

 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  
        }  

}
公共类web\u api\u get\u线程扩展异步任务{
private ProgressDialog ProgressDialog=新建ProgressDialog(上下文);
InputStream InputStream=null;
字符串结果=”;
受保护的void onPreExecute(){
progressDialog.show();
progressDialog.setCancelable(真);
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
StringBuilder=新的StringBuilder();
//做你的工作
返回builder.toString();
}//受保护的Void doInBackground(字符串…参数)
受保护的void onPostExecute(字符串){
此.progressDialog.discouse()文件;
//在这里查看您的结果
}  
}

这里我们称之为带有活动上下文的AsyncTask,当
AsyncTask
在后台运行时,它将馈送到AsyncTask,以在这些活动中显示
ProgressDialog

public void onCreate(Bundle savedInstanceState)
{
 SpinnerDataTask spinnerDataTask = new SpinnerDataTask(this);
 spinnerDataTask.execute(null);
}
AsyncTask的方法用于在
doInBackground()
中进行后台工作,并将结果发布到
onPostExecute()
。要在AsyncTask开始工作时显示视图,
onPreExecute()
非常适合在后台显示某些东西正在工作


私有类SpinnerDataTask扩展了AsyncTask
{
语境;
公共SpinnerDataTask(上下文){
//TODO自动生成的构造函数存根
this.context=上下文;
}
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
pDialog=新建进度对话框(上下文);
setMessage(“请稍候…”);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
//TODO自动生成的方法存根
试一试{
用于(字符串s:dLinks){
字符串pathToFile=s.substring(1));
add(dFs.fetchLink(pathToFile,false.toString());
}
}捕获(DbxException e){
dURL=null;
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
if(pDialog.isShowing())
{
pDialog.disclose();
}
}
}
导入java.io.BufferedReader;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.impl.client.DefaultHttpClient;
导入de.vogela.android.asyntask.R;
导入android.app.Activity;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.TextView;
公共类ReadWebpageAsyncTask扩展活动{
私有文本视图文本视图;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView=(textView)findViewById(R.id.TextView01);
}
私有类下载WebPagetTask扩展异步任务{
@凌驾
受保护的字符串doInBackground(字符串…URL){
字符串响应=”;
for(字符串url:url){
DefaultHttpClient=新的DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(url);
试一试{
HttpResponse execute=client.execute(httpGet);
InputStream内容=execute.getEntity().getContent();
BufferedReader buffer=新的BufferedReader(新的InputStreamReader(内容));
字符串s=“”;
而((s=buffer.readLine())!=null){
响应+=s;
}
}捕获(例外e){
e、 printStackTrace();
}
}
返回响应;
}
@凌驾
受保护的void onPostExecute(字符串结果){
setText(结果);
}
}
公共void onClick(视图){
DownloadWebPagetTask=新建DownloadWebPagetTask();
task.execute(新字符串[]{”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>


请参阅:

若要从另一个线程访问UI元素,请使用
runOnUiThread()
处理程序
,这可能会有所帮助。。。。我不确定我是否能够使用异步任务,是否可以使用上面的代码并显示进度条,只是让用户知道发生了什么事情……使用
JSONObject
作为参数。。。。我认为可能是返回类型和
URI
作为这样的参数<代码>私有类SpinnerDataTask扩展AsyncTask
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>