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

3

In my application I have a BroadCast that receives push notifications in background , this push currently opens an activity with the information of a request to be accepted, what happens is that if the same instant is reading one request receive another the app opens on top in 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();
    }
 }

}
    
asked by anonymous 28.08.2016 / 22:24

1 answer

3

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

In the AndroidManifest.xml file, in the Activity statement, place:

android:launchMode="singleTop"

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

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 onNewIntent() method.

    
28.08.2016 / 22:54