public class MainActivity extends ActionBarActivity {
Button b;
ImageView i;
ProgressDialog p;//進度條
String path="http://pic.nipic.com/2007-12-23/200712231523651_2.jpg";//圖片地址
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
i = (ImageView) findViewById(R.id.imageView1);
p = new ProgressDialog(this);
p.setTitle("提示信息");
p.setMessage("下載中,請稍後...");
p.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//設置進度樣式
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MyTask().execute(path);//啓動AsyncTask
}
});
}
//第一個參數是路徑
//第二個參數是進度刻度
//但三個參數是返回類型
class MyTask extends AsyncTask<String, Integer, Bitmap> {
//準備階段,一般顯示進度條
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
p.show();
}
//後臺長時間跑的邏輯業務
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bp=null;
InputStream in=null;
ByteArrayOutputStream bo=new ByteArrayOutputStream();
//設置Http協議訪問
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet =new HttpGet(params[0]);
try {
HttpResponse httpResponse=httpClient.execute(httpGet);
//當Http請求成功返回
if(httpResponse.getStatusLine().getStatusCode()==200){
in=httpResponse.getEntity().getContent();//通過流得到實體內容
long file_length=httpResponse.getEntity().getContentLength();//得到文件總容量
int len=0;//每次讀取長度
int total_length=0;//已讀取總長
byte[] data=new byte[1024];
while ((len=in.read(data))!=-1) {
total_length+=len;
int value= (int) ((total_length/(float)file_length)*100);
publishProgress(value);
bo.write(data, 0, len);
}
byte[] result=bo.toByteArray();
bp=BitmapFactory.decodeByteArray(result, 0, result.length);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//對各種流關閉
finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bo!=null){
try {
bo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return bp;
}
//時時更新UI進度條
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
p.setProgress(values[0]);
}
//doInBackground方法結束後執行此方法,對UI做最後更新
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
p.dismiss();
i.setImageBitmap(result);
}
}
}
代碼片--Android--圖片下載進度條
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.