嘗試使用此,它實現了的AsyncTask做的東西在後臺(需要Android 4.0以上版本):
class loadimage extends AsyncTask<Void, Void, Void> {
ProgressDialog pdLoading = new ProgressDialog(YourClass.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("Loading Image...");
pdLoading.show();
}
@Override
protected void doInBackground(Void... params) {
String stringurl = "http://imgur.com/1awAsRh"
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(stringurl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pdLoading.dismiss();
// do what you want with your bitmap
return null;
}
}
然後在這樣調用你的onCreate
:
new loadimage().execute();
您還需要確保您的清單中包含以下內容:
<uses-permission android:name="android.permission.INTERNET" />
正是像我一樣,但線 位圖位= BitmapFactory.decodeStream( (InputStream)new URL(stringurl).getContent()); 返回null。應該是因爲img是http://i.imgur.com/1awAsRh.jpg而不是http://imgur.com/1awAsRh –