Android 如何将选择器的意图用作挂起内容

Android 如何将选择器的意图用作挂起内容,android,android-pendingintent,chrome-custom-tabs,share-intent,Android,Android Pendingintent,Chrome Custom Tabs,Share Intent,我想使用CustomTabs库,在这里我需要添加一个共享菜单项。库只接受PendingEvent实例用作菜单项的操作。我想使用以下代码确保始终向用户建议列表,而不使用仅一次和始终按钮: Intent shareIntent = Intent.createChooser(intent, "Choose the application to share."); 但现在的问题是,如果我使用此选择器意图创建PendingEvent,则Chrome的CustomTabs不会为用户启动选择器: Pendi

我想使用CustomTabs库,在这里我需要添加一个共享菜单项。库只接受PendingEvent实例用作菜单项的操作。我想使用以下代码确保始终向用户建议列表,而不使用仅一次始终按钮:

Intent shareIntent = Intent.createChooser(intent, "Choose the application to share.");
但现在的问题是,如果我使用此选择器意图创建PendingEvent,则Chrome的CustomTabs不会为用户启动选择器:

PendingIntent pendingIntent = PendingIntent.getActivity(context,
            requestCode,
            shareIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
有没有办法将选择器的意图用作悬挂式帐篷

我不能用下面的行来开始这个意图,因为库就是这样做的,它只接受PendingEntities:

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

您可以通过使用广播接收器来实现这一点

首先创建一个自定义BroadcastReceiver类来创建要共享的选择器

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

然后在自定义选项卡生成器类中设置菜单项

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

请确保使用显式广播…隐式广播将无法正常工作。此外,您需要在AndroidManifest.xml中声明广播接收器,否则它将无法工作。@Markoninini您知道为什么需要将其添加到清单中吗?我们正在升级到Oreo并删除它,以便为我们的BroadcastReceiver做一个registerReceiver(使其明确),但PendingEvent从未到达接收器。在添加了清单行之后,它起了作用。@C Nick此刻,我想不起这种行为的确切原因,我可能和你或我在某个地方读到的有同样的经历。不管怎样,我很高兴听到我的评论对某人有所帮助。