我的应用程序存在很多内存问题。我正在尝试捕获内存异常,然后使用toast显示内存不足的消息。
当我使用tast代码运行应用程序时,它会崩溃。当我在调试器中运行它时,不会崩溃但没有消息出现。
我正在尝试在Activty类的onCreate方法内的catch内存异常中显示消息。
代码块:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set size of card image
ImageView CardImage = ( ImageView)findViewById(R.id.viewcard);
int ScreenWidth=getWindowManager().getDefaultDisplay().getWidth();
int ScreenHeight=getWindowManager().getDefaultDisplay().getHeight();
// fix for tblets
if (ScreenHeight<ScreenWidth)
ScreenWidth=ScreenHeight;
int CardWidth=ScreenWidth/2;
CardWidth+=CardWidth/10;
// set bitmap
// Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.card2);
String FileName=new String("card");
FileName+=Integer.toString( CardId+1);
FileName+=".jpg";
// put in text that matches card
TextView mCardText = (TextView)findViewById(R.id.cardtext);
mCardText.setText( "Card Meaning \n"+ cCardText.mCardMeaning[ CardId]);
// put in text that matches card
TextView mHouseText = (TextView)findViewById(R.id.housetext);
mHouseText.setText( "House Meaning \n"+ cCardText.mHouseMeaning[ HouseId-1]);
try {
AssetManager assetManager= getAssets();
InputStream inputStream;
inputStream=assetManager.open(FileName);
Bitmap icon=BitmapFactory.decodeStream(inputStream);
CardImage.setImageBitmap(icon);
} catch( OutOfMemoryError e)
{
/////////////////////////////////////////////////////////////////////
// crashes heare
Context context = getApplicationContext();
CharSequence text = "Out of Memory ";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
gi++;
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
//scale it
// note: only code here that pertains to card image, becouse if card image cannot be loaded
// the above exceptions will go off and we will never get here
CardImage.getLayoutParams().width=CardWidth;
CardImage.getLayoutParams().height = (int)( (float) CardWidth *1.7);
}
答案 0 :(得分:1)
当你是OutOfMemory时,所有的赌注都相当多,因为那时JVM无法真正分配任何新的内存。所以它可能因为这个原因而崩溃。
您可能希望在显示消息之前尝试清除一些指针......但我从未见过有人真正尝试捕获OutOfMemory错误。
这篇文章中的第3个答案Is it possible to catch out of memory exception in java?解释了为什么尝试捕获外部存储异常是一个非常糟糕的主意。