执行createChooser(context,intent,IntentSender)后,BroadcastReceiver未被调用。

8

我希望能够在 createChooser() 对话框弹出后检测用户选择的 app。因此,我创建了一个如下所示的 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清单文件中:

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

尽管我直接使用ShareBroadcastReceiver类名而没有使用任何intent-filter,这仍然是一个明确的PendingIntent,但当用户点击选择器对话框后,我的广播接收器并没有被回调,我做错了什么?
1个回答

5

您的代码完全没有问题。您只需要在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}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接