3

当用户选择要在其上共享图像的应用程序时,我正在尝试处理IntentSenderofIntent.createChooser()做某事。我在这里找到的大多数示例(在下面发布)都需要使用BroadcastReceiver 如下

Intent receiver = new Intent(context, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
String type = "image/*";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType(type);
share.putExtra(Intent.EXTRA_STREAM, awesome_photo_uri);
startActivity(Intent.createChooser(share, "some_title", pendingIntent.getIntentSender()));

我对这个解决方案的问题,位于这一行:

Intent receiver = new Intent(context, MyReceiver.class);

这些示例中使用的Intent 构造函数需要我创建一个静态MyReceiver类,所以我有一个类可以传递给构造函数的第二个参数。但是,这会导致一个问题,因为我希望BroadcastReceiver'sonReceive在我的 Fragment 中做一些事情。因此,我更愿意BroadcastReceiver在我的 Fragment 中动态创建一个。

无济于事,我尝试了以下解决方法:

内部MyFragment.kt

private val receiver: BroadcastReceiver = getBroadcastReceiver()
private val intentFilter = IntentFilter("com.my.app.CHOOSER_ACTION")

override fun onResume() {
    requireContext().registerReceiver(receiver, intentFilter)
    super.onResume()
}

override fun onPause() {
    requireContext().unregisterReceiver(receiver)
    super.onPause()
}

private fun shareImage(imageFile: File) {
    Intent().apply {
        flags = Intent.FLAG_ACTIVITY_NEW_TASK
        action = Intent.ACTION_SEND
        type = "image/*"
        putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(
            requireContext(),
            "${myPackageName}.fileprovider",
            imageFile
        ))

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            val receiver = Intent("com.my.app.CHOOSER_ACTION")
            val pendingIntent = PendingIntent.getBroadcast(requireContext(), 0, receiver, PendingIntent.FLAG_CANCEL_CURRENT)
            startActivity(Intent.createChooser(this, "Share image using", pendingIntent.intentSender))
        } else {
            startActivity(Intent.createChooser(this, "Share image using"))
        }
    }
}

private fun getBroadcastReceiver() : BroadcastReceiver {
    return object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.extras?.keySet()?.forEach {
                Log.v("MyTest", "$it: ${intent.extras?.get(it)}")
            }
            doSomethingInMyFragment()
        }
    }
}

内部AndroidManifest.xml

<activity android:name="MyActivityThatHasMyFragment" />
    <intent-filter>
        <action android:name="com.my.app.CHOOSER_ACTION" />
    </intent-filter>
</activity>

不幸的是,在用户按下选择后,动态BroadcastReceiver函数onReceive()永远不会被调用。几个问题:

  1. 为什么这不起作用?我错过了什么?我是否以某种方式设置IntentIntentFilter不正确?
  2. 甚至可以使用动态BroadcastReceiver来处理IntentSenderofcreateChooser吗?如果没有,我怎样才能创建一个BroadcastReceiver触发某些事情发生的静态MyFragment

资源:

4

0 回答 0