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/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:networkSecurityConfig="@xml/network_security_config"
... >
$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>
$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 が詳しく説明してくれています。
参考リンク
Author And Source
この問題について(Android Emulator でホスト上で稼働中の HTTP サーバーと通信する), 我々は、より多くの情報をここで見つけました https://qiita.com/ryohji/items/f41c37edf6f800a1c53f著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .