androidandroid-pendingintentchrome-custom-tabsshare-intent

How to use the Intent from chooser as a PendingIntent


I want to use the CustomTabs library, where I need to add a share menu item. The library accepts only PendingIntent instance to be used as an Action for the menu item. I want to use the following code to make sure that the list is suggested to the user all the time without Just Once and Always buttons:

Intent shareIntent = Intent.createChooser(intent, "Choose the application to share.");

But the problem is now that if I use this chooser Intent to create a PendingIntent, the CustomTabs for Chrome doesn't fire up the Chooser for the user:

PendingIntent pendingIntent = PendingIntent.getActivity(context,
            requestCode,
            shareIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

Is there a way to use the Chooser's Intent as a PendingIntent?

I can't use the following line to start the Intent, because the library is the one who is doing that and it only accepts PendingIntents:

startActivity(Intent.createChooser(i, getString()));

Solution

  • You can achieve this by using broadcast receiever.

    first create a custom broadcastreciever class to create chooser to share

    ShareBroadcastReceiver.java

    public class ShareBroadcastReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
        String url = intent.getDataString();
        if (url != null) {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT,context.getResources().getString(R.string.chromeextra)+ url);
    
            Intent chooserIntent = Intent.createChooser(shareIntent, "Share url");
            chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
            context.startActivity(chooserIntent);
        }
    }
    

    }

    then set menu item in custom tabs builder class

      String shareLabel = getString(R.string.label_action_share);
    Bitmap icon = BitmapFactory.decodeResource(getResources(),
            android.R.drawable.ic_menu_share);
    
    //Create a PendingIntent to your BroadCastReceiver implementation
    Intent actionIntent = new Intent(
            this.getApplicationContext(), ShareBroadcastReceiver.class);
    PendingIntent pendingIntent = 
            PendingIntent.getBroadcast(getApplicationContext(), 0, actionIntent, 0);            
    
    //Set the pendingIntent as the action to be performed when the button is clicked.            
    intentBuilder.setActionButton(icon, shareLabel, pendingIntent);