firebase 在没有设置android的情况下为android:usesCleartextTraffic=“真”的情况下为Android提供Flutter?

zzoitvuj  于 2022-11-17  发布在  Android
关注(0)|答案(1)|浏览(185)

I have had some issues getting requests from the Android emulator to interact with FireBase. I ended up setting:

android:usesCleartextTraffic="true"

in the manifest file.
A quick search tells me that this allows insecure connections:

Android 6.0 introduced the `useCleartextTraffic` attribute under the application element in the android manifest. The default value in Android P is “false”. Setting this to true indicates that the app intends to use clear network traffic

What do I have to do in order to deploy my application without setting android:usesCleartextTraffic="true" ?

z0qdvdin

z0qdvdin1#

Option 1

In the res/xml/ folder create a network_config.xml file that contains the following:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

I believe that 10.0.0.2 is the ip address that the emulator uses on the Android device. If I am wrong, you can update the ip address to whatever might be the correct address.
Then in the AndroidManifest.xml file in the application tag add android:networkSecurityConfig="@xml/network_config" . The output would look like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_config"
        ...>
        ...
    </application>
</manifest>

This should allow any traffic coming from an emulator be allowed in clear text, but block other endpoints from being accessed over http/cleartext.

Option 2

You could hypothetically configure a setup with gradle to release a different manifest for debug and release builds. I just looked at the android folder for flutter and what you could do instead is go to the ${PROJECT_FOLDER}/android/app/src/debug/AndroidManifest.xml and add the following:

<application
  android:usesCleartextTraffic="true">
</application>

Your output AndroidManifest.xml in the debug folder (which should only be applied to debug builds, may look something similar to this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package">
    <!-- The INTERNET permission is required for development. Specifically,
         the Flutter tool needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <!-- ADD FROM HERE-->
    <application
        android:usesCleartextTraffic="true">
    </application>
    <!-- TO HERE-->
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

Note

I haven't tested option 2 myself, but from my understanding, this should work. This medium article may help.

相关问题