Android Emulator でホスト上で稼働中の HTTP サーバーと通信する


Android Emulator からは、ホストを IP 10.0.2.2 で参照できます。
ホストで開発中の HTTP (API) サーバーを立ち上げて通信を試みたところセキュリティポリシーで阻まれてしまいました。

CLEARTEXT communication to 10.0.2.2 not permitted by network security policy

以下のようにして、デバッグビルドでのみ 10.0.2.2 との平文通信を許可できます。(サーバー開発が安定してきたら HTTPS で通信するようにしましょう)

平文通信許可手順

1. manifest ファイルに network security config への参照を追加

$MyProject/app/src/main/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <application android:networkSecurityConfig="@xml/network_security_config"
                    ... >

2. デバッグビルド用ネットワークセキュリティ設定を追加

$MyProject/app/src/debug/res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="false">10.0.2.2</domain>
    </domain-config>
</network-security-config>

3. リリースビルド用ネットワークセキュリティ設定を追加

$MyProject/app/src/release/res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config />

メモ

空の $MyProject/app/src/main/res/xml/network_security_config.xml を作成してデバッグビルド用の設定をマージしてほしかったのですが、ファイルが重複しているとエラーが出て叶いませんでした。

ビルドバリアントやソースセットの作成に関しては公式の Configure build variants | Android Developers が詳しく説明してくれています。

参考リンク