我目前正在为android平台编写一个应用程序
要求
安装的SD卡(或
外部存储
)我知道这可能不是需要这样的东西的最佳方式,但是应用程序将处理大量数据,我甚至不想考虑将这些数据存储在设备的存储中。
无论如何,为了确保应用程序不会在没有外部存储的情况下运行,我快速检查了活动
onCreate
方法。如果没有安装卡,我想显示一条错误消息,然后退出应用程序。
我目前的做法是这样的:
public void onCreate ( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.main );
try
{
// initialize data storage
// will raise an exception if it fails, or the SD card is not mounted
// ...
}
catch ( Exception e )
{
AlertDialog.Builder builder = new AlertDialog.Builder( this );
builder
.setMessage( "There was an error: " + e.getMessage() )
.setCancelable( false )
.setNeutralButton( "Ok.", new DialogInterface.OnClickListener()
{
public void onClick ( DialogInterface dialog, int which )
{
MyApplication.this.finish();
}
} );
AlertDialog error = builder.create();
error.show();
return;
}
// continue ...
}
当我运行应用程序,并引发异常(我手动引发它以检查是否一切正常)时,错误消息将正确显示。但是,当我按下按钮时,应用程序关闭,我得到一个android错误,应用程序意外关闭(我应该强制退出)。
在关闭应用程序之前,我读过一些主题,我知道可能不应该这样。但是我应该如何防止应用程序继续运行呢?发生错误时如何正确关闭应用程序?