關閉應用程序,我目前正在寫爲Android平臺需要安裝的SD卡(或ExternalStorage)的應用程序。我知道它可能不是最好的方式來要求類似的東西,但應用程序會處理大量的數據,我甚至不想考慮將其存儲在設備的存儲上。誤差
無論如何,爲了確保應用程序不會在沒有外部存儲的情況下運行,我會快速檢查活動的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錯誤,應用程序意外關閉(我應該強制退出)。
我在關閉應用程序之前閱讀了一些主題,我知道它可能不會發生這種情況。但是,我應該如何阻止應用程序繼續運行?發生錯誤時如何正確關閉應用程序?
您的代碼似乎按照您建議的方式工作。我沒有看到關於應用程序意外關閉的任何警告。也許你的問題在別處。 – 2010-04-18 20:15:31
在Eclipse中使用'adb logcat',DDMS或DDMS透視圖來查看與強制關閉錯誤相關聯的Java堆棧跟蹤。這將幫助你診斷你的問題。我同意tkryger的看法,即不會顯示您的錯誤與您在此處列出的代碼直接相關。 – CommonsWare 2010-04-18 20:32:29
噢!我在關閉未打開的數據庫的'onDestroy'處理程序中有一些較舊的代碼。這可能引發了一個例外。謝謝你的評論!但是,我仍然不太確定它是否是正確的方法,所以如果有更好的方法,請告訴我:) – poke 2010-04-18 20:35:36