从共享意图选择器中获取选定的应用程序名称?

时间:2018-07-06 09:07:05

标签: android broadcastreceiver share android-pendingintent

在我的应用中,我具有共享选项以共享数据。我想获取用户选择共享内容的应用程序名称。 从API 21开始,借助Intent Sender可以实现

下面是我的共享代码

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "My shared text");
sendIntent.setType("text/plain");
Intent receiver = new Intent(this, AppChooserReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
Intent chooser = Intent.createChooser(sendIntent, null, pendingIntent.getIntentSender());
startActivity(chooser);

我创建了一个接收器,并在清单中声明了它。下面是接收方代码

public class AppChooserReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    for (String key : Objects.requireNonNull(intent.getExtras()).keySet()) {
        try {
            ComponentName componentInfo = (ComponentName) intent.getExtras().get(key);
            PackageManager packageManager = context.getPackageManager();
            assert componentInfo != null;
            String appName = (String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(componentInfo.getPackageName(), PackageManager.GET_META_DATA));
            Log.i("Selected Application Name", appName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
}

我在onreceive中得到了意图,但是键集始终为null。有什么我想念的吗?

1 个答案:

答案 0 :(得分:0)

感谢源代码,我尝试并添加了

<receiver android:name="AppChooserReceiver" android:exported="false"/> 

在AndroidManifest中。然后我得到了应用名称