Broadcast receiver startActivity with singleTop

I am listening to GPS activation or GPS deactivation with broadcast receiver by subscribing to android.location.PROVIDERS_CHANGED .

When the GPS is deactivated, I would like to print a popup. I use the following code for this:

public class GPSReceiver extends BroadcastReceiver {

public GPSReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
    final LocationManager manager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);

    boolean gps = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean network = manager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (!gps || !network) {

        Intent popup = new Intent(context,
                ModalActivity.class);
        popup.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(popup);
    }
}

      

My popup is printing ok. But I have 2 popups. In fact, when I cut out GPS, my OnReceive is called 2 times: for network and for GPS.

How can I only print one popup?

I am trying many solutions:

1) I am trying to start my activity with Intent.FLAG_ACTIVITY_SINGLE_TOP, but I have this error:

Calling the startActivity () function from outside the activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

2) I am trying to trigger my activity with NEW_TASK and SINGLE_TOP, but I have 2 popups:

popup.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

      

3) I am trying to add a public static boolean to see if my activity has been started, but my onReceive seems to be making a call at the same time. So my boolean was changed after the onReceive call.

Do you have any suggestions?

thank

+3


source to share


1 answer


The following setup worked for me.

Set the action as singleTask in the manifest:

android:launchMode="singleTask"

      



And then call it with these flags:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

      

0


source







All Articles