finish是Activity的类,仅仅针对Activity,当调用finish()时,只是将活动推向后台,并没有立即释放内存,活动的资源并没有被清理;当调用System.exit(0)时,杀死了整个进程,
这时候活动所占的资源也会被释放。
在开发android应用时,常常通过按返回键(即keyCode == KeyEvent.KEYCODE_BACK)就能关闭程序,其实大多情况下该应用还在任务里运行着,其实这不是我们想要的结果。
我们可以这样做,当用户点击自定义的退出按钮或返回键时(需要捕获动作),我们在onDestroy()里强制退出应用,或直接杀死进程。
- @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());
-