简体   繁体   中英

Pressing the back button goes back to first launched activity

I have an activity which starts when my app is first launched(Only once).The activity lets the users select the topics.Then when they press done, I finish() the activity.This leads the user to the MainActivity.But when the user press the back button it goes back to the activity which was first launched(the activity which I closed using finish()).But what i want is that the app should close when the user presses the back button from the MainActivity(always).I overrided onBackPressed in both the classes.

My onBackPressed method in both the classes looks like this:

@Override
    public void onBackPressed() {
        finish();
    }

MainActivity(Relevant part of code):

public class MainActivity extends AppCompatActivity  
 {

TopicAdapter adapter;
    private AdView mAdView ;

//-------GLOBAL VARIABLES-------------------

    AdRequest adRequest;
    ArrayList<Sections> gameList = new ArrayList<>();
    String json;
//-------------------------------------------

    @Override
    protected void onCreate(Bundle savedInstanceState)
       {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences sharedPreferences = 
        getSharedPreferences("ShaPreferences", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        boolean  firstTime=sharedPreferences.getBoolean("first", true);

//Launch the topics selection activity for the first time
        if(firstTime) 
         {
            editor.putBoolean("first",false);
            editor.commit();
            Intent intent = new Intent(MainActivity.this, channels_activity.class);
            intent.putExtra("isFirst",true);
            startActivity(intent);
          }
          }

  @Override
    public void onBackPressed() 
    {
        finish();
    }
}

You just need to call finish()

Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();

And Set android:noHistory="true" on the activity in your manifest See here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM