简体   繁体   中英

Android loading image from url performance

I have classic AsyncTask to load image:

private class DownloadImageTask extends AsyncTask<String,Void,Bitmap> {

    Bitmap  bitmap = null;

    @Override
    protected Bitmap doInBackground(String... str) {
        try{   

            InputStream in = new java.net.URL(picture).openStream();
            bitmap = BitmapFactory.decodeStream(new SanInputStream(in));
            //viewPicture.setImageBitmap(bitmap);
            viewPicture.setBackgroundDrawable(new BitmapDrawable(bitmap));


        }
        catch(Exception e){
            e.printStackTrace();
        }
        return bitmap;
    }
}

But loading of image is to long. When I start this activity, everything is loaded besides image and only after waiting a second I can see it. What is the problem?

Simple... because it takes time to open connection to the resource URL and download all the required bytes. Moreover, the performance may also vary on the speed of your Internet connection.

viewPicture.setBackgroundDrawable(new BitmapDrawable(bitmap));

should be done on the UI thread, in the onPostExecute method of your AsyncTask.

Also, close the stream (if !null) you use with a nice finally block of your try/catch.

And don't worry about the time, it's the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM