finish是Activity的類,僅僅針對Activity,當調用finish()時,隻是将活動推向背景,并沒有立即釋放記憶體,活動的資源并沒有被清理;當調用System.exit(0)時,殺死了整個程序,
這時候活動所占的資源也會被釋放。
在開發android應用時,常常通過按傳回鍵(即keyCode == KeyEvent.KEYCODE_BACK)就能關閉程式,其實大多情況下該應用還在任務裡運作着,其實這不是我們想要的結果。
我們可以這樣做,當使用者點選自定義的退出按鈕或傳回鍵時(需要捕獲動作),我們在onDestroy()裡強制退出應用,或直接殺死程序。
[java] view plain copy print ?
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- //按下鍵盤上傳回按鈕
- if(keyCode == KeyEvent.KEYCODE_BACK){
- new AlertDialog.Builder(this)
- .setIcon(R.drawable.services)
- .setTitle(R.string.prompt)
- .setMessage(R.string.quit_desc)
- .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- }
- })
- .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- finish();
- }
- }).show();
- return true;
- }else{
- return super.onKeyDown(keyCode, event);
- }
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- System.exit(0);
- //或者下面這種方式
- //android.os.Process.killProcess(android.os.Process.myPid());