以下代码仅能在ImageView中显示图片,
请问如何实现下载图片至私有目录?package cn.zhangyazhou.izanmeishi;import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;public class Utils extends Activity {private ImageView ImageView;protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);new MyTask().execute("http://www.zhangyazhou.cn/xinbianzanmeishi/1.jpg");
}@SuppressLint("NewApi")
class MyTask extends AsyncTask<String, Void, Bitmap> {@Override
protected Bitmap doInBackground(String... params) {String path = params[0];
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setDoInput(true); // 读或写
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
Log.i("TEST", "内容长度:" + conn.getContentLength());
Log.i("TEST", path);
InputStream is = conn.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
return bmp;
} else { // 如果联网失败}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null; // 返回空
}// 主程序
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
ImageView.setImageBitmap(result);
} else {
Toast.makeText(Utils.this, "简谱下载失败,可能网络状况较差……",
Toast.LENGTH_LONG).show();
}
super.onPostExecute(result);
}
}}