如何将选择器中的 Intent 用作 PendingIntent

How to use the Intent from chooser as a PendingIntent

我想使用 CustomTabs 库,我需要在其中添加一个 share 菜单项。该库只接受 PendingIntent 实例用作菜单项的 Action。我想使用以下代码来确保在没有 Just OnceAlways 按钮的情况下始终向用户建议列表:

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

但现在的问题是,如果我使用此选择器 Intent 创建一个 PendingIntent,Chrome 的 CustomTabs 不会为用户启动选择器:

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

有没有办法将 Chooser 的 Intent 用作 PendingIntent?

我不能使用以下行来启动 Intent,因为图书馆是这样做的,它只接受 PendingIntents:

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

您可以使用广播接收器来实现。

首先创建一个自定义的广播接收器class来创建选择器来分享

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);
    }
}

}

然后在自定义选项卡构建器中设置菜单项 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);