(1) define the stack, write an Exitactivity class, and manage the Activity in singleton mode.
The onCreate () method of the Activity calls the Exitactivity. getInstance (). addActivity (this) method.
Call Exitactivity. getInstance (). exit () to exit the application. This mainly creates a dialog box to exit the activity.
(2) Exitactivity class:
Package com. liuzuyi. exit; import java. util. using list; import java. util. list; import android. app. activity; import android. app. application; public class Exitactivity extends Application {private List activityList = new external List (); private static Exitactivity instance; private Exitactivity () {}// obtain the unique ExitApplication instance public static Exitactivity getInstance () {if (null = instance) {instance = new Exitactivity ();} return instance;} in singleton Mode ;} // Add the Activity to the container public void addActivity (Activity activity) {activityList. add (activity);} // traverse all activities and finish public void exit () {for (Activity: activityList) {activity. finish ();} System. exit (0 );}}
MainActivity:
Package com. liuzuyi. exit; import android. app. activity; import android. app. alertDialog; import android. app. alertDialog. builder; import android. content. dialogInterface; import android. content. intent; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. toast; public class MainActivity extends Activity {private Button ne Xt; private Button exit; int I = 0; protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); next = (Button) findViewById (R. id. button2); exit = (Button) findViewById (R. id. button1); next. setOnClickListener (l); exit. setOnClickListener (ll); Exitactivity. getInstance (). addActivity (this);} OnClickListener l = new OnClickListener () {public void o NClick (View v) {Intent intent = new Intent (MainActivity. this, TwoActivity. class); startActivity (intent) ;}}; OnClickListener ll = new OnClickListener () {@ Overridepublic void onClick (View v) {builddialog () ;}}; public void builddialog () {AlertDialog. builder ad = new Builder (MainActivity. this); ad. setTitle ("exit application"); ad. setMessage ("exit application? "); Ad. setPositiveButton ("OK", new DialogInterface. onClickListener () {public void onClick (DialogInterface dialog, int which) {Exitactivity. getInstance (). exit () ;}}); ad. setNegativeButton ("cancel", new DialogInterface. onClickListener () {public void onClick (DialogInterface diich, int which) {dialog. dismiss () ;}}); ad. create (). show ();}}
The other two activities are the same. You can refer to the above activity