我想通过chrome自定义选项卡加载本地html文件,这是可行的吗?

Wan*_*avx 11 chrome-custom-tabs

目前我把我的html文件放在资源中,然后在WebView中加载它.我可以通过Chrome自定义标签加载吗?

小智 6

其实是有办法的。在 AndroidManifest.xml 中

    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>
Run Code Online (Sandbox Code Playgroud)

定义提供者路径

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
    name="external_files"
    path="." />
</paths>
Run Code Online (Sandbox Code Playgroud)

然后只需将您的本地文件提取到外部目录

val file = File(activity.externalCacheDir, "hello.html")
        val bytes = resources.openRawResource(R.raw.hello).use { it.readBytes() }
        FileOutputStream(file).use { it.write(bytes) }
        val uri = FileProvider.getUriForFile(activity, "${activity.packageName}.provider", file)
        CustomTabsIntent.Builder()
            .build()
            .also { it.intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) }
            .launchUrl(activity, uri)
Run Code Online (Sandbox Code Playgroud)


小智 5

否,无法在customtabs中打开file:// URL。

  • 这是使用Nano httpd的本地服务器实现。这将提供资产文件夹中的文件,我们可以使用它在自定义镶边选项卡中呈现脱机页面。https://bitbucket.org/snippets/pkumarad/qAk6x (3认同)