How to prevent a new instance of Activity from being created every Intent

Asked

Viewed 628 times

4

In my application I have a BroadCastwho receives push notifications in background, that pushcurrently opens an Activity with the information of a request to be accepted, what happens is that if at the same time you are reading a request receive another the app opens on top of a new Intent.

public class BroadcastReceiverOneSignal extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Bundle extras = intent.getBundleExtra("data");
    try {
        JSONObject customJSON = new JSONObject(extras.getString("custom"));
        if(customJSON.has("a")){

            String id = customJSON.getJSONObject("a").getString(Constants.ID_CORRIDA);

            Intent i = new Intent(context, Activty.class);
            i.putExtra(Constants.ID, id);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }catch (Exception e){
        e.printStackTrace();
    }
 }

}

1 answer

3


This set of flags only does what you want if the launchMode of Activity for singleTop.

In the archive Androidmanifest.xml, in that statement Activity, place:

android:launchMode="singleTop"

To Activity will only be created if it is not running, if it is running Intent in the method onNewIntent().

The same result can be obtained with:

i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

In both cases the new Intent and its Extra can be obtained in the method onNewIntent().

  • I can keep all data from other orders if I receive a new one?

  • 1

    Yes, the new will be received in the method onNewIntent()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.