我目前正在为 Android 平台编写一个应用程序,需要安装 SD 卡(或外部存储)。我知道这可能不是要求类似内容的最佳方式,但应用程序将处理大量数据,我什至不想考虑将其存储在设备的存储上。
无论如何,为了确保应用程序在没有外部存储的情况下不会运行,我在 Activity 的 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 错误,即应用程序意外关闭(我应该强制退出)。
我之前读过一些关于关闭应用程序的主题,我知道它可能不应该发生这样的情况。但是我应该如何阻止应用程序继续运行呢?发生错误时如何正确关闭应用程序?
最佳答案
But how should I instead prevent the application from continuing to run?
完成当前的 Activity 应该没问题,就像您今天所做的那样。
How do you close the application correctly when an error occurs?
你不知道。您关闭组件( Activity 、服务等)。如果本 Activity 需要SD卡,且SD卡不可用,请结束 Activity 。
一般来说,您越少考虑 Android“应用程序”,而将 APK 中的松散耦合组件考虑得越多越好。
关于android - 出错时关闭应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2663491/