Search code examples
androidandroid-widgetandroid-pendingintent

Pending intents for multiple intents opening wrong activities


I have two widgets A and B. I have two issues:

  1. On tapping a widget (A or B) multiple times, multiple instances of the same activity opens up.
  2. Sometimes Widget A opens widget Bs activity and vice versa.

Here is my code:

Widget A Provider class:

 for (int appWidgetId : appWidgetIds) {
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.favorite_flavor_widget);
        Intent intent = new Intent(context, SplashActivity.class);
        intent.setAction("FromFavoriteFlavorWidget");
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        intent.putExtra("FromFavoriteFlavorWidget", true);
        PendingIntent pendingIntent = PendingIntent.getActivity(context,
                0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.favoriteFlavorBox, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
    }

Widget B Provider class:

 for (int appWidgetId : appWidgetIds) {
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                    R.layout.report_food_widget);
            Intent intent = new Intent(context, SplashActivity.class);
            intent.setAction("FromReportFoodWidget");
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("FromReportFoodWidget", true);
            PendingIntent pendingIntent = PendingIntent.getActivity(context,
                    0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.reportFoodBox, pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }

Solution

  • settings flags as Intent.FLAG_ACTIVITY_CLEAR_TOP Intent.FLAG_ACTIVITY_REORDER_TO_FRONT

    and try adding this to manifest.

    android:launchMode="singleTask"
    

    and

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(intent );
    

    http://inthecheesefactory.com/blog/understand-android-activity-launchmode/en