0
我在Android中顯示來自服務器的圖像。爲此我已經通過了教程Android Load Image From URL Example。這非常有幫助。但從服務器顯示圖像需要5分鐘的時間。所以我想要異步顯示圖像。我怎樣才能做到這一點?如何在Android中異步顯示來自服務器的圖像?
我在Android中顯示來自服務器的圖像。爲此我已經通過了教程Android Load Image From URL Example。這非常有幫助。但從服務器顯示圖像需要5分鐘的時間。所以我想要異步顯示圖像。我怎樣才能做到這一點?如何在Android中異步顯示來自服務器的圖像?
試試Lazy Loading中的示例鏈接。
以下代碼段將幫助您。
DownloadHelper.java
public interface DownloadHelper
{
public void OnSucess(Bitmap bitmap);
public void OnFailure(String response);
}
MainActivity.java
public class GalleryExample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
DownloadHelper downloadHelper = new DownloadHelper()
{
@Override
public void OnSucess(Bitmap bitmap)
{
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
}
@Override
public void OnFailure(String response)
{
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
};
new MyTask(this,downloadHelper).execute("image url");
}
MyTask.java
public class DownloadTask extends AsyncTask<String, Integer, Object>
{
private Context context;
private DownloadHelper downloadHelper;
private ProgressDialog dialog;
public DownloadTask(Context context,DownloadHelper downloadHelper)
{
this.context = context;
}
@Override
protected void onPreExecute()
{
dialog = new ProgressDialog(context);
dialog.setTitle("Please Wait");
dialog.setMessage("Fetching Data!!");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
@Override
protected Object doInBackground(String... params)
{
URL aURL = new URL(myRemoteImages[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
}
@Override
protected void onPostExecute(Object result)
{
dialog.dismiss();
if (result != null)
{
downloadHelper.OnSucess((Bitmap)result);
}
else
{
downloadHelper.OnFailure("Error in Downloading Data!!");
}
super.onPostExecute(result);
}
}
你應該嘗試[Android - 通用圖像加載器](https://github.com/nostra13/Android-Universal-Image-Loader)或[在懶惰加載ListView示例中給出的ImageLoader](http://stackoverflow.com /一個/379693分之3068012) –