【问题标题】:How to use the Intent from chooser as a PendingIntent如何将选择器中的 Intent 用作 PendingIntent
【发布时间】:2023-03-27 04:35:01
【问题描述】:

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

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

有没有办法将选择器的 Intent 用作 PendingIntent?

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

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

【问题讨论】:

    标签: android android-pendingintent chrome-custom-tabs share-intent


    【解决方案1】:

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

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

    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 中声明您的广播接收器,否则它将无法正常工作。
    • @Markonionini 你知道为什么需要将它添加到清单中吗?我们正在升级到 Oreo 并删除了它,以支持对 BroadcastReciever 进行 registerReceiver (使其明确),但 PendingIntent 从未到达接收器。在重新添加该清单行后,它起作用了。
    • @C Nick 目前,我无法回忆起这种行为的确切原因,我可能和你有同样的经历,或者我在某处读过它。无论如何,我很高兴听到我的评论对某人有所帮助。
    猜你喜欢
    • 2014-07-06
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    相关资源
    最近更新 更多