简体   繁体   中英

Open application from a second Activity

I have an application that has a main Activity where you have several options to choose from, which entered different Activities. What I want to do is that once an option is selected, if I close and open again the application is started from second Activity (from the screen of the selected option).

This is my main activity but doesn't work:

public class InicioActivity extends Activity {

Button b1;
Button b2;
SharedPreferences sharedPreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.inicio);
    b1=(Button)findViewById(R.id.b1);
    b2=(Button)findViewById(R.id.b2);
    ElegirIdioma();

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (sharedPreferences.getBoolean("startFromSecondActivity", false))
    {
        Intent intent = new Intent(this, EspanolActivity.class);
        startActivity(intent);
        finish();
    }
}

private void ElegirIdioma() {

    b1.setOnClickListener(new OnClickListener() {
        @Override
            public void onClick(View v) {   
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("startFromSecondActivity", true);
            editor.commit();

            Intent aEspanol = new Intent(InicioActivity.this, EspanolActivity.class);
            startActivity(aEspanol);
            Toast.makeText(v.getContext(), "Bienvenido" , Toast.LENGTH_SHORT).show();
        }
    });

    /*b2.setOnClickListener(new OnClickListener() {
        @Override
            public void onClick(View v) {   
                    Intent aEnglish= new Intent(InicioActivity.this, EnglishMainActivity.class);
            startActivity(aEnglish);
            Toast.makeText(v.getContext(), "Bienvenido" , Toast.LENGTH_SHORT).show();
        }
    });*/

} }

you can save that option in SharedPreference and in your MainActivity 's onCreate method change for saved value and then you can finish() your MainActivity and start SecondActivity

put this in your onCreate method:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        if (sharedPreferences.getBoolean("startFromSecondActivity", false))
        {
            Intent intent = new Intent(this, SecondActivity.class);
            startActivity(intent);
            finish();
        }

and put this in your Button 's onClick method :

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("startFromSecondActivity", true);
    editor.commit();

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