前提
開発環境: Mac OS, Vagrant
スマホ向けサイトを、Android Studioのエミュレーター上で確認したいが、エミュレーターと開発PCのhostsファイルが共有されていないので、ネームサーバーが機能しない。エミュレーター内のhostsファイルを直接書き換える必要がある。
また、開発環境はVagrantで作られており、Vagrantfileの設定は以下。
config.vm.network "private_network", ip: "192.168.11.22"
config.vm.hostname = "hogehoge.local"
手順
① Android Studioでエミュレーターをつくる
API Level: 28
Target: Android9.0 (Google APIs)
API Levelが新しいとhostsの書き換えができなかったり、
TargetがAndroid9.0 (Google Play)だと$adb root
が使えなかったりするので注意。
② エミュレーターの名前を確認
$ emulator -list-avds
Pixel_2_API_28
③ 書き込み可能モードでエミュレーターを起動
起動はGUIでなくターミナルから行う。
$ emulator -avd Pixel_2_API_28 -writable-system
ターミネルが占有されるので別タブを開く。
⑤ hostsファイルの書き換え
hostsファイルは、エミュレーター内の /system/etc/hosts
にあるので、これを書き換える。
※最初にrootになって、remountするのが必須。
$ adb root
$ adb remount
$ adb shell "echo 192.168.11.22 hogehoge.local >> /system/etc/hosts"
⑥ 確認
catでhostsファイルの中を確認
$ adb shell cat /system/etc/hosts
127.0.0.1 localhost
::1 ip6-localhost
192.168.11.22 hogehoge.local
これで、エミュレーター内のChromeから、http://hogehoge.local
にアクセスして、ローカルのサイトが表示されれば成功。
上記⑤の違う方法
hostsファイルを一度取り出して、手元で編集してから、エミュレーターに戻す方法もある。
⑤-1' 起動中のエミュレーター名を確認
最初に確認した名前と違うので注意
$ adb devices
List of devices attached
emulator-5554 device
⑤-2' hostsファイルの取り出し
PCの~/Desktop/
に保存
$ adb -s emulator-5554 pull /system/etc/hosts ~/Desktop/
取り出したら、hostsファイルをPC上で編集。
⑤-3' 編集したhostsファイルを戻す
$ adb root
$ adb remount
$ adb -s emulator-5554 push ~/Desktop/hosts /system/etc/hosts
参考にしたサイト
[Android] Android Virtual Device の /etc/hosts を書き換えて、Vagrant Virtual Machine へ接続する