Android xml source code

Как устроен билд APK файла внутри

Процесс создания APK и компиляции кода

Рассматриваемые темы

  • Архитектура процессоров и необходимость для виртуальной машины
  • Понимание Java виртуальной машины
  • Компиляция исходного кода
  • Виртуальная машина Андроид
  • Процесс компиляции в .dex файл
  • ART против Dalvik
  • Описание каждой части билд процесса
  • Исходный код
  • Файлы ресурсов
  • AIDL файлы
  • Модули библиотек
  • AAR библиотеки
  • JAR библиотеки
  • Android Asset Packaging Tool
  • resources.arsc
  • D8 и R8
  • Dex и Multidex
  • Подписывание APK файла
  • Ссылки

Понимание флоу процесса билда APK файла, среда исполнения и компиляция кода
Этот пост нацелен быть отправной точкой для разработчиков, чтобы они ближе познакомились с билд процессом и созданием APK файла.

Архитектура процессоров и зачем нужна виртуальная машина

Андроид после того как вышел в 2007 году претерпел множество изменений связанный с билд процессом, средой исполнения и улучшениями производительности.

У андроида много удивительных характеристик и одна из них разные архитектуры процессоров такие как ARM64 и x86

Невозможно скомпилировать код, который поддерживает каждую архитектуру. Вот именно поэтому используется Java виртуальная машина.

Понимание Java виртуальной машины

JVM это виртуальная машина, позволяющая устройству запускать код, который скомпилирован в Java байткод

Используя JVM, вы избавляетесь от проблемы с разной архитектурой процессоров.

JVM предоставляет переносимость и она позволяет запускать Java код в виртуальной среде, вместо того, чтобы запускать его сразу «на железе»

Но JVM была создана для систем с большими мощностями по ресурсам, а наш андроид имеет сравнительно мало памяти и заряда батареи.

По этой причине Google создал адаптированную под андроид виртуальную машину, которая называется Dalvik.

Компилируем исходный код

Наш исходный Java код для андроида компилируется в класс файл .class с байткодом с помощью javac компилятора и запускается на JVM

Для котлина есть kotlinc компилятор, который делает совместимый с Java байткод.

Байткод — это набор инструкций, который выполняется на целевом устройстве.

Java байткод — это набор инструкций для Java виртуальной машины.

Андроид виртуальная машина

Каждое андроид приложение работает на своей виртуальной машине. С версий 1.0 до 4.4, это был Dalvik. В андроид 4.4, вместе с Dalvik, Google представил в качестве эксперимента новый андроид runtime, который назывался ART

Сгенерированный класс файл .class содержит JVM Java байткод.

Но у андроида есть свой собственный оптимизированный формат байткода, который называется Dalvik bytecode — это просто инструкции машинного кода для процессора также как и JVM байткод.

Комплияция в .dex файл

Во время компиляции происходит конвертация .class класс файл и .jar библиотеки в один classes.dex файл, который содержит Dalvik байткод.

Команда dx превращает все .class и .jar файлы в один classes.dex файл, который написан с форматом Dalvik байткода.

Dex — это аббревиатура с английского — Dalvik Executable.

ART против Dalvik

C версии 4.4 андроид мигрировал на ART. ART также работает с .dex файлом.

Преимущество ART над Dalvik проявляется в том, что приложения запускаются быстрее, потому что весь DEX байткод транслируется в машинный код во время установки, не нужно дополнительного времени на компиляцию в рантайме.

ART и Dalvik совместимы, так что приложения разработанные для Dalvik должны работать и на ART.

Компиляция Dalvik (JIT- just in time) имела такие минусы как — быстрая трата батареи, лаги в приложениях и плохой перформанс. В Dalvik трансляция происходит только когда это нужно. Мы открываем новый экран и только в этот момент происходит трансляция, за счет этого установка происходит быстрее, но при этом проседает перформанс.

Это причина по которой Google сделал Android Runtime (ART).

ART — основан на AOT (ahead of time) компиляции, она происходит до того как приложение запустится.

В ART компиляция происходит во время установки приложения. Это ведет к более долгому времени установки, но уменьшает трату батареи и избавляет от лагов, которые были на Dalvik.

Несмотря на то, что Dalvik был заменен на ART, .dex формат файлов еще используется

В андроид 7.0 JIT вернулся. Гибридная среда сочетает фичи как от JIT компиляции так и
от ART

Среда запуска байткода это очень важная часть андроида и она вовлечена в процесс запуска и установки приложения

Каждый этап описанного процесса

Source Code (Исходный код)

Это Java и Kotlin файлы в src пакете.

Resource Files

Файлы находящиеся в директории с ресурсами

AIDL Files

AIDL — аббревиатура Android Interface Definition Language, позволяет вам описать интерфейс межпроцессорного взаимодействия.

AIDL — может использоваться между любыми процессами в андроиде.

Library Modules

Модули библиотек содержат Java или Kotlin классы, компоненты андроида и ресурсы.

Код и ресурсы бибилотеки компилируются и пакуются вместе с приложением.

Поэтому модуль библиотеки может считаться компайл тайм артефактом.

AAR Libraries

Андроид библиотеки компилируются в AAR — android archive файл, который вы можете использовать как зависимость для вашего android app модуля.

AAR файлы могут содержать андроид ресурсы и файл манифеста, что позволяет вам упаковать туда общие ресурсы такие как layouts и drawables в дополнение к Java или Kotlin классам и методам.

JAR Libraries

JAR это Java библиотека и в отличие от AAR она не может содержать андроид ресурсы и манифесты.

Android Asset Packaging Tool

AAPT2 — аббревиатура (Android Asset Packaging Tool) — компилирует манифест и файлы ресурсов в один APK.

Читайте также:  Miui android 12 откат

Этот процесс разделен на два шага компиляцию и линковку Это улучшает производительность так как если вы поменяете один файл, вам нужно компилировать только его и прилинковать к остальным файлам командой ‘link’

AAPT2 может компилировать все типы андроид ресурсов, таких как drawables и XML файлы.

При вызове AAPT2 для компиляции, туда передается по одному ресурсному файлу на каждый вызов

Затем APPT2 парсит файл и генерирует промежуточный бинарный файл с расширением .flat

Фаза линковки склеивает все промежуточные файлы сгенерированные в фазе компиляции и дает нам на выход один .apk файл. Вы также можете сгенерировать R.java файл и правила для proguard в это же время.

resources.arsc

Полученный на выходе .apk файл не включает в себя DEX файл, APK не подписан и не может быть запущен на устройстве.

APK содержит AndroidManifest, бинарные XML файлы и resources.arsc

resource.arsc содержит всю мета информацию о ресурсах, такую как индексы всех ресурсов в пакете

Это бинарный файл и APK который может быть запущен. APK который вы обычно создаете и запускаете не сжат и может быть использован просто посредством размещения в памяти.

R.java файл это выходной файл вместе с APK ему назначен уникальный id, который позволяет Java коду использовать ресурсы во время компиляции.

arsc это индекс ресурса который используется во время запуска приложения

D8 и R8

Начиная с андроид студии 3.1 и далее, D8 был сделан дефолтным компилятором.

D8 производит более маленькие dex файлы с лучшей производительностью, если сравнивать со старым dx.

R8 используется для компиляции кода. R8 это оптимизированная версия D8

D8 играет роль конвертера класс файлов в Dex файлы, а также производит дешугаринг функций из Java 8 в байткод, который может быть запущен на андроиде

R8 оптимизирует dex байткод. Он предоставляет такие фичи как оптимизация, обфускация, удаление ненужных классов.

Обфускация уменьшает размер вашего приложения укорачивая названия классов, методов и полей.

Обфускация имеет и другие преимущества для предотвращения реверс инжиниринга, но основная цель уменьшить размер.

Оптимизация уменьшает размер Dex файла путем переписывания ненужных частей кода и инлайнинга.

С помощью дешугаринга мы можем использовать удобные фичи языка Java 8 на андроиде.

Dex and Multidex

R8 дает на выходе один DEX файл, который называется classes.dex

Если количество методов приложения переваливает за 65,536, включая подключенные библиотеки, то произойдет ошибка при билде

Источник

Android xml source code

AX2J — Android XML to Java code

A tool converting your Android XML resource to native Java code.

2020/3/10 This repo is deprecated. See X2C for better solution.

2017/11/26 Update supported attributes from documents of Android Developers. Supported attribute list: http://ax2j.sickworm.com/attribute-list.html

2017/11/16 Website building finished. http://ax2j.sickworm.com/

2017/7/24 Web version online! Only content translate available. http://ax2j.sickworm.com/

2017/6/20 Now GUI support project translate function.

2017/6/17 Add GUI, add content translate function.

2015/3/27 Fix lots of bugs due to refactor, remove trailing spaces.

2015/3/12 Refactor finished.

2015/2/9 Support android:textAppearance. style supporting is still improving. many attributes of system styles cannot support.

2015/1/29 Support style.

2015/1/26 Support parts of shape in drawable.

2015/1/22: Support drawable selector, drawable picture.java not generated yet.

2015/1/21: Support drawable picture, fix some value error.

2015/1/20: Support margin, gravity, padding, inputType, fix some error.

2015/1/19: Improve behavior, support RelativeLayout rule, weight, color, and AXMLResources.getLayout() feature.

2015/1/16: Add R.java, AXMLResources feature(only getString() works).

2015/1/15: Support margins, . Generated Java files will show in a good order.

2015/1/14: Support some basic attributes of layout XML. Like id, layout_width, layout_height, enabled.

About

AX2J — A tool that transfers Android XML to Java code(XML block or whole project)

Источник

Extract source code (Java and XML) from Android APK File

Not getting any idea how to make good layout in Android activity or not getting how any application doing that things which you want in your project but you don’t know how to implement it in your APK File. So, I came here with new technology & new thinking which can make you crazy in android world.

Now time for backtracking…start your time to do hacking. Do you know you can get source code of Android APK file? Time to break the code..Let’s learn step by step.

In this tutorial we will learn how to convert android APK file into source code. Android .apk file is a compressed form of a file which contains Java classes (in .dex form), XML files and all necessary files. So first we will learn how to get Java source File from android apk using dex2jar and Java decompiler tools and then we will learn how to get XML source file using apktool and apkinstall tools.

To get the source code from APK file, we will need these tools:

Get Java files from APK:-

1. Rename the .apk file into .zip file (example SharedPr.apk into SharedPr.zip).
2. Extract SharedPr.zip file and copy classes.dex file from extracted folder.
3. Extract dex2jar.zip and paste classes.dex into dex2jar folder.
3. Open command prompt and change directory to the dex2jar folder. Then write dex2jar classes.dex and press enter. Now you will get classes.dex.dex2jar file in the same folder.

Convert classes.dex to classes.dex.dex2jar
classes.dex.dex2jar will be in dex2jar folder
Save All Java Files

Get XML files from APK:-

1. Extract apktool and apkinstall in a folder(Example : New Folder).
2. Put SharedPr.apk(your apk file) in same folder(i.e New Folder).

Keep Android Apk File with apktool and apkinstall

3. Open the command prompt and go to the root directory(i.e New Folder).
4. Type command on command prompt: apktool d SharedPr.apk

Читайте также:  Sim меню для андроид
Get All XML Files In Resource Folder

5. This will generate a folder of name SharePr in current directory (here New Folder) and all XML files will be in res->layout folder.

See All XML Files in new created Folder

Now you have source code. If you have any doubts please comment. Share and help others.

Note:- I disabled comment option on this post because I was getting lots of comment on this post. I updated download links & if anybody facing any problem than contact me directly.

For more related to Android tutorials see List of Android Tutorials.

154 comments:

very good nice sharing.

java decompiler link show this error
Erreur 403 — Refus de traitement de la requête (Interdit — Forbidden)

May be file moved..but I updated and used your given URL and Thanks dear.

I am only getting a smali folder and no XML files at all. I am following every step perfectly.

even I got smali folder
what I did after that is, I have Downloaded the latest version of apktool. https://bitbucket.org/iBotPeaches/apktool/downloads/apktool_2.0.1.jar
extract it rename it «apktool» and then it should work

i tried on this one is this correct.
http://jd.benow.ca/

yeah this is correct. Thanks for sharing.

Thanks I used this URL also.

i tried i didnt get any res folder etc..

Try again I updated post with images. This will help you.

how accurate is the java code with this tool??

it gave me 100% result.

m getting an error everytime i try to apktool !! [even though i run with admin rights]

_________________________________________________________
apktool d prov.apk
Exception in thread «main» brut.androlib.AndrolibException: brut.directory.DirectoryException: java.util.zip.ZipException: error in opening zip file
at brut.androlib.ApkDecoder.hasSources(ApkDecoder.java:199)
at brut.androlib.ApkDecoder.decode(ApkDecoder.java:83)
at brut.apktool.Main.cmdDecode(Main.java:146)
at brut.apktool.Main.main(Main.java:77)
Caused by: brut.directory.DirectoryException: java.util.zip.ZipException: error in opening zip file
at brut.directory.ZipRODirectory.(ZipRODirectory.java:55)
at brut.directory.ZipRODirectory.(ZipRODirectory.java:38)
at brut.androlib.res.util.ExtFile.getDirectory(ExtFile.java:55)
at brut.androlib.ApkDecoder.hasSources(ApkDecoder.java:197)
. 3 more
Caused by: java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.(ZipFile.java:127)
at java.util.zip.ZipFile.(ZipFile.java:144)
at brut.directory.ZipRODirectory.(ZipRODirectory.java:53)
. 6 more

Read and apply this method again and with different apk file. If you failed than send me your apk file.

Where i can send apk file ?

Bro.. First always try yourself to learn and now this tutorial is also available on Video. So you can easily learn.

i tried alot, i am stuck at > 3. Open command prompt and change directory to the dex2jar folder. Then write dex2jar classes.dex and press enter. Now you will get classes.dex.dex2jar file in the same folder.

did you seen video?? and are you not getting classes.dex.dex2jar??

I am getting the same error and no XML files.

type d2j-dex2jar classses.dex in command prompt

Hello
Do not bother
I had this problem and I was very much looking solution
Loved this problem is solved with the following code

java -jar apktool.jar d -f -r apkfilename.apk

This comment has been removed by the author.

This comment has been removed by a blog administrator.

i am sucessfully decompiled but m not open in eclips so please hell me

If you got resource file(all XML files and images) and all Java files than create new android project and use them.

I used the video and it all worked. Now, I’ve got loads of files here, to include a folder with java and a folder with XML. How do I build all of this into an editor to start playing around with it? I have dreamweaver (trial) but I’m open to lean another editor.

if you dont mind if i ask if you do you have the decode file of flow free game? thanks

Mohsin bhai. one critical question.
Is it possible to make an android app that can’t be decompiled? It will be needed sometimes in case of security application.

You can provide security on some code but how? i don’t know this also. I tried to get code of WatsApp Application and failed to get complete code but i got all resources files and partially all Java files(some parts gave error on decompile)

I ecxtracted the apk file but i dont know, how to understand the coding in GUI. Can u able to help me?

If you are beginner in android than don’t try decoding..try to learn code and than learn decoding. If not than share your code we will help you.

«apktool d myfile.apk»

message frm cmd: ‘apk tool is not recognsed internal or external command, operable program or batch file’

correct your path folder or watch video of this post.

i finally managed to decomile app app but i ddnt know how to arrange the arts so that i can run it into eclipse please help..

you have to make new android project and paste all Java files and XML files manually.

Hey Bro. Is it possible to get the source code of an app in playstore using this method?? Plz reply its for my College project.

You have to keep APK file for this method(download from website). You cant get apk from Google Play Store.

Oh. k. could u plz get me the code for an android anti theft app. I tried bt can’t get the apk file.

You can get apk file of any google play application by using any «apk extractor»

Use «Helper Plus» app to get apk.

I done all the steps and i imported in eclipde but it showed error in R.java what can i do

I have got XML files and java source code in two different folders. How can I combine them, so as to Import them into Eclipse for tesing purpose??

Читайте также:  Nfs no limits android секреты хитрости прохождения

Sir Help me to I am Not able to get full source code of this app https://play.google.com/store/apps/details?id=com.tenforwardconsulting.simplefit

Please Help me to provide it

I am A B.Tech sudent and My project is simple fitness app 🙂
if you have a app with source code please send it to me

Check where you are getting problem please tell.

my command propmt always
java is not recognized. error .

Set Java Path first than do.

it has worked on my PC perfectly thanks anyway

do you know how to import all files true without errors into eclipse?

you need to make a new project and all extracted codes are only for knowing logic not complete code because all integer and string changed into hexa-decimal value at compile time.

Sir please can you teach me how to do it step by step? bcz I really need it and I have only a bit knowledge in Android development.
if possible can you send to my email how to change or add into source:
iris.org.baron@gmail.com
thanks and really
appreciate beforehand

If you have little bit knowledge of android than it is better to learn from basic and create project yourself because source code will not help you to make your project.

I just opened an xml document on dreamweaver and a lot of it is scrambled. must be hexadecimal value stuff you mentioned interrupting it. Yeah, I’ll have to build it from scratch.

BaRoN, I just googled a little and found this: http://developer.android.com/training/basics/firstapp/index.html

Everything works good extracting the source code from the APK. Great Tutorial. However the source code extracted is not running in development environment. Can you make a tutorial on how to run it Eclipse once extracted. This would be Perfect

I can’t remember which one of these tutorials covered Eclipse. One of these will cover it in detail:

I’ll be starting off with android’s tutorial first. Editing a packaged app is not the same as getting html source code and files and editing it on an html editor. This is complicated stuff but the tutorials look really good.

Hello . When i convert .apk into .zip . after unzipping there is no .apk file show in extracted folder . Help

This comment has been removed by the author.

hey khizar you have to keep original apk file with you.

hi Khizar. yaar m also getting this same problem..please help me.

Extracted file only for understanding the application . We cant convert exact the code .

hi its great. now i have got aal source code and xml code. bt when i m import this code in adt(android development tool) it dont show the sjava code..source code folder not opened their. what can i do..please help me its urgent.

congrats. you have to create new project to use extracted code. Extracted code is only for help to know logic not complete code.

is it possible to import these files into eclipse workspace

i try to get code for «AndroidUSBSerialMonitorLite» this apps.. i got the java code and xml files. using these files i try to create a new new project.. its showing an error like «Android Library Projects Cannot Be Launched» 🙁
what can i do. can you give me some ideas?? i hope these apps contains some library files and we have to add. how to add these library files.

If APK file have library files than you have to download from net.

it works bro but how to arrange them?
cause i m not android developer and i didnt know android.
i use different method and i get 4 folders (assets, res, smali, src), 1 XML file (AndroidManifest).
now what can i do.

i have to run this apps in android eclipse ide

This comment has been removed by the author.

This comment has been removed by the author.

Hey
I have problem while compile problem.
I see lib and apktool.yml is missing.
Please help me.

Super Tutorial..
Thank you.

i can’t extract xml files .. it shows unable to acess jarfile
i tried dwnload from other source but still shows same result
please help me

This comment has been removed by a blog administrator.

Please How can I get the video?

This comment has been removed by the author.

Please Dear I’m developing an android RSS Reader application but I don’t know where to start. please can you be of help to me?

hi
i want to change in my apk file these thing..
1. about
2. in share opition
3. and i could not set score in my apk file..

how i change these three things in my apk file.

Hie sir,
when i’m converting the apk file to get the xml files im getting an error
:
C:\Users\Nikki\Desktop\xml files>apktool d com.pandutechnology.phoneadd
pk
I: Baksmaling.
I: Loading resource table.
Exception in thread «main» brut.androlib.AndrolibException: Multiple re
spec=0x7f050000 dimen/title_height, config=-v13
at brut.androlib.res.data.ResConfig.addResource(ResConfig.java:
at brut.androlib.res.data.ResConfig.addResource(ResConfig.java:
at brut.androlib.res.decoder.ARSCDecoder.readEntry(ARSCDecoder.

at brut.androlib.res.decoder.ARSCDecoder.readConfig(ARSCDecoder
)
at brut.androlib.res.decoder.ARSCDecoder.readType(ARSCDecoder.j
at brut.androlib.res.decoder.ARSCDecoder.readPackage(ARSCDecode
5)
at brut.androlib.res.decoder.ARSCDecoder.readTable(ARSCDecoder.
at brut.androlib.res.decoder.ARSCDecoder.decode(ARSCDecoder.jav
at brut.androlib.res.AndrolibResources.getResPackagesFromApk(An
ources.java:315)
at brut.androlib.res.AndrolibResources.loadMainPkg(AndrolibReso
a:50)
at brut.androlib.res.AndrolibResources.getResTable(AndrolibReso
a:43)
at brut.androlib.Androlib.getResTable(Androlib.java:44)
at brut.androlib.ApkDecoder.getResTable(ApkDecoder.java:148)
at brut.androlib.ApkDecoder.decode(ApkDecoder.java:98)
at brut.apktool.Main.cmdDecode(Main.java:120)
at brut.apktool.Main.main(Main.java:57)

It seems there’s some problem in building the resources while recompiling the apk. what you can do is, when you decompile your apk use this command

apktool d -f -r apkfilename.apk
here -f is to replace previous decompiled apk’s code and -r is to ignore the decompiling of resources.

this would prevent the resources from being decompiled and will simply copy the same resources when you recompile the ap

Источник

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