LoginSignup
14
9

More than 3 years have passed since last update.

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

Last updated at Posted at 2018-09-11

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 が詳しく説明してくれています。

参考リンク

14
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
9