【问题标题】:BroadcastReceiver is not called after createChooser(context,intent,IntentSender) is executed执行 createChooser(context,intent,IntentSender) 后不调用 BroadcastReceiver
【发布时间】:2017-01-17 06:43:00
【问题描述】:

我想在我向用户展示 createChooser() 对话框后检测用户选择了什么应用程序。所以我创建了我的BroadcastReceiver 子类,如下所示:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ShareBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("INFORMATION", "Received intent after selection: "+intent.getExtras().toString());
    }
}

我还把我的接收器添加到我的 android ma​​nifest 文件中:

<application>
...
...
...
    <receiver android:name=".helpers.ShareBroadcastReceiver" android:exported="true"/>
</application>

下面是调用 createChooser 对话框的代码:

Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.setType("image/png");

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
    Log.d("INFORMATION", "The current android version allow us to know what app is chosen by the user.");

    Intent receiverIntent = new Intent(this,ShareBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, receiverIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    sendIntent = Intent.createChooser(sendIntent,"Share via...", pendingIntent.getIntentSender());
}
startActivity(sendIntent);

尽管这是一个显式的PendingIntent,因为我直接使用ShareBroadcastReceiver 类名而没有任何intent-filter,但我的广播接收器在用户单击选择器对话框后没有被回调,我在做什么错了吗?

【问题讨论】:

    标签: android android-pendingintent android-broadcastreceiver android-intent-chooser


    【解决方案1】:

    您的代码一切正常。您只需在 ShareBroadcastReceiver 中更改 onReceive 方法中的一行,即可捕获 Intent 的“EXTRA_CHOSEN_COMPONENT”键:

    Log.d("INFORMATION", "Received intent after selection: "+intent.getExtras().get(Intent.EXTRA_CHOSEN_COMPONENT));

    在您的日志中,您会看到类似这样的内容(在我的例子中,我选择了 Google Keep):

    ComponentInfo{com.google.android.keep/com.google.android.keep.activities.ShareReceiverActivity}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多