如何关闭或退出Android活动

时间:2012-09-26 22:36:07

标签: android android-activity sharedpreferences buttonclick

我希望我的应用程序在启动时检查用户名和密码是否保存在sharedPreferences中。如果它检测到这些凭据,则会显示登录页面,如果没有,则会显示注册页面。在用户登录到应用程序后,我希望整个应用程序关闭,按下设备的后退按钮或按下应用程序退出按钮。

除了正确关闭应用程序之外,我还能正常工作。我以为我编码正确但我没有。当选择退出和设备后退按钮时,如何关闭整个应用程序。

退出方法:

      public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      finish();
      }
      });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
               arg0.cancel();
            }
        });
    AlertDialog alert=builder.create();
    alert.show();

3 个答案:

答案 0 :(得分:3)

按下后退按钮时,只需在活动上拨打finish()

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        finish();
    }
    return super.onKeyDown(keyCode, event);
}

答案 1 :(得分:1)

public void AppExit()
{

 this.finish();
 Intent intent = new Intent(Intent.ACTION_MAIN);
 intent.addCategory(Intent.CATEGORY_HOME);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(intent);

/*int pid = android.os.Process.myPid();=====> use this if you want to kill your activity. But its not a good one to do.
 android.os.Process.killProcess(pid);*/

 }

如果要退出应用程序,请调用此方法。

假设您想在按下后退按钮时退出应用程序,只需这样做

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    AppExit();
}
return super.onKeyDown(keyCode, event);
}

答案 2 :(得分:1)

您可以使用此代码关闭或退出您的应用程序。

android.os.Process.killProcess(android.os.Process.myPid());