1.在onCreate()方法中获取LinearLayout控件
private LinearLayout personal_bg;
personal_bg = findViewById(R.id.personal_bg);
2.在适当的地方调用如下方法:
new DownloadImageTask().execute("http://b.hiphotos.baidu.com/image/h%3D200/sign=025e31065dafa40f23c6c9dd9b65038c/10dfa9ec8a136327137e4407968fa0ec08fac777.jpg");
2.后台线程进行下载
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Drawable result) {
personal_bg.setBackgroundDrawable(result);
}
}
3.公用方法
private Drawable loadImageFromNetwork(String imageUrl) {
Drawable drawable = null;
try {
// 可以在这里通过第二个参数(文件名)来判断,是否本地有此图片
drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), null);
} catch (IOException e) {
Log.d("skythinking", e.getMessage());
}
if (drawable == null) {
Log.d("skythinking", "null drawable");
} else {
Log.d("skythinking", "not null drawable");
}
return drawable;
}