Search code examples
javaandroid-studioandroid-layoutadmob

Close MainActivity(main) from another activity (ActivityPoliticas)


I'm looking for a solution to press the (non-personalized ads) button of the ActivityPolicies and close the MainActivity and then reopen the MainActivity with the correct ad.

MainActivity(principal)

public void politicas(View view) // button
{
    Intent i = new Intent (this, ActivityPolicies.class);
    i.putExtra("valor","politicas");
    startActivity(i);   

}

ActivityPolicies

public void NonPersonalizedAdvertising(View view) //button
{
    SharedPreferences myPreferences = PreferenceManager.getDefaultSharedPreferences(MensajePoliticas.this);
    SharedPreferences.Editor myEditor =myPreferences.edit();
    myEditor.putString("POLITICAS","LEIDO_NOACEPTADO");
    myEditor.commit();

//Missing some option to close the main activity

*
*
*
 //Reopen the main activity

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


    finish();  // Close the current activity (ActivityPolicies)
}

The goal is to close the MainActivity to reload the correct personalized or non-personalized ad. I already have the code but I am missing this option to reload the MainActivity.

Another question: Close the main activity to reload the ads, can I have problems with some Admob rule?

Thank you very much


Solution

  • If your MainActivity is in backstack, you can call same activity like this:

    Intent entrar = new Intent(this,MainActivity.class);
    entrar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // this will open the same MainActivity instance and also give you a new intent.
    startActivity(entrar);
    

    Now in your MainActivity you can override onNewIntent

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    // here you will get the new Intent. You can reload only the ads programmatically or just call `this.recreate();`
    }