I have 3 activities: The main one, a secondary and a third not very important.
When my application is opened for the first time, the main activity that has category launcher is executed, and according to a shared preferences that contains a boolean called trueVez, then an if (firstVez) that inside calls the unimportant activity and put the first of the sharedprefences to false so that it never runs again if.
The unimportant activity is a layout that simply asks for your name and it also contains a button that after having written your name sends you to the secondary activity.
Now everything would work fine, but if someone happened to hit the back button when it was in the unimportant activity, the main activity would be loaded. And of course the person did not write me the name or anything, to avoid this I overwrote the onBackPressed () method of the unimportant activity and put moveTaskToBack (true) so that it leaves the application and leaves it in the background.
My intention is that when I reopen the application the unimportant activity is executed so that it asks for the name.
That will not happen because the main application will be executed and as if now it is false because the unimportant activity will not be executed again.
Any ideas to achieve my purpose in an ideal and simple way?
EDIT
I have solved the problem with your second solution by editing the sharedPreferences in the unimportant class, the code has stayed like this:
I declare a Boolean variable called firstTime out of all the methods in the main class
Code onCreate () main class:
SharedPreferences sharedPreferences = getSharedPreferences("ShaPreferences", MODE_PRIVATE);
firstTime = sharedPreferences.getBoolean("first", true);
Toast.makeText(this, "Estoy en onCrete()", Toast.LENGTH_SHORT).show();
Code onResume () main class:
SharedPreferences sharedPreferences = getSharedPreferences("ShaPreferences", MODE_PRIVATE);
firstTime = sharedPreferences.getBoolean("first", true);
if(firstTime) {
Intent intent = new Intent(Lista.this, Bienvenida.class);
Toast.makeText(this, "Estoy en onResume()", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
Code of the method that is executed when pressing button to access in the unimportant class that will take me to the secondary class:
public void acceder() {
if(comprobar().length() > 0) {
Intent i = getIntent();
i.putExtra("nombre", comprobar());
i.putExtra("inscrito", "si");
SharedPreferences sharedPreferences = getSharedPreferences("ShaPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("first",false);
editor.commit();
Intent intent = new Intent(Bienvenida.this, MainActivity.class);
startActivity(intent);
} else {
Toast toast = Toast.makeText(this, R.string.comprobar, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}
}
Code method onBackPressed () of the unimportant class:
public void onBackPressed() {
moveTaskToBack(true);
}