AsyncTask 异步 URL请求加载图片并保存到本地sd卡
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" >
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.ImageView;
对应java文件:
public class MainActivity extends Activity {
ImageView img;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
img = (ImageView) findViewById(R.id.img);
Aysnctask as = new Aysnctask(img);
as.execute("http://www.crazyit.org/attachments/month_1008/20100812_7763e970f822325bfb019ELQVym8tW3A.png");
}
}
新建xx.java文件做为异步:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.ImageView;
public class Aysnctask extends AsyncTask<String, Integer, Bitmap> {
ImageView imageview;
public Aysnctask(ImageView imageview) {
super();
this.imageview = imageview;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap;
try {
URL url = new URL(params[0]);
InputStream is = url.openStream();
String filestr = Environment.getExternalStorageDirectory()
.getPath();
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = new File(filestr + "/imgs.jpg");
FileOutputStream fos = new FileOutputStream(file);
byte byt[] = new byte[1024];
while (is.read(byt) > 0) {
fos.write(byt, 0, byt.length);
}
fos.flush();
fos.close();
}
InputStream is1 = url.openStream();
bitmap = BitmapFactory.decodeStream(is1);
return bitmap;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
imageview.setImageBitmap(result);
}
}