Android学习篇章45-HttpClient网络下载-IO流传输-下载图片资源

来源:互联网 发布:模糊算法讲解 编辑:程序博客网 时间:2024/05/22 07:05

Mainactivity:

public class MainActivity extends Activity {ImageView img1=null;ProgressDialog dialog=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);img1=(ImageView)findViewById(R.id.img1);dialog=new ProgressDialog(this);dialog.setTitle("下载图片");dialog.setMessage("正在下载请稍候....");dialog.setCancelable(false);dialog.setMax(100);dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);}public void clickBtn(View view){      new MyDownloadImgTask().execute("http://192.168.1.151/advmgr/test.jpg");}private class MyDownloadImgTask  extends AsyncTask<String, Integer, Bitmap>{@Overrideprotected Bitmap doInBackground(String... params) {// 使用Httpclient发起get请求String path=params[0];HttpClient  client= new DefaultHttpClient();//设定get请求HttpGet  get=new HttpGet(path);try {//执行这个get请求 HttpResponse response=client.execute(get);//获得响应的entity    HttpEntity entity=response.getEntity();    //获得传回的图片数据的长度    long size=entity.getContentLength();    Log.i("test", "size="+size);    InputStream is=entity.getContent();    ByteArrayOutputStream  bos=new ByteArrayOutputStream();    byte[] buf=new byte[1024];    int length=0;    int sum=0;//用来记录已经读了多少字节的数据    while((length=is.read(buf))>0)    {    //写入到字节输出流中    bos.write(buf, 0, length);    SystemClock.sleep(10);    sum+=length;//记录总的读取的字节数    Log.i("test", "sum="+sum);    int progress=(int)(sum*100.0/size);    Log.i("test", "progress="+progress);    //更新进度    publishProgress(progress);        }   return BitmapFactory.decodeByteArray(bos.toByteArray(), 0, (int)size);} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}@Overrideprotected void onPostExecute(Bitmap result) {img1.setImageBitmap(result);//下载完毕后关闭进度对话框dialog.dismiss();super.onPostExecute(result);}//在下载任务开始之前显示进度对话框//当调用了publishProgress方法时就会更新@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubdialog.setProgress(values[0]);super.onProgressUpdate(values);}@Overrideprotected void onPreExecute() {            dialog.show();super.onPreExecute();}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <Button android:id="@+id/btn1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="clickBtn"        android:text="图片下载"        />    <ImageView android:id="@+id/img1"        android:layout_below="@+id/btn1"        android:scaleType="fitCenter"        android:layout_width="match_parent"        android:layout_height="wrap_content"    /></RelativeLayout>


权限:    <uses-permission android:name="android.permission.INTERNET"/>

原创粉丝点击