我已经从我的师兄那里解决了我的问题。我刚刚在我的旧共享代码上添加了一行 intent.setPackage(packageId)。然后它起作用了。完整的流程如下。
第 1 步。
在 AndroidManifest.xml 的应用程序块中添加这些行。
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
第 2 步。
在 res/xml 文件夹中创建一个 file_path.xml 文件(如果 xml 文件夹不可用,则创建它)。在 file_path.xml 文件中过去这段代码。
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="my_images" path="/" />
<!--For Share-->
<external-path name="external_files" path="." />
<cache-path name="cache_files" path="/"/>
</paths>
第 3 步。
创建一个 ShareUtils.kt 对象文件并通过此代码。
package com.example.riz1.utils
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import com.liilab.photo_editor.BuildConfig
import java.io.File
object ShareUtils {
interface FileUriCreator { val uri: Uri }
fun shareImage(context: Context, imagePath: String, packageId: String){
if (packageId!=AppConstants.DEFAULT_PACKAGE_ID && context.packageManager.getLaunchIntentForPackage(packageId) == null) {
context.customToast("Please first install the app")
context.startActivity(Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=$packageId")
))
}else{
val fileUriCreator = object : FileUriCreator {
override val uri: Uri get() = FileProvider.getUriForFile(context,
BuildConfig.APPLICATION_ID + ".fileprovider", File(imagePath))
}
try {
val intent = Intent(Intent.ACTION_SEND)
if (packageId!=AppConstants.DEFAULT_PACKAGE_ID) intent.setPackage(packageId)
intent.type = "image/jpeg"
intent.putExtra(Intent.EXTRA_STREAM, fileUriCreator.uri)
context.startActivity(Intent.createChooser(intent, "Share Image"))
} catch (ex: Exception) {
context.customToast("Please first install the app")
context.startActivity(Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=$packageId")
))
}
}
}
}
现在只需调用 ShareUtils.shareimage(context,ImagePath, packageId)。如果您想打开默认共享列表,只需删除 intent.setPackage(packageId) 并且 packageId 可以为空。