There is a need. We click to exit the application in the menu item, and the application exits without returning to MainActivity.
Design:
There are two application interfaces: MainActivity and BActivity, and the general class ExitUtil for the program.
Steps:
1. Add a class named ExitUtil
Copy codeThe Code is as follows: public class ExitUtil {
Public static final int exit_applications = 0x0001;
Private Context mContext;
Public ExitUtil (Context context ){
MContext = context;
}
// Exit the application completely
Public void exit (){
Intent intent = new Intent (mContext, MainActivity. class );
// Set FLAG !!! Jump from the current Activity to the class added in the intent constructor, and finish the Activity between the two activities!
Intent. setFlags (Intent. FLAG_ACTIVITY_CLEAR_TOP );
// Issue exit application instructions
Intent. putExtra ("flag", EXIT_APPLICATION );
MContext. startActivity (intent );
}
}
2. Add a BActivity and overwrite it as follows. You must configure this Activity in the configuration file.
Copy codeThe Code is as follows: public class BActivity extends Activity {
Private static final int MENU_EXITAPPLICATION = Menu. FIRST;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
TextView TV = new TextView (this );
TV. setText ("wecolme! ");
SetContentView (TV );
}
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
Menu. add (0, MENU_EXITAPPLICATION, 0, "Exit program ");
Return super. onCreateOptionsMenu (menu );
}
@ Override
Public boolean onOptionsItemSelected (MenuItem item ){
// Other Activity callers use this method
If (item. getItemId () = MENU_EXITAPPLICATION ){
ExitUtil eu = new ExitUtil (this );
Eu. exit ();
}
Return super. onOptionsItemSelected (item );
}
}
3. Modify the MainActivity Method
Copy codeThe Code is as follows: public class MainActivity extends Activity {
Button btn = null;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
Btn = (Button) findViewById (R. id. btn );
Btn. setOnClickListener (new OnClickListener () {// click to enter the BActivity
@ Override
Public void onClick (View v ){
Intent intent = new Intent (getApplicationContext (), BActivity. class );
StartActivity (intent );
}
});
}
// Receive the command to exit the program
@ Override
Protected void onStart (){
Int flag = getIntent (). getIntExtra ("flag", 0); // for the first time, the default flag value is 0!
If (flag = ExitUtil. EXIT_APPLICATION ){
Finish ();
}
Log. I ("TAG", "Start ");
Super. onStart ();
}
// When the Activity is in singleton mode, the onCreate-> onStart methods will not be called when the Activity is started twice.
@ Override
Protected void onNewIntent (Intent intent ){
Int flag = getIntent (). getIntExtra ("flag", 0 );
If (flag = ExitUtil. EXIT_APPLICATION ){
Finish ();
}
Log. I ("TAG", "NewIntent ");
Super. onNewIntent (intent );
}
}