Swarnveer Swarnveer - 18 days ago 19
Android Question

Background image causing lag and frame skipping

I have a simple layout in which I want a background image. First I tried to put the background image through xml but there was very much lag.

So I followed Set image through AsyncTask but still no luck.

Image is of 1131 X 1800 resolution and size is 369kb.

I/Choreographer: Skipped 33 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 34 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 34 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 34 frames! The application may be doing too much work on its main thread.


Java File

public class MainActivity extends flights{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new LoadDrawable().execute();
}

private class LoadDrawable extends AsyncTask<Drawable, Void, Drawable> {
@Override
protected Drawable doInBackground(Drawable... params) {
//Loading the drawable in the background
final Drawable image = getResources().getDrawable(R.drawable.as);
//After the drawable is loaded, onPostExecute is called
return image;
}

@Override
protected void onPostExecute(Drawable loaded) {
//Hide the progress bar
//ProgressBar progress = (ProgressBar) findViewById(R.id.progress_bar);
//progress.setVisibility(View.GONE);
//Set the layout background with your loaded drawable
RelativeLayout layout = (RelativeLayout) findViewById(R.id.root);
layout.setBackgroundDrawable(loaded);
}

@Override
protected void onPreExecute() {}

@Override
protected void onProgressUpdate(Void... values) {}
}

}

Answer

your image size is big. a problem in set image to background is size of image and not fit resolution. i had same problem. after search and test many methods, i found glide is a good library to set a image. with this library, its not important what your device size is. the glide will set it.

for set image from your drawable, you can code like this:

 Glide.with(this).load(R.drawable.backtwo).asBitmap().into(new SimpleTarget<Bitmap>(size.x, size.y) {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                Drawable drawable = new BitmapDrawable(resource);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    iv_background.setBackground(drawable);
                }
            }
        });

another approach is using different image resolution for different device screen. weakness of this approach is increasing apk size

Comments