1 回答

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
從 API 26 開(kāi)始,“REQUEST_INSTALL_PACKAGES”權(quán)限是實(shí)現(xiàn)安裝 apk 文件的必要權(quán)限。
在 res/xml 文件夾中創(chuàng)建“file_paths.xml”以使用 FileProvider api
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="" path="/" />
</paths>
在 AndroidManifest.xml 中聲明 FileProvider 和權(quán)限
筆記。我使用的是 Androidx 版本的 FileProvider,如果你不使用 androidx,請(qǐng)確保 android.support.v4.content.FileProvider
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="{PACKAGE_NAME}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
通過(guò) FileProvider api 獲取“Uri”并請(qǐng)求安裝權(quán)限
private fun openFile(file: File) {
val uri = if (Build.VERSION.SDK_INT >= 24) {
val authority = packageName + ".fileprovider"
FileProvider.getUriForFile(this, authority, file)
} else {
Uri.fromFile(file)
}
val myMime = MimeTypeMap.getSingleton()
val mimeType = myMime.getMimeTypeFromExtension(file.extension)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, mimeType)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
if (Build.VERSION.SDK_INT >= 26 && !packageManager.canRequestPackageInstalls()) {
startActivity(
Intent(
Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
Uri.parse("package:$packageName")
)
)
} else {
intent.action = Intent.ACTION_VIEW
startActivity(intent)
}
}
編輯 -> 刪除在我的項(xiàng)目中使用的特定方法。
添加回答
舉報(bào)