Search code examples
androidlayoutonpause

Avoid black background during changing activities when calling setbackgroundresources(0) in the onPause?


I have a problem that I wasn't able to fix, whenever I call the setbackgroundresources(0) on a layout in the onPause method there is a 1 second time where my background becomes black but all the others components remain. I'm trying to free up some memory and this is the only method that I tried till now. Is there anyway to avoid this kind of problem?

This is the code:

protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();

        relativelayout.setBackgroundResource(0);            
}

Solution

  • Ok guys, I've just figured out how to avoid that black background during activities switch! First of all I've decoded the background image of the XML layout with this code:

    xmlbackground= BitmapFactory.decodeResource(this.getResources(), R.drawable.xmlbackgroundimage);
    

    Second, in the onPause method I've recycled the bitmap:

        @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();        
        xmlbackground.recycle();
        xmlbackground= null;
    }
    

    After this the Bitmap was recycled properly but when I was returning to this activity, my app would crash therefore I've fixed this issue with this lines of code:

        @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (xmlbackground== null || xmlbackground.isRecycled()){xmlbackground=BitmapFactory.decodeResource(this.getResources(), R.drawable.xmlbackgroundimage);}
    
    }
    

    Now everything works fine and my memory management problem was fixed for now.