Setting the background of an Activity
In the onCreate() method of my Activity, I grab the outermost LinearLayout of the Activity's layout. I then check to see what the orientation of the phone is. If it is portrait, I set the background image of the LinearLayout to one image; if it is landscape, I set the background image of the LinearLayout to another image.
A user reported that if they open and cl开发者_如何学编程ose their hardware keyboard several times, the application will crash. The resulting log shows an OutOfMemoryError (bitmap size exceeds VM budget) error deep down in the bowels of setBackgroundResource called from onCreate().
Am I doing something wrong here? Is there a built in way to have Android handle this?
If it is useful, the log also shows about 2 dozen "unexpected resumes" just above the crash. This is the user opening and closing the hardware keyboard.
Override the onConfigurationChange() method, since the changes in layout are handled with this method.
@Override
public void onConfigurationChanged(Configuration newConfig) {
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
{
//change of background
}
else if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT)
{
//change the background
}
else
{ //do nothing, this might apply for the keyboard }
super.onConfigurationChanged(newConfig);
}
}
and add this to your manifest
<activity android:name=".YourActivity"
android:configChanges="keyboardHidden|orientation"
android:label="@string/app_name">
When you load the background image in onCreate
, save a reference to it. I'm assuming its a Bitmap, so in onDestroy
call recycle
on the Bitmap and you should be fine.
That happens because the previous image remains in memory until the garbage collector clean it, and everytime the user open an close the keyboard, a new activity is created and a new instance of an image is done. So to prevent that crash, clean the memory on your activity. Use what Femi said, in case it is a bitmap, or force a call to the garbage collector
精彩评论