如何在 android 中退出应用程序时创建弹出窗口 window 进行确认,同时处理多个活动

How to create a popup window for confirmation while exiting an app in android when working wth multiple activities

我在 Android 从事许多活动。 我需要的是,在退出应用程序时,它应该弹出确认是否退出。 我知道只在 java 中不使用任何 .xml 文件就可以创建弹出窗口 window。 我也知道如何在仅使用一个 activity 或单击事件时执行以下操作。 但在多个活动的情况下,通过单击后退按钮,它不起作用。

首先,您应该只询问用户有关退出主程序(启动器 Activity)的问题,因为后退按钮应该始终让用户返回到之前的 activity(如果有的话)。如果你想这样做,你应该覆盖 activity 的 onBackPressed() 方法。如果您想在所有活动中提供选项,或者如果您想在启动器 activity 中提供选项,则必须在所有活动中实施 onBackPressed()。这是例子。

@Override
public void onBackPressed() {
    AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
    ab.setTitle("myDialog");
    ab.setMessage("are you sure to exit?");
    ab.setPositiveButton("yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            //if you want to kill app . from other then your main avtivity.(Launcher)
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);

            //if you want to finish just current activity

            yourActivity.this.finish();
        }
    });
    ab.setNegativeButton("no", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
        }
    });

    ab.show();
}

其他解决方案(但有点重): 在你的 parent activity 中。

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
 if (getIntent().getBooleanExtra("closeornot", false)) {
     finish();
}
//after this you can write any other code.
}     

并且在您的其他(Child 活动)中使用 onBackPressed 如下:

@Override
public void onBackPressed() {
  Intent mIntent = new Intent(yourActivity.this, Home.class);
   mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   mIntent.putExtra("closeotnot", true);
   startActivity(mIntent);
 }