0

我在 Android 中显示来自服务器的图像。为此,我已经阅读了教程Android Load Image From URL Example。这是非常有帮助的。但是显示来自服务器的图像需要 5 分钟。所以我想异步显示图像。我怎样才能做到这一点?

4

2 回答 2

2

以下片段将为您提供帮助。

下载Helper.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");
    }

我的任务.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);
    }
}
于 2012-06-05T05:41:41.037 回答
1

尝试延迟加载中的示例链接。

于 2012-06-05T05:46:32.347 回答