2014-04-01 100 views
0

我想用一個線程在後臺花費幾秒鐘做一些工作。 我試圖顯示一個進度對話框,但它根本沒有顯示。如何使用異步任務

我認爲使用異步任務會更好,但每當我嘗試時都無法使其工作,主要是因爲我無法訪問需要在異步任務中修改的變量。

這裏是我的線程在單擊按鈕時被調用:

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到主線程?

+1

從另一個線程訪問UI元素,使用'runOnUiThread()'或'Handler' –

+0

也許這可以幫助.... http://www.vogella.com /tutorials/AndroidBackgroundProcessing/article.html – SMR

+0

我不確定我是否能夠使用異步任務,是否有使用上述代碼並顯示進度條,只是爲了讓用戶知道發生了什麼。 .. – user3437721

回答

0

在這裏,我們叫的AsyncTask與活動的上下文這將喂的AsyncTask在這些活動中的背景顯示ProgressDialogAsyncTask運行。

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

使用'JSONObject'作爲參數....我認爲它可能是返回類型和'URI'作爲這樣的參數。 'private class SpinnerDataTask extends AsyncTask '' – SMR

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 
     } 

} 
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