我正在試圖製作一個應用程序,它將從網址下載網頁的源代碼並將其顯示在TextView。我也希望它顯示一個水平進度條而頁面正在後臺下載。我已經成功地在後臺使用Asynctask下載網頁,但我不知道如何根據後臺下載狀態找出網頁的大小並更新進度條。android-將水平進度條添加到AysncTask
這是我在做什麼,下載網頁源代碼 -
package com.example.gc;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.cd);
grabURL("http://google.com");
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
if (Error != null) {
Toast.makeText(MainActivity.this, Error, Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(MainActivity.this, "Source: " + Content, Toast.LENGTH_LONG).show();
tv.setText(Content);
}
}
}
}
請幫我顯示在我的應用程序更新水平進度條。提前致謝!