Android studio root emulator

Google Play и root права для Android Emulator

Хочу поделиться своим опытом набивания шишек добавления Google Play в эмулятор, входящий в состав Android SDK. Вы спросите: «Да что тут может быть сложного? Добавить нужные .apk и пользоваться с удовольствием, об этом уже писали на Хабре тут!«

А вот и нет, подводных камней оказалось достаточно много. О них я расскажу под катом. Кстати, попутно расскажу как получить root права для эмулятора.

Интересно? Добро пожаловать под кат.

UPD: Обновил устаревшие ссылки.

И так, для начала — чем моя инструкция отличается от написанной ранее? Тем, что при использовании Google Play вы не столкнётесь с такой картиной, когда в категориях видно три с половиной приложения. Например вот, в Top Free видно целых два (sic!) приложения.:

Инструкция написана для ОС Windows, но подойдёт и для других поддерживаемых SDK ОС, просто с маленькими изменениями.

Нам потребуется:
Andoid SDK со следующими установленными пакетами:

  • Android SDK Tools
  • Android SDK Platform-tools
  • SDK Platform для Android 2.3.3
  • Extras/Android Support
  • Extras/Google USB Driver

Обладателям процессоров от Intel с поддержкой виртуализации рекомендую, для начала, проследовать инструкции, недавно опубликованной тут, и создать эмулятор с андроидом 2.3.

Создайте папку с именем GooglePlay и откройте консоль в ней. Это легко сделать, кликнув правой кнопкой в папке, с зажатой клавишей Shift. К сожалению это работает только в Windows Vista и выше. Тем, кто пользуется XP, придётся писать пути для cd.

Теперь нужно скачать кое-какие файлы. Сохраняйте все загрузки в созданную папку.
Мы используем эмулятор 2.3, поэтому берём:

  • Google Apps для CyanogenMod 7
  • Утилиту mkfs.yaffs2: для ARM эмулятора
  • Или же mkfs.yaffs2 для x86 эмулятора
  • SuperUser.apk и su для ARM или x86.

После установки всех пакетов — добавьте android-sdk\tools и android-sdk\platform-tools в системный PATH для удобства работы.

Создайте эмулятор для Android 2.3 с помощью AVD Manager, задав размер SD карты в 200-250 мб.

Запустите эмулятор и когда он полностью загрузится — откройте командую строку и введите команду «adb devices«. Вы должны будете увидеть эмулятор в списке подключённых устройств:

Если его там нет — в эмуляторе заходим в настройки (Кнопка меню — Настройки — Приложения — Разработка). Поставьте галочку на пункте «Отладка по USB» и перезапустите эмулятор. Теперь он должен отображаться в списке.

Далее вас ждёт увлекательный не очень ввод кучи консольных команд и ожидание.

Нам понадобятся файлы GoogleServicesFramework.apk, MarketUpdater.apk и Vending.apk из скачанного архива с GoogleApps. Откройте его и скопируйте их в созданную ранее папку.

Теперь нам нужно сделать несколько хитрых хаков для того чтобы нам были доступны все приложения из Google Play, вне зависимости от их требований. Иначе — вас ожидает картина из нескольких одиноких приложений, как было показано выше. Стоит сделать ремарку — запустить неподдерживаемые приложения не получится, но эти хаки позволят скачать эти приложения на девайс и, после, вытащить apk из эмулятора, например.

Читайте также:  Color os это андроид

Это позволит нам видеть приложения, которые требуют архитектуру процессора ARM7 и поддержку версии версии 2.0.

Так же нам нужен архив с permissions, который можно взять здесь.
Перетащите папку permissions из архива в нашу папку GooglePlay.
Эти файлы нужны для приложений, которые требуют определённое оборудование для работы. Например камеру, или акселерометр.

Кстати, насчёт ввода кучи консольных команд я соврал. Хе-хе.
Вам нужно будет всего лишь создать два .bat файлика. Приступим-с.

Первый файл назовите permissions.bat и наполните его таким вот содержанием:

adb push permissions/android.hardware.camera.autofocus.xml /system/etc/permissions/
adb push permissions/android.hardware.camera.flash-autofocus.xml /system/etc/permissions/
adb push permissions/android.hardware.camera.front.xml /system/etc/permissions/
adb push permissions/android.hardware.camera.xml /system/etc/permissions/
adb push permissions/android.hardware.location.gps.xml /system/etc/permissions/
adb push permissions/android.hardware.location.xml /system/etc/permissions/
adb push permissions/android.hardware.sensor.accelerometer.xml /system/etc/permissions/
adb push permissions/android.hardware.sensor.compass.xml /system/etc/permissions/
adb push permissions/android.hardware.sensor.gyroscope.xml /system/etc/permissions/
adb push permissions/android.hardware.sensor.light.xml /system/etc/permissions/
adb push permissions/android.hardware.sensor.proximity.xml /system/etc/permissions/
adb push permissions/android.hardware.telephony.gsm.xml /system/etc/permissions/
adb push permissions/android.hardware.touchscreen.multitouch.jazzhand.xml /system/etc/permissions/
adb push permissions/android.hardware.touchscreen.multitouch.xml /system/etc/permissions/
adb push permissions/android.hardware.touchscreen.xml /system/etc/permissions/
adb push permissions/android.hardware.wifi.xml /system/etc/permissions/
adb push permissions/android.software.live_wallpaper.xml /system/etc/permissions/
adb push permissions/android.software.sip.voip.xml /system/etc/permissions/
adb push permissions/com.android.location.provider.xml /system/etc/permissions/
adb push permissions/features.xml /system/etc/permissions/
adb push permissions/handheld_core_hardware.xml /system/etc/permissions/
adb push permissions/platform.xml /system/etc/permissions/

После — создайте ещё один, с произвольным названием, например make.bat и таким содержанием:

adb remount
adb push build.prop /system/
adb push su /system/bin/
adb push Superuser.apk /system/app/
adb push Vending.apk /system/app/
adb push MarketUpdater.apk /system/app/
adb push GoogleServicesFramework.apk /system/app/
call permissions.bat
adb push mkfs.yaffs2 /data/misc/
adb shell rm /system/app/SdkSetup.apk
adb remount
adb shell chmod 4755 /system/bin/su
adb shell chmod 777 /data/misc/mkfs.yaffs2
adb shell ./data/misc/mkfs.yaffs2 /system /sdcard/system.img
adb pull /sdcard/system.img system.img

adb push su /system/bin/
adb push mkfs.yaffs2 /data/misc/
adb shell chmod 777 /data/misc/mkfs.yaffs2
adb shell ./data/misc/mkfs.yaffs2 /system /sdcard/system.img

adb push su.x86 /system/bin/su
adb push mkfs.yaffs2.x86 /data/misc/
adb shell chmod 777 /data/misc/mkfs.yaffs2.x86
adb shell ./data/misc/mkfs.yaffs2.x86 /system /sdcard/system.img

В итоге содержимое папки GooglePlay должно быть таким:

Теперь — запускайте файл make.bat и начинайте ждать. Имейте ввиду, что последние две команды из файла make.bat будут выполняться долго. Есть маленькая хитрость — что бы ускорить этот процесс нужно что-нибудь делать на эмуляторе. Например, серфить хабрахабр из эмулятора. Я не знаю как и почему, но когда эмулятор нагружен — это здорово ускоряет процесс создания и копирования system.img.

После того, как консоль отрапортует о выполнении своим закрытием, мы обнаружим в рабочей папке файлик system.img. Теперь закроем эмулятор. Не нужно сразу логиниться или устанавливать какие-то приложения — вы потеряете все изменения после перезапуска эмулятора.

Хватайте появившийся system.img и заменяйте им файлик из папки

Не забудьте сделать резервную копию оригинального system.img!
Обратите внимание, что папка android-10 эквивалента для андроида версии 2.3. Для других версий андроида число после android- равно API Level данной версии.

Теперь заходите в папку, в которой у вас находятся файлы эмулятора и удаляйте файлы «cache.img«, «userdata-qemu.img«, «snapshot.img«, «userdata.img«(если он там есть). По умолчанию для Win7 это

После этого запускайте эмулятор, открывайте Google Play, логиньтесь, принимайте условия соглашения и… перезапускайте эмулятор ещё раз, потому что, зачастую, приложения не хотят загружаться сразу после логина.

Читайте также:  Диспетчер файлов для андроид апк

И вот, после последней перезагрузки, вы наконец-то можете полноценно пользоваться эмулятором.

Надеюсь, моя статья поможет кому-нибудь сохранить время. Спасибо за то, что уделили время на её прочтение.

Источник

infosectrek

Rooting the Android Emulator – on Android Studio 2.3 (Android 4.4+)

Having struggled to easily find instructions on how to run apps as root on the Android Emulator, I’ve decided to document what worked for me. I’ve tested this on the emulator bundled in Android Studio 2.3 with an emulator running Android 4.4 (Kitkat)and 7.1.1 (Nougat).

NB : Basically, through ADB (the Android debug bridge) you can get root access to the filesystem (only). This means you can access privileged directories, change file/directory permissions, put apps and binaries in certain (many?) locations (not in the system partition, unless you make it writable), and run them via the command line interface. However, this does not mean that you will be able to run apps in the emulator directly as root.

Getting access to the filesystem as root is as easy as running:

or getting into the emulator and using su , i.e.:

Notice the # telling you that you are root. (The -e just means to direct the adb connection to the emulator)

Now this is NOT exactly what I wanted, I wanted more!!

Rooting the Emulator:

Tl;dr : The basic idea is to get the correct su (superuser) binary from the SuperSu project by Chainfire (Jorrit Jongma), put it in the right directory, change the permissions. Install the SuperSu app, turn off SELinux policies and set up a daemon. I won’t claim I understand the whole process (particularly the daemon part), but i’ll document below what worked for me.

I’ll assume we’re using a Windows machine as the host. (Running these on Ubuntu, or some other Linux /Unix flavour should not be too different).

Step 0: Installing the SuperSu app

Ideally this step could come first before everything else, or last, after everything else. If you install it now you, and try to run it, very likely it would indicate that the su binary was not installed. If you try to run it after all the steps below, it should open error free and (without the dialog telling you that the binary is not installed).

Install the Supersu app either from Google Play or sideload it through adb . The links are available at the SuperSu downloads section.

Install the Supersu.apk file through sideloading as follows:

Step 1 : Start up the emulator with a writable system partition.

Step 2 : Get the SU binary and put it in the right directory

You can download the Superuser binary from the supersu downloads section. Download the latest ZIP files. (As of writing this is Recovery Flashablev2.79). Unzip the archive. Locate the su binary for the correct architecture of the emulator that you are using. In my case i’m running an emulator with Android x86 (on a Windows device), so i look under the x86 directory of the SuperSu ZIP archive. NB : If you are using Android 5.1 and above (or if you are getting some errors about Position Independent Executables [PIE]), what you need is the su.pie binary, rather than the plain su binary.

Читайте также:  Skachat telegram dlya android besplatno

We now need to put the binary into the correct location as follows:

Make sure you are running adb as root using. Not sure why you need to remount, but for some reason it enables writing to the system partition, (after having used the -writable-system directive).

Remember that if you are using an Android emulator with a version lower than Android 5.1 you likely will have to use the plain su binary (not the su.pie )

Not sure why, but some resources suggest that you need to push the binary to /system/bin/ for some Android versions. For good measure you can just do it, just incase.

Now we need to get into the emulator device through adb and change the permissions of the su binary.

For good measure, if you also put the binary in /system/bin/su you can also traverse into that directory and put the permissions of 06755 on the su binary there in. (I can’t remember exactly whether i used 06755 , or just 755 as the permissions, but I seem to vaguely remember the former as what I used). Also i noticed that originally the permissions on the su binary in the emulator had rwsr_x_x permissions if i remember correct.

Step 3 : Set the install directive on the su binary and set a daemon

I’m not entirely sure what is going on in this step, but it looks like the su binary may have a —install directive to install some more things (maybe??). I just followed [1] (from Android StackExchange).

Now we set up the daemon, (also taken from the same StackExchange post)

Notice the ampersand (&) at the end of the line with no space before. This indicates that the daemon (service) should run in the background.

Step 4 : Set SELinux to Permissive (i.e. turn off SELinux)

This step essentially turns off SELinux. Logically this step sounds like it should have come earlier, but for some reason it came at the end and still worked.

In my situation, at this point the emulator seems to have hung/crashed. I just terminated it.

Now you can restart the emulator via the command line, or via Android Studio. It should start up successfully. If you had installed the SuperSu app then you can just run the app and it might prompt you that there is a new version of the binary. Install it via the “Normal” option (if prompted).

At this point everything should be working well, and you can test some other app that requires root permissions to verify that the su binary is installed correctly and that the SuperSu (Gatekeeper) app fires correctly to “Grant” or “Deny” access to the requesting app.

Источник

Оцените статью