异步下载图片

布局文件

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
   />
   
<ImageView 
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:id="@+id/imagedownload"
   />
<Button 
   android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:id="@+id/btn_imagedown"
        android:text="下载图片"
   />

</LinearLayout>


ManiActivity代码

package com.csdn.hbsi;


import com.csdn.hbsi.AsyncImageDownTask.An;


import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;


public class MainActivity extends Activity {


private ImageView imageview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview = (ImageView) findViewById(R.id.imagedownload);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void click(View v){

String url="http://csdnimg.cn/www/images/csdnindex_logo.gif?";

AsyncImageDownTask aidt=new AsyncImageDownTask(new An() {

@Override
public void imagedownloadbefore() {
// TODO Auto-generated method stub
imageview.setImageResource(R.drawable.defaultlogo);
}

@Override
public void imagedownloadAfter(Bitmap bmp) {
// TODO Auto-generated method stub
imageview.setImageResource(R.drawable.fengjing);
}
});
aidt.execute(url);
}


}

新的类AsyncImageDownTask

package com.csdn.hbsi;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.Toast;


public class AsyncImageDownTask extends AsyncTask<String, Void, Bitmap> {

private An imageview;
public AsyncImageDownTask(An _an){
this.imageview=_an;
}
/**
* @param args
*/
public interface An{
public void imagedownloadbefore();
public void imagedownloadAfter(Bitmap bmp);
}
public static void main(String[] args) {
// TODO Auto-generated method stub


}
protected void onPreExecute() {
// TODO Auto-generated method stub
//当我们点击查询以后,异步任务开始之前
imageview.imagedownloadbefore();

super.onPreExecute();
}
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
byte[] buffer=null;
System.out.println("正在后台运行中...");
String getStr="";
try {
Thread.sleep(3000);
//进行网络连接,Http的方式
HttpClient client=new DefaultHttpClient();
//定义get请求对象
HttpGet get=new HttpGet(params[0]);
//发送get请求,并且返回响应的结果
HttpResponse response=client.execute(get);
//判断是否响应完成
if(response.getStatusLine().getStatusCode()==200){
//响应的实体
HttpEntity he=response.getEntity();
//读取返回的数据流
InputStream is=he.getContent();
//将返回的输出流,转化为字节数组,最后构造一个新的字符串
buffer=AsyncImageDownTask.getByteData(is);
getStr=new String(getByteData(is),"GBK");

System.out.println("======"+getStr);

}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
imageview.imagedownloadAfter(result);

super.onPostExecute(result);
}
/**

* 根据InputStream 返回二进制的流数组
* @param is
* @return
*/
public static byte[] getByteData(InputStream is){

//声明一个ByteArrayOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
   try {


//定义缓冲区
byte[] buffer = new byte[1024];
//读取is中的数据,写入到bos中
int len = -1;
while ((len = is.read(buffer)) != -1) {


//写入到bos中
bos.write(buffer, 0, len);


}

is.close();

bos.close();
} catch (Exception e) {
e.printStackTrace();
}
 
 return bos.toByteArray();

}





}

另外在drawable中添加两张图片

加internet权限

你可能感兴趣的:(异步下载图片)