Получить объект IntentSender для метода createChooser в Android
Я хотел бы использовать новую версию метода Intent.createChooser, который использует IntentSender
.
В документации указано только, что я могу захватить ее из экземпляра PendingIntent
. В моем случае кажется, что PendingIntent
не будет использовать другое.
Есть ли другой способ получить IntentSender
или мне нужно создать PendingIntent
?
Ответы
Ответ 1
цель целевого выбора не является PendingIntent
. Например, в следующем фрагменте я объявляю намерение для ACTION_SEND
, с типом text/plain
, и это мое целевое намерение для Intent.createChooser
. Затем я создаю еще один Intent
, приемник и обработчик PendingIntet
, который будет вызывать onReceive
моего BroadcastTest
после того, как вы выберите что-то из выбора.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
intent.setType("text/plain");
Intent receiver = new Intent(this, BroadcastTest.class);
receiver.putExtra("test", "test");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
Intent chooser = Intent.createChooser(intent, "test", pendingIntent.getIntentSender());
startActivity(chooser);
Изменить:
Информация, в случае BroadcastReceiver
, встроена в намерение, которое вы получаете как параметр. После того, как вы выбрали один из вариантов, извлеките дополнительные компоненты и используя клавишу android.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
Ответ 2
Другой способ сделать это.
/**
* Receiver to record the chosen component when sharing an Intent.
*/
static class TargetChosenReceiver extends BroadcastReceiver {
private static final String EXTRA_RECEIVER_TOKEN = "receiver_token";
private static final Object LOCK = new Object();
private static String sTargetChosenReceiveAction;
private static TargetChosenReceiver sLastRegisteredReceiver;
static boolean isSupported() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
static void sendChooserIntent(Activity activity, Intent sharingIntent) {
synchronized (LOCK) {
if (sTargetChosenReceiveAction == null) {
sTargetChosenReceiveAction = activity.getPackageName() + "/"
+ TargetChosenReceiver.class.getName() + "_ACTION";
}
Context context = activity.getApplicationContext();
if (sLastRegisteredReceiver != null) {
context.unregisterReceiver(sLastRegisteredReceiver);
}
sLastRegisteredReceiver = new TargetChosenReceiver();
context.registerReceiver(
sLastRegisteredReceiver, new IntentFilter(sTargetChosenReceiveAction));
}
Intent intent = new Intent(sTargetChosenReceiveAction);
intent.setPackage(activity.getPackageName());
intent.putExtra(EXTRA_RECEIVER_TOKEN, sLastRegisteredReceiver.hashCode());
final PendingIntent callback = PendingIntent.getBroadcast(activity, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
Intent chooserIntent = Intent.createChooser(sharingIntent,
activity.getString(R.string.share_link_chooser_title),
callback.getIntentSender());
activity.startActivity(chooserIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
synchronized (LOCK) {
if (sLastRegisteredReceiver != this) return;
context.getApplicationContext().unregisterReceiver(sLastRegisteredReceiver);
sLastRegisteredReceiver = null;
}
if (!intent.hasExtra(EXTRA_RECEIVER_TOKEN)
|| intent.getIntExtra(EXTRA_RECEIVER_TOKEN, 0) != this.hashCode()) {
return;
}
ComponentName target = intent.getParcelableExtra(Intent.EXTRA_CHOSEN_COMPONENT);
if (target != null) {
setLastShareComponentName(context, target);
}
}
}