Android 添加启动画面跳转时出现 OOM
本博客地址 : http://blog.csdn.net/lys211
转载请保留。
解决方案参考使用如下链接的:
http://blog.csdn.net/shineflowers/article/details/41648745
在此感谢此博主。
最近想做一个程序启动画面的demo,使用的方法是额外添加一个Launcher Activity的方法实现。
Launcher Activity 设置为无标题栏且全屏,在2秒后启动Main Activity,并销毁 Launcher Activity.启动画面就是Launcher Activity的背景。
手机是Galaxy S3 , android 4.3
刚开始Main Activity并没有设置背景图片,一切都工作良好,但是在Main Activity设置了背景图了以后,每次在从Launcher Activity跳转到Main Activity的时候,都会出现OOM错误。
最终采取的解决方案如下:
Launcher Activity 的代码
public class LauncherActivity extends Activity {
private static String _TAG = LauncherActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_launcher);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
SoftReference<Bitmap> bitmap = new SoftReference<Bitmap>(
decodeBackgoundBitmapFromResource(
getResources(),
R.drawable.background_water_1,
metrics.widthPixels,
metrics.heightPixels
)
);
ImageView imageView = (ImageView) findViewById(R.id.launcherImageView);
if (null != bitmap) {
imageView.setImageBitmap(bitmap.get());
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
startActivity(intent);
LauncherActivity.this.finish();
}
}, 2000);
}
@Override
protected void onDestroy() {
Log.i(_TAG, "onDestroy");
System.gc();
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return false;
}
return super.onKeyDown(keyCode, event);
}
public static Bitmap decodeBackgoundBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int width = options.outWidth;
final int height = options.outHeight;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
<span style="white-space:pre"> </span>}
return inSampleSize;
}
}