选择器目标意图不是PendingIntent。例如,在下面的 sn-p 中,我声明了 ACTION_SEND 的意图,类型为 text/plain,这是我对 Intent.createChooser 的目标意图。然后我创建另一个Intent、接收器和一个处理程序PendingIntent,在用户从选择器中选择某些内容后,它将调用我的BroadcastReceiver 的onReceive。
// Set up the broadcast receiver (preferably as a class member)
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Unregister self right away
context.unregisterReceiver(this);
// Component will hold the package info of the app the user chose
ComponentName component = intent.getParcelableExtra<ComponentName>(Intent.EXTRA_CHOSEN_COMPONENT);
// Do something with component
}
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
intent.setType("text/plain");
// Use custom action only for your app to receive the broadcast
final String shareAction = "com.yourdomain.share.SHARE_ACTION";
Intent receiver = new Intent(shareAction);
receiver.putExtra("test", "test");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
Intent chooser = Intent.createChooser(intent, "test", pendingIntent.getIntentSender());
// Before firing chooser activity, register the receiver with our custom action from above so that we receive the chosen app
context.registerReceiver(broadcastReceiver, new IntentFilter(SHARE_ACTION));
startActivity(chooser);
编辑:
在BroadcastReceiver 的情况下,信息嵌入在您作为参数获得的意图中。选择其中一个选项后,检索捆绑包的附加内容并使用密钥 Intent.EXTRA_CHOSEN_COMPONENT,您应该能够找到用户选择的内容。
尝试将简单的 Log.d 添加到onReceive
for (String key : intent.getExtras().keySet()) {
Log.d(getClass().getSimpleName(), " " + intent.getExtras().get(key));
}
在我的例子中,我得到了
ComponentInfo{org.telegram.messenger/org.telegram.ui.LaunchActivity}
对于Telegram 和
ComponentInfo{com.google.android.apps.inbox/com.google.android.apps.bigtop.activities.ComposeMessageActivity}
为InBox