Blended Android tidbits

This time I don’t have a full article about one specific topic but rather few useful tips. These are not really bound together, you don’t need to read from the top to the bottom but you can skip to what interests you most.

Permissions – Application lifecycle consideration

I don’t want to explain once again how the new (still?) permission system works on Android because the official documentation does a great job in this regard and there are plenty of blog posts and tutorials around.

I just want to put the focus on one aspect, remembering the users can grant or deny permissions while your application is running.

So I have created a project with Android Studio with just one empty Activity and I have declared a dangerous permission in the manifest, just to have it in the Settings screen of the application. Then I have overridden almost all the lifecycle methods for my Activity and the Application class (so I have implemented a custom one too).

Now the first test, granting a permission: start the application, put it in background, open to application Permissions setting screen, grant my permission and open again the application from the Recents view. This is the log:

com.fasteque.permissionsapplication.PermissionsApplication: attachBaseContext
com.fasteque.permissionsapplication.PermissionsApplication: onCreate
com.fasteque.permissionsapplication.MainActivity: onCreate
com.fasteque.permissionsapplication.MainActivity: onStart
com.fasteque.permissionsapplication.MainActivity: onResume
com.fasteque.permissionsapplication.MainActivity: onResumeFragments
com.fasteque.permissionsapplication.MainActivity: onPause
com.fasteque.permissionsapplication.MainActivity: onSaveInstanceState
com.fasteque.permissionsapplication.MainActivity: onStop
com.fasteque.permissionsapplication.MainActivity: onRestart
com.fasteque.permissionsapplication.MainActivity: onStart
com.fasteque.permissionsapplication.MainActivity: onResume
com.fasteque.permissionsapplication.MainActivity: onResumeFragments

Now the second test, revoking a permission: start the application, put it in background, open to the application Permissions setting screen, revoke my permission and open again the application from the Recents view. This is the log:

com.fasteque.permissionsapplication.PermissionsApplication: attachBaseContext
com.fasteque.permissionsapplication.PermissionsApplication: onCreate
com.fasteque.permissionsapplication.MainActivity: onCreate
com.fasteque.permissionsapplication.MainActivity: onStart
com.fasteque.permissionsapplication.MainActivity: onResume
com.fasteque.permissionsapplication.MainActivity: onResumeFragments
com.fasteque.permissionsapplication.MainActivity: onPause
com.fasteque.permissionsapplication.MainActivity: onSaveInstanceState
com.fasteque.permissionsapplication.MainActivity: onStop
com.fasteque.permissionsapplication.PermissionsApplication: attachBaseContext
com.fasteque.permissionsapplication.PermissionsApplication: onCreate
com.fasteque.permissionsapplication.MainActivity: onCreate
com.fasteque.permissionsapplication.MainActivity: onStart
com.fasteque.permissionsapplication.MainActivity: onRestoreInstanceState
com.fasteque.permissionsapplication.MainActivity: onResume
com.fasteque.permissionsapplication.MainActivity: onResumeFragments

As you can clearly see, if you grant a permission while your application is in background, but still alive, when you resume it, nothing special happens, you get the usual lifecycle, with the Activity started and resumed again.

But in the second case, when you revoke a permission, methods to create both the Application and the Activity are called.

This has been tested on a Samsung S7 (6.0.1) and a Nexus 6 (N Preview2 – NPC91K).

Permissions – Grant them all for testing

This is a quick tip useful when you manually install an application, because the standard adb installation command does not grant any of the requested dangerous permission by default. And this is completely fine, in the end that’s the same exact behaviour you get when installing an application from Google Play Store.

But let’s say you’re in the development phase, you have to delete and re-install your application several times and you don’t want all the time to deal with runtime permissions. So simply add a parameter, -g, to your command:

adb install -g YOUR_APPLICATION.apk
Files directory symbolic link

We all know that getFilesDir() returns the path of the directory holding application files. Starting from API Level 23 getFilesDir() returns /data/user/0 instead of /data/data/ like in the past.
But this is just a symbolic link to /data/data/, so the data of any application is still actually saved to /data/data/ as usual. I guess the reason for this change is related to Android for Work: in the past I’ve indeed noticed that the system, in order to manage two different profiles, personal and work, creates two “users”, 0 (personal) and 10 (work). In this way, Android can separate personal and work applications, so you can install the same application for both profiles, of course with data and notifications separation.

You don’t have to worry about it unless your application deals with canonical paths, because a canonical path is an absolute path with symbolic links and references to “.” or “..” resolved.

Shrinking debug builds

Starting from version 2.0.0-beta7/2.1.0-alpha3 (2016/3/19) of the Android Gradle plugin, there’s a new (experimental) built-in shrinker available, which can be used instead of ProGuard.

You can enable it in this way:

android {
    buildTypes {
        debug {
            minifyEnabled true
            useProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt')

Please note this removes dead code only, but it doesn’t optmize or obfuscate your code.

AppLaunchChecker – a first quick analysis

With the release of the Android Support Library revision 23.3.0, a new utility class has been introduced: AppLaunchChecker.

Its aim is very simple:

To help track how your app has been launched by the user in the past. This can be useful if you want to confirm that a user has launched your app through its front door activity from their launcher/home screen, rather than just if the app has been opened in the past in order to view a link, open a document or perform some other service for other apps on the device.

According to the change log, it is sufficient to call hasStartedFromLauncher() method to know if the user has launched the application from the home screen.

So, let’s try to to add the following code in typical Hello World application:

protected void onResume() {
    if (AppLaunchChecker.hasStartedFromLauncher(this)) {
        Toast.makeText(this, "Started from launcher", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "NOT started from launcher", Toast.LENGTH_SHORT).show();

Launching it from the home screen, we would expect to see “Started from launcher” displayed by a Toast, instead “NOT started from launcher” is shown.

Looking into AppLaunchChecker source code, we can notice two things: first, there’s another public static method available called onActivityCreate, second, the overall logic is simply based on SharedPreferences.

In fact, from the comment we know that:

To track this state properly you must call onActivityCreate(Activity) in your launcher activity’s onCreate(Bundle) method.

This method is responsible to set to true a boolean key named startedFromLauncher in a preference file called Of course if the key already exists and it is set to true or the Activity’s launching intent is null nothing is done.

So let’s give it a try:

protected void onCreate(Bundle savedInstanceState) {


Building again the application and launching it from the home screen, we now get the “Started from launcher” Toast.

Thus, this new utility class is nothing more than the typical “workaround” based on SharedPreferences already used by many developers: when the launcher Activity is created, a boolean shared preference is set to true, then later in the lifecycle of the application, calling hasStartedFromLauncher, we simply get its value.

Important: it’s not possible using Android Support Library public methods to set back the preference to false. In fact, reading carefully the documentation, the key parts are:

… your app has been launched by the user in the past.

… if this app has been started by the user from the launcher at least once.

That means this utility class is only useful to know if the application has been launched from the home screen at least once in the past but not every time it’s launched: in fact, after the fist time, you will get always true from hasStartedFromLauncher.

Request for simplifying padding and margins declarations

I’ve recently created a new feature request for the AOSP code related to padding and margin attributes used in layout declarations.

Quite often, while setting a padding or a margin, it’s done using the same value for left and right (or start and end) and for top and bottom: that’s the case for example for list row or main Activity/Fragment layouts.

Something like this (I didn’t use dimens intentionally):


If you have enabled RTL support and your app works with versions earlier than Android 4.2, it would be even worst:


Of course, you can and should declare styles, but still, it’s too much XML code to write.

It would be nice to have the option to quickly set these values without having to provide all of them. Something like:


This will set a 16dp padding on both sides of the view, horizontally, and a 8dp padding on both sides vertically. That would also apply for margins.

You can find it at the AOSP issue tracker here: if you think it could be helpful, please star it, otherwise stop by anyway to leave a comment, criticise or propose another solution. In the end, the ultimate goal is to simplify our life of Android developers.

Tips on updating to Retrofit 2

Retrofit 2.0.0 has been finally released and while the official documentation, articles or blog posts give you all the details about this new version, I’ve seen several questions on StackOverflow about how to update the code just to do the most common tasks like logging, adding request parameters or using JSON objects. So, in this blog post, I will give you a few tips about that.

This article is currently updated with Retrofit v2.0.0.

NEW Group id

The very first change you will notice is the new group idcom.squareup.retrofit2, so that’s the new dependency declaration:

compile 'com.squareup.retrofit2:retrofit:2.0.0'

NEW Package name

Main package name has also changed to:

package retrofit2;

It means you will have to change all the import related to Retrofit. Furthermore, if you perform any processing or manipulation tasks involving package names, remember to update them as well.


Due to the new package name, if you have Proguard enabled on your application, the first thing to do is to update the rules in the configuration file. They are available on the official site:

-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions


OkHttp is now a default dependency and Retrofit 2 builds on top of it. In fact, looking at the Retrofit 2 pom file, there’s the following dependency:


If you don’t need to use a specific version or another client, you don’t have to do anything in this regard.


The next thing you will immediately notice is that the code you have implemented to generate the service interface implementation doesn’t compile anymore.

What follows is the typical and minimal code you would implement on Retrofit:

RestAdapter restAdapter = new RestAdapter.Builder()

GitHubService service = restAdapter.create(GitHubService.class);

In Retrofit 2, this will change to:

Retrofit retrofit = new Retrofit.Builder()

GitHubService service = retrofit.create(GitHubService.class);

As you can see, the Builder pattern has been kept but classes and methods involved have changed.


Being able to log HTTP requests and responses is quite important during development, so if you have enabled this feature on your Retrofit instance, you will find that the method provided to do that is not available anymore.


That’s because now you must rely on the logging system provided by OkHttp, HttpLoggingInterceptor.

The first thing to do is to declare a new dependency, since it’s not part of the main OkHttp artifact:

compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'

Second, create an instance of the interceptor:

HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();

Then, add it to the OkHttp client instance:

OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();

And finally set the client while creating the service interface implementation:

Retrofit retrofit = new Retrofit.Builder()

movieDbApi = retrofit.create(MovieDbApi.class);


By default, Retrofit can only deserialize HTTP bodies into OkHttp’s ResponseBody type and it can only accept its RequestBodytype for @Body.

That means a converter must be set while creating the service interface implementation to support other types.

In order to enable Java serialization to convert Java Objects into JSON and back, a GSON converter must be set.

First, a new dependency is required:

compile 'com.squareup.retrofit2:converter-gson:2.0.0'

Then, a converter factory – GsonConverterFactory – must be set:

Retrofit retrofit = new Retrofit.Builder()

movieDbApi = retrofit.create(MovieDbApi.class);

The full list of available converters is available on the official documentation.


Another useful feature of Retrofit is the ability to intercept HTTP calls to monitor, rewrite or retry them for example.

One typical scenario is the requirement to append an API key to all the HTTP requests performed by your application. Prior to Retrofit 2, this could have been achieved declaring a RequestInterceptor:

final RequestInterceptor authorizationInterceptor = new RequestInterceptor() {
        public void intercept(RequestInterceptor.RequestFacade request) {
            request.addQueryParam(MovieDbApi.PARAM_API_KEY, "YOUR_API_KEY");

And the set it in the interface implementation generation:

RestAdapter restAdapter = new RestAdapter.Builder()

movieDbApi = restAdapter.create(MovieDbApi.class);

This is not valid anymore on Retrofit 2 because now you must rely on OkHttp interceptors.

You can directly set one inline while instantiating the OkHttp client:

OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.url().newBuilder().addQueryParameter(
MovieDbApi.PARAM_API_KEY, BuildConfig.MOVIE_DB_API_KEY).build();
        request = request.newBuilder().url(url).build();
        return chain.proceed(request);

And then set the client as already shown before:

Retrofit retrofit = new Retrofit.Builder()

movieDbApi = retrofit.create(MovieDbApi.class);

rxjava observable

If you’re using RxJava, you will notice that Retrofit 2 interfaces does not support Observable out of the box anymore: in fact, the Call pattern is used for standard HTTP requests.

Of course, you can use your own type, providing your CallAdapter implementation, but luckily for you there is one already available, RxJavaCallAdapterFactory. In short, it converts a Call to an Observable.

First, add its dependency:


Then, set it using the addCallAdapterFactory method:

Retrofit retrofit = new Retrofit.Builder()

movieDbApi = retrofit.create(MovieDbApi.class);


Deep dive into Android Multidex

The 65k reference limit of a DEX file is a problem that any developer might face sooner or later while working on an Android project and at some degree we had to deal with it at Sysmosoft as well.

In the community, it has been discussed many times how to deal with it so, in this article, after briefly explaining what we should do in such a situation, we’ll see how multidex actually works behind the scenes.

Quick recap

Any APK package has at least one DEX file and that’s where all the executable code of an application is stored. This includes not only our own implementation but also all the code of the libraries referenced, the dependencies declared in the build.gradle file (or the pom.xml file if we’re using Maven). So common libraries such as Android Support Libraries, Retrofit, ButterKnife, Guava, Jackson, Google Play Services, … if used by our application, will be taken into account while producing the DEX file.

The size of the DEX file’s method index is 16 bit, so it means that 65536 represents the total number of references that can be invoked by the code within a single DEX file. If building our application we surpass this limit, the dx tool throws an error, causing the failure of the APK packaging.

Error:Your app has more methods references than can fit in a single dex file.
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_60.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2

So, what should we do in this case? Actually we could think about it as a great occasion to review our code. In fact, before enabling the multidex support, two steps should be done.

First, review direct and transitive dependencies of our application: it is worth taking a bit of time and do this review, because we may find out we are including a very large library just to use a few of its methods. Anyway, don’t be surprised if everything is fine: if we did our job consciously while adding this dependency, we should have already picked the best option for our needs.

Also, if our application is a mature project, we could also realize that this large library is widely used in our code base: thus, a bit of time would be required to refactor our implementation, with the risk of introducing few regressions.

Anyway, one thing to double check very carefully are the transitive dependencies, because there’s the chance we could exclude few of them. A typical example is the Location API provided by Google: as of version 8.4.0, if we declare play-services-location as a dependency, we get also play-services-maps, but maybe we don’t need map support in our application

The second option we have is to shrink the code using Proguard: we could configure this tool to remove all the unused code, ensuring it’s not included in the final APK, reducing the number of referenced methods in our DEX file. We don’t need to optimize or obfuscate the code, simply to shrink it. The problems here could arise if we have never enabled Proguard at all in our project, because very likely we’ll face crashes at runtime due to missing classes removed by mistake. In this case, we need to add specific rules in the Proguard config file to explicitly tell the tool to keep those classes.

If neither of these two options is not enough for our project, so it doesn’t produce a DEX file with less than 65536 referenced methods, the way to go is to enable the multidex support.

methods count

At this point it should be clear that keeping an eye on the methods count is quite important, because dealing with code refactoring, Proguard or multidex support later in the life of an application could be tricky or anyway take away some time that could be spent implementing new features or improving the user experience.

There are many solutions to get this value, here I simply mention two of my favourites:

dex-methods-count (command-line tool)

dexcount-gradle-plugin (Gradle plugin, so it can be conveniently integrated in the application build process)

I’d like also to mention this online tool (they also provide a Gradle plugin): Methods count. That’s a good place to check a new dependency before integrating it in an application: the only limitation is that the library repository must be Maven Central, jCenter or JitPack.

Enabling Multidex

The official documentation about multidex is particularly well written so there’s no point in doing a mere copy & paste here.

One important thing to highlight though, is about the minimum SDK version supported by the application: in fact, if it runs on Android 5.0 and higher, the configuration would be quite simple, because multiple DEX files in an APK are natively loaded by ART. For lower versions of Android, the multidex support library must be used.

That’s s an important point because I’ve seen a lot of questions on StackOverflow about the java.lang.NoClassDefFoundError exception while running a multidex enabled application on Android versions prior to Lollipop.

Multidex support library

Let’s start enabling multidex using the support library, following the official instructions. Just two things to note: the version of the library used for this article is 1.0.1, while the application is the Empty Activity project created from Android Studio using the wizard.

Also, since there’s not much code implemented, to force the need to enable multidex, we should add a bunch of dependecies, like the following:

compile ''
compile ''
compile ''
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.facebook.fresco:fresco:0.8.1'
compile ''
compile ''
compile ''
compile ''
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'org.apache.commons:commons-lang3:3.4'
compile ''

Once the APK is produced, we can list its content using aapt to see that there are actually many DEX files in it.

DEX files
DEX files

You can also take advantage of one of the many tools available online to browse an APK and have a look at the methods inside each of the DEX file. One simple to install and use is ClassyShark: here is also available a quick introduction about inspecting multidex APK files.

The main aim of the library is to patch the application context class loader in order to load classes from more than one DEX file. The primary classes.dex must contain the classes necessary for calling this class methods, otherwise the application will crash. Secondary DEX files, named classes2.dex, classes3.dex, … found in the application APK will be added to the classloader after the first call to install(Context) of the MultiDex class.

The logic of interest is in the installSecondaryDexes method of the MultiDex class: first, secondary DEX files are retrieved and then dalvik.system.DexPathList pathList field is modified to append additional DEX file entries. In this way, the ClassLoader instance at Application level (retrieved using getClassLoader()) is also aware of the classes present in the additional DEX files.

Source code of the latest version of the multidex support library can be found here.

This operation is performed when the application is started: in fact, if the application already extends the Application class, the requirement of the multidex support library is to call the install method from attachBaseContext (overriding it if necessary).
In short, when the application is started and the Application instance is attached, the patched class loading system is run to load the additional DEX files present in the APK file.

Of course, this extra work, required at startup, has an impact on performances: that’s explained in details by this great article, which I suggest you to read.

Actually the support library is only one part of the whole multidex feature, because, as we have seen, it simply takes care of loading all the classes when we start our application and nothing much more. But at point, the APK already has multiple DEX files in it.

So who’s responsible for generating all the different DEX files?


The dx tool is the executable in charge of generating the DEX file (or more) to be included in the final APK package, which will be installed on the device.

Simply typing dx in a terminal gives us the help output for the command and three options are related to multidex:

--multi-dex: allows to generate several DEX files if needed.

--main-dex-list=<file><file> is a list of class file names, classes defined by those class files are put in classes.dex.

--minimal-main-dex: only classes selected by --main-dex-list are to be put in the main DEX.

The first one is obvious: it’s used when the build process has to support multidex, producing more than one DEX file. So, when we enable multidex, this options is passed to dx.

The second option is a path to a file where class file names are listed: these files will be put into the main DEX file. This is necessary because some classes cannot be stored in secondary DEX files, otherwise the application could crash when launched. If we use the multidex support library, a typical example of a file to be kept into the main DEX file, is the Application class (the one provided by the library or our own implementation). As we have seen, this file is responsible for loading the classes of the secondary DEX files, and it’s executed at application startup time, so it must be in the main DEX file.

A typical auto-generated file will list at least the following classes using the multidex support library:


The third option is again quite simple to understand: if set, only the classes listed in --main-dex-list will be put into the primary DEX file.

There’s also a fourth option, labelled as undocumented test option--set-max-idx-number.  It sets the maximum number of method references to be put into the main DEX file: that’s it, we can instruct dx to put at least a specific number of method references in any DEX file to be produced.

dx source code is open, so let’s start having a look at the main class for the class file translator, specifically at the runMultiDex() method. The first line of interest is:

readPathsFromFile(args.mainDexListFile, classesInMainDex);

That’s basically where the classesInMainDex HashSet is filled with the class files to be kept in the primary DEX file.

Then, the second method to look to have a better understanding is processAllFiles(), which is where, very unsurprisingly, all the DEX files are created and filled with all the specified classes. Here we can see how the tool tries to force the classes listed by --main-dex-list, to be part of the main DEX file: looking at the DexException that could be thrown, it’s clear that we don’t have to try to have too many classes as part of this list, otherwise we could face the same initial issue for which we have enabled the multidex support.

That’s all about multidex, it’s not worth diving into more specific details: it was just important to highlight what’s behind the scenes when we simply add multiDexEnabled in our gradle script.

MissingTranslation issue for release builds

Using the default Lint configuration, while building the release version of our application, we could face the MissingTranslation error:

Error:(3) Error: "pick_color_array" is not translated in "ru" (Russian) [MissingTranslation]
    <string-array name="pick_color_array">


1 errors, 0 warnings
Error:Execution failed for task ':android-rgb-tool:lintVitalRelease'.
> Lint found fatal errors while assembling a release target.

This happens when more than one locale is supported by an application but not all the string resources have been translated in all the languages.

Please notice that we don’t get this issue while building for debug (again, using the default Lint settings): in fact, checking the list of tasks executed for release builds, we can see there’s an additional lintVitalRelease run by Gradle. Checking its description, we understand that this task runs Lint on just the fatal issues in the Release build.

So, how to deal with it? Well, the first obvious thing to do is to provide a translation for all the strings for which is missing. But what if we don’t need or want to do that? In the end, we know the system will rely on the default language if a translation is not provided for a specific locale or in some cases there is no translation at all for our string resources.

Quick and dirty

The quickest thing to do is to turn off this check from the module gradle build script:

android {
    lintOptions {
        checkReleaseBuilds false

It works, indeed, but in this way we are turning off all the checks for a release build, not only the one related to a missing translation. Thus, this kind of “solution” should be avoided at all costs.

Quick and dirty, again

The second option we have is to configure the Lint options to not abort the build process if an error is found:

android {
    lintOptions {
        abortOnError false

In this case, checks are run but the build is performed even when errors are found. That’s slightly better than the previous solution but again it should be avoided: in the end, the APK is produced, so we should manually check the build logs or the Lint report to see if critical errors have been raised during the process.

Ignoring MissingTranslation issue only

Both previous solutions are not the proper ways to deal with missing translations because those settings are valid in general at application level and not for our specific problem.

If we want to ignore the issue only, maybe because we are fine to rely on the default language string resources, we can simply add the following attribute:


This attribute must be set for the specific string for which we’re fine to ignore the issue:

<string name="example" tools:ignore="MissingTranslation">Lorem ipsum dolor sit amet&#8230;</string>

Please notice that we are telling to ignore the issue: again, we must be really sure about what we’re doing, because if we’ll add later a new language, we won’t get any failure for those strings for which the missing translation error must be ignored.

Set strings as NON-translatable

Another option is to set the string as non-translatable: we simply have to add the following attribute for all the strings for which we don’t want to provide a translation in all the supported languages (we have to set this in the default string resource files, usually located in res/values/).

<string name="example" translatable="false">Lorem ipsum dolor sit amet&#8230;</string>

The final results is the same as the previous solution, but I think this is better, because instead of asking to ignore something, we’re explicitly telling that some resources are not translatable.

Define NON-translatable strings in a dedicated file

The last two ways to deal with the MissingTranslation issue work fine, but the problem arises if our application has a lot of strings that should not be translated: the extra attributes will become a bit noisy and we could forget to set it for newly defined strings.

In such a situation, the way to go is to define these strings in a dedicated file called donottranslate.xml: Lint will consider all these resources as not-translatable.

As we’ve seen, there are few ways to deal with missing translations, even if I would suggest the following pattern:

  1. if non-translatable strings are just few, set the translatable="false" for them.
  2. if non-translatable strings are a considerable % of the total, use the donottranslate.xml file.

Official documentation is available here.

Gradle bits for beginners

The following tips are meant especially for who is quite new to Android Studio and Android application development in general.

Gradle Version

Any project in Android Studio can set to use the Gradle Wrapper or the local Gradle distribution.

The latter is actually stored within Android Studio and it gets updated along with the IDE.

There are two important points to highlight:

  • if we want to update the Gradle version, we have to install it manually and then tell Android Studio where to find it.
  • if we update Android Studio, importing the preferences from the previous installation, and this new version updates the Gradle version, we will have a wrong Gradle home setting. This is not pointed out clearly, so it’s always a good idea to double check.
Gradle settings
Gradle settings

Gradle Wrapper

The Gradle Wrapper is meant to ease our life, since we don’t have to deal with manual installation: it is essentially a script and a property file, which will be included in any project and it will take care of our builds.

A property file, called, is generated the first time we create a new project, pointing to a specific version of Gradle. So, if we work for weeks if not months, very likely this version will become old or obsolete.


What we have to do is simply to update the name of the zip file with a newer version of Gradle: here we can check the latest available stable version and its link.

We cannot anyway pick any Gradle version as we’ll see later.

Gradle Plugin

The Android build system uses the Android Plugin for Gradle to support building Android applications with the Gradle build toolkit.

In other words, this plugin provides all the tasks required to build, test, and package Android applications and libraries.

The version being used is generally set in the main build.gradle file of any project.

classpath ''

So, if we want to update the plugin version to get new features, we just have to update this dependency: all the revisions are provided by the official documentation.

As anticipated earlier, not all the combinations of Gradle and the Android Plugin for Gradle can work together: it’s always a good idea to have a look at the version compatibility summary page.

Projects and tasks

Projects in Gradle are something that can be built, such a JAR library or an Android APK, but also something to be done, for example deploying an application to the production environment, which actually doesn’t build a “thing”.

Any project, is made of one or more tasks, defined in the build script: these are essentially a list of actions to be performed by the build process.

In the Android context, we can see the list of the available tasks for our project in two ways.

First, from Android Studio, clicking on the Gradle label on the right side:

Gradle tasks
Gradle tasks

Second, issuing the following command in the terminal, from the root folder of our project:

./gradlew tasks
Gradle tasks
Gradle tasks

As we can see, the Android Plugin already defines several tasks for us, so we don’t have to do anything to clean or build the project, to produce an APK or to run tests on the emulator or a device.

These tasks are executed each time we click on some buttons of the Studio, like the Run green arrow for example: we know that it will trigger a build, to produce an APK to be deployed on a running emulator instance or any attached device.

In fact, opening the Gradle Console view, we can see all the details of the build being executed (debug variant in the screenshot):

Run a debug build
Run a debug build

Dry run

If we need to check which steps are performed by any task, without actually executing them, we can launch it in dry run mode.

./gradlew TASK_NAME --dry-run

We can also activate this mode using -m.

dry run
dry run

Types, flavors, variants?

We often read or hear about build types, product flavors and build variants, but what exactly are they in the context of an Android project built with Gradle?

By default, the Android Plugin sets up the project to build two types of the application, debug and release. The debug type is the default one, so it’s not necessary to declare it in the build script: all its settings are already defined for us, in order to be able to develop and test our application.

The other types, like release, can be defined in the buildTypes block of the build script.


When we create a new build type, we don’t have to set all its properties any time, but we can initialize it with an existing type, using the initWith() method, with the possibility to override properties.


If using the build types, we define different builds of the same application, with flavors we define customized versions of the application to build.

Typical examples are paid and free flavors, or in the case of a white label application, flavors can represent all the different branding. Same code base, but different theme colors, logo, images and backend URL.

In the build script, flavors can be defined in this way:

productFlavors {
        flavor1 {

        flavor2 {

Build type or flavor? In general, the suggestion is to create a new flavor when the new APK will be uploaded to the Google Play Store or published externally.

Build Type + Product Flavor = Build Variant

That’s it, a variant is obtained simply combining a build type with a product flavor. Every time a type or a flavor is defined, a new variant will be generated. Not only, but the Android Plugin will also create tasks for all the variants defined in the build script, so we don’t have to do that manually.


In a project with a lot of dependencies or with different modules having few dependencies in common, or anyway if we want to have a clean solution, there’s a nice approach firstly proposed by Fernando Cejas in his Android – Clean Architecture sample app.

The main idea is to declare the version of all the dependencies in a separate Gradle file, which can be stored anywhere in the project hierarchy folder.

Let’s call it dependencies.gradle and place it in the root folder of our project.

ext {
    // Android
    androidBuildToolsVersion = "23.0.2"
    androidMinSdkVersion = 21
    androidTargetSdkVersion = 23
    androidCompileSdkVersion = 23

    // Libraries
    androidSupportLibraryVersion = '23.1.1'

    // Testing
    robolectricVersion = '3.0'
    jUnitVersion = '4.12'

    appDependencies = [

    appTestDependencies = [

Complete file can be found on GitHub here.

Then, in the main build.gradle of our project, we include the dependency script, so it will be visible from all the modules:

apply from: 'dependencies.gradle'

Then, in the build.gradle of our module, we use it to declare our dependencies:

dependencies {
    def dataDependencies = rootProject.ext.appDependencies
    def testDependencies = rootProject.ext.appTestDependencies

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile dataDependencies.appCompat
    compile dataDependencies.recyclerView
    compile dataDependencies.annotations
    compile dataDependencies.customTabs

    testCompile testDependencies.junit
    testCompile testDependencies.robolectric

Again, the complete file is available here on GitHub.

Android Reverse Engineering 101 – Part 5

In our introduction journey in the Android reverse engineering world, so far we’ve seen what is an APK and its format, how we can extract useful information about an application using aapt, which is provided by the Android SDK, how we can convert the DEX bytecode to a more readable and easily editable format and how we can actually decompile and modify an Android application (source code and resource).

In this last part of the series, we’ll have a look at Androguard, a full python tool to play with Android files.

According to the official website, Androguard let us play with:

  • APK
  • Android’s binary xml
  • Android resources
  • Disassemble DEX/ODEX bytecodes
  • Decompiler for DEX/ODEX files

The complete list of features is quite impressive and even though on GitHub is not fully reported, it can be found here.

Androguard is available for Linux, OS X and Windows.


The installation procedure is described in great details in the old project home, while on the new GitHub page the documentation doesn’t provide any updated information.

What is important is to have Python installed on our machine (2.6 or later versions), and this let us decompile/disassemble APK files only. For more advanced features it’s necessary to install more modules: on the installation page we can find the complete list with a short explanation about why each module is required.

It’s just important to remember to run the following command from the main Androguard folder:

sudo python install

After the installation, we can directly run the tools from the main directory of Androguard.

Specially if the operating system of the machine is Windows, there’s also the possibility to run Androguard (actually many other reverse engineering tools) from ARE – Android Reverse Engineering virtual machine: download and installation procedures can be found at the official wiki page. We just need to rely on VirtualBox to run the image.

All the examples of the article will be run using this Androguard version: 2.0. It can be downloaded directly here, otherwise there’s also the chance to pick a specific version from the stable releases page.

The first thing to do, is to check if our installation is properly working, so let’s move to the main Androguard folder and type the following command: -s

We should get an output like this:


The interactive console (with commands history support) is ready to accept the first inputs.

It’s now necessary to set the APK to analyze and the decompiler type. In fact, 3 different decompilers are supported: DAD, DED and dex2jar + jed. Specific details are available here and for the following examples, we’ll use DAD because is the default decompiler, so nothing in specific must be done at installation time to enable it.

a,d,dx = AnalyzeAPK("FILENAME.apk", decompiler="dad")

It could take some time depending on the specific APK being decompiled: when the procedure is done, we’ll be able to run other commands from the prompt.

We can now type a. and then press TAB key the get the full list of APK related commands directly from the prompt.

Let’s start with some simple commands, useful to get some info out of an APK.


APK files

It’s possible to list all the files contained in the APK package (which is essentially a ZIP file):



Application Activities

With the following command, we can extract the list of Activities in the application:



Application permissions

With the following command, we can extract the list of permissions requested in the manifest file by the application:


It’s even possible to get a detailed description for each permission:


An important feature to highlight about Androguard, is the possibility to know which part of the application code is requesting permissions to be declared in the manifest.

That’s very important because it can help us to:

  • know if we’re missing any permission declaration in the manifest
  • know if we’re asking for more permissions than required in the manifest
  • review the pieces of code where permissions are required and double check if we must add a missing annotation in case we’re using them.


Application Content providers

With the following command, we can extract the list of Content providers declared by the application (if any):



Application signature

It’s also possible to know where the signature of the APK is stored and the signature itself:



Here is available the documentation with the full list of commands that can be used: it’s for version 1.9 of the tool, but it’s a good reference anyway.

Code dumping

Using the androdd tool, we can get the source code all the classes packaged in the APK (application code + dependencies): in this case, rather than getting .class files as we do using dex2jar, in output we get Java classes. -i FILENAME.apk -o OUTPUT_DIR

In the output directory, Java classes are organized by package name as expected.

Of course, what we get is not exactly the same code as the original one implemented by the developer, but it’s anyway readable and very easy to understand. Please bear in mind that if the original application code has been obfuscated, methods and classes names could have been renamed and the tool is not able to restore the original names.

Here below an example of one Fragment class: the original source code is available here.


As we already seen during this series, don’t expect to see resource names, such as strings, layouts, arrays, colors, but what we get is the integer assigned to a specific resource at build time and stored in the file. Here it’s represented as a decimal value, while in the original class file is in hexadecimal.

XML manifest

Using the next tool, we can extract the manifest file, which is stored in binary format inside the APK file, in plain XML, so easily readable and viewable. -i FILENAME.apk -o OUTPUT.xml

If we open the output XML file, we can see the complete manifest file of the APK, nearly identical to the original one.


Comparing two APKs

One important tool provided by Androguard is androsim, which essentially compares two applications files. That’s an important feature because we can compare the APK of the original application against one which could be potentially altered to add malware. Of also simply to see the different between two different releases of the same application.

danielealtomare$ -i FILENAME_1.apk FILENAME_2.apk -c ZLIB -n

That’s the output for comparing two identical APKs:

androsim identical APKs
androsim identical APKs

While the following is the result for comparing two different releases of the same application:

androsim different APKs
androsim different APKs

Adding --help we can get all the options available for this tool, so the analysis can be even more precise and focused on specific aspects of the application.


A course there’s a lot more we can do with Androguard, but the aim of this article is just to present the tool and from that start any kind of experiment and analysis.


Before concluding the series, there are a couple of tools which are worth a mention.

The first one is Bytecode Viewer, and it’s actually a complete suit of reverse engineering tools: it allow us to easily edit APKs via smali/baksmali integration and more in general open Android APK and DEX files. dex2jar and Apktool are integrated too. A bit more about it can be found here.

The second one is ClassyShark, which is a handy browser for Android executables. It has clients for both Android (APK) and Desktop (JAR). With ClassyShark we can open APK/Zip/Class/Jar files and analyze their contents.

This ends the series: as already highlighted, this was just an introduction to the Android reverse engineering world and the main tools involved in this practice. Of course it really depends on what we need to do, so we may find some tools more suitable while others could be not helpful at all.

Android Reverse Engineering 101 – Part 4

In this introduction series to Android application reverse engineering, after having talked about the APK formataapt and dex2jar, the next thing we’re going to turn our attention to is Apktool.

As we have seen, resources in an APK are compressed and stored in binary format and neither aapt nor dex2jar can help us to view and edit them: the former is essentially a read-only tool, useful to extract information, while with the latter we can work with the executable code of the APK but not the resources.

According to the official website, Apktool is:

A tool for reverse engineering 3rd party, closed, binary Android apps. It can decode resources to nearly original form and rebuild them after making some modifications; it makes possible to debug smali code step by step. Also it makes working with an app easier because of project-like file structure and automation of some repetitive tasks like building apk, etc.

So it seems a good candidate, because it’s able to decode resources.

As it’s underlined, it’s important to remember that this tool is not intended for piracy and other non-legal uses.


The installation procedure is described here in great details: just check to have the proper Java version installed and then jump to the instructions related to any of the supported environments: Windows, Linux and Mac OS X.

All the examples of the article will be run using this Apktool version: v2.0.2.

If everything is correctly installed and set up, we should get this output simply typing apktool in a terminal window.


Before starting to issue the very first command, we still need to take care of one aspect: choose an application. As I did for the dex2jar article, I picked RGB Tool because it’s an open source application and I’m part of the project, so there will be no issue in reverse engineering it: we can get the APK here.

For all the examples, I have used RGB Tool v1.4.3 and a Nexus 6 running Android 6.0.


Frameworks are important when we decompile framework dependent APKs or system applications. In fact, on any device or emulator, as part of the system image, there is always an APK file containing all the resources of the ROM: images, animations, sounds, splash screens, …

The actual file is usually: /system/framework/framework-res.apk

Simply put, this file contains essential resources for the general look and feel of our device, which are used by system or other applications, so any manufacturer, such as Samsung, HTC, Motorola, LG, … provides its own framework APK file.

Apktool, by default, uses the framework from the AOSP and place a copy of this file at this location (on a Mac OS X): $HOME/Library/apktool/framework/1.apk

If we need to decompile system applications which are based on a different framework, we have the possibility to install it, otherwise we could get the following error:

W: Could not decode attr value, using undecoded value instead: ns=android, name=drawable
W: Could not decode attr value, using undecoded value instead: ns=android, name=icon
Can't find framework resources for package of id: 2. You must install proper framework files, see project website for more info.

The first thing to do is to retrieve the framework APK file from a device with the adb pull command: usually we can find it in /system/framework, but we can double check here to have the complete list of all the possible locations in case is not there.

Then we can install it: apktool if FRAMEWORK.apk

After this operation, we will be able to decompile a system application.

Note: next sections of the article use the default AOSP framework, so it’s not required to install a custom one.


The decode operation of an APK can be easily run with the following command:

apktool d FILENAME.apk

apktool decode
apktool decode

The tool creates a folder named after the APK file just decoded.

apktool decode output
apktool decode output

Please notice the content of the output folder depends on the specific APK and the files packaged in it.

The first thing to note is the apktool.yml file: it contains important information like application version name and code, min and target SDK version, … This file is essential when we build back the APK file, specially if we want to change any of those values.

Then we have the AndroidManifest.xml file in XML format, not binary, so we can view and modify it.

The original folder usually contains the AndroidManifest.xml file in binary format and the META-INF folder with the JAR manifest and the signature of the APK. Basically these two items are copied directly from the APK without any modification.

The smali folder contains the application source code in smali format: I’ve already talked about it in my previous article, so I just mention a couple of things. First, the code is organized in folders by package name and what we get is the full executable code: this means code from dependencies is also present in the folder. Then, having the option to rebuild the APK as we’ll see later, we can modify these files and it will be reflected in the newly produced APK.

The last folder is res, and as we can guess this is the resources folder: Apktool is able to decode resource files (remember inside the APK they are stored in a binary file called resources.arsc), so we can view and of course also modify them. Here there’s one important thing to highlight: since what we decode is the APK, so an application that can be run on any device, resources from the dependencies of the application are also present in this folder. So don’t be surprised if we see more resources than the one we have in our Android Studio projects. To make it clear, if we declare the AppCompat v7 as a dependency in our project, here we will also get its resources (the ones starting with abc_).

Last thing to note, the names of the subfolders of res could not exactly match the ones in our project or the original application: Apktool creates them in order to be able to build back a working APK, so it needs to name them taking that into account.


The build process can be started issuing the following command:


This builds the output folder resulted from a decode operation and places the resulting APK in APKTOOL_DECODE_OUTPUT_DIR/dist.

Otherwise we can also specify the destination APK:

apktool build
apktool build


apktool build output
apktool build output


Please notice that the APK built with Apktool is not signed, so it cannot be installed on a device.

In fact, if we try to install the APK in the dist folder, we get the following error:

APK not signed error
APK not signed error

So, before installing the APK on our device, we must sign it with the following command (it prompts us for passwords for the keystore and key):

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1
-keystore my-release-key.keystore my_application.apk alias_name

If it’s not a release build, we can always rely on the debug keystore, the same used by Android Studio to sign debug builds. The actual file is usually stored in an hidden folder (home folder depends on the specific environment):


Keystore password is android, key alias is androiddebugkey and key password again android.

Instead, if we need to create the keystore, we can refer to the official documentation (it also suggest us to zipalign the APK after the signature process).

Let’s have a bit of fun!

Now that we know how to decompile and re-build an application, let’s try to do some small changes, just to test Apktool features.

First of all, let’s have a look at the original application main view, just to be able to compare it later after our modifications.

RGB Tool original main view
RGB Tool original main view

Application name and main theme

As a first thing, let’s change the application name and the main theme colors.

If we look at the manifest file, we can see the application name is stored in a string resource called app_name. So let’s open values/string.xml file and change the value from RGB Tool to MyRGB Tool.

About the theme colors, let’s again have a look at the manifest file to check if a theme is set at application level: it is and it’s called Theme.Rgbtool. We can find its declaration in values/styles.xml, and what interests us is this part:

<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/accent</item>

So, let’s move to values/colors.xml and change these colors. Regarding this point and more in general main theme colors, I suggest you to bookmark Material Palette.

I have defined the new colors as it follows:

<color name="primary">#4CAF50</color>
<color name="primary_dark">#388E3C</color>
<color name="accent">#FFC107</color>

Let’s build the application, sign the APK and have a look at our changes. Please remember we always have to resign the APK every time is built and it has to overwrite the existing application on the device too.

Modified RGB Tool
Modified RGB Tool

Application icon

In the same way, we can update the icon of the application because as we know it’s just a drawable PNG file and its name is set in the manifest file again, as for the previous attributes. So, the change is very trivial, in fact it’s just necessary to update few PNG files (there could be a PNG for different screen densities) with new resources and build again the APK.

For this specific examples, the icon is set as @mipmap/ic_launcher.

To help us create a simple set of valid launcher icons, we could take advantage of the Android Asset Studio, choosing Launcher icons option.

After having updated the PNG files, built and signed the APK, this is the new application icon displayed on the launcher:

New application icon
New application icon

New resources

So far, we have just replaced existing resources, using the same file name, but what if we would introduce a completely new resource in the application? Let’s try to do that.

If we open the application and we decrease the value of the opacity (O), we can see an Android robot appearing in the background:

RGB Tool android
RGB Tool android

The resource is called @drawable/robot and it’s used in a bunch of layouts: let’s take it, duplicate, change its color and call it robot_apktool. Then, we have to replace in all the XML layouts the reference robot to robot_apktool. Done that, we can rebuild the APK, sign and install it on our device.

New robot
New robot

Our new robot is there! That was easy honestly, because that resource is only referenced by XML files but never in any Java class. That’s a crucial difference when we have to add new resources: we’ll see why in a moment.

Can we change the source code?

Yes, as said before in the article, Apktool decompiles the executable code of the application and produces .smali files, so we can directly change them and rebuild the APK. Of course, working with smali it’s not like working with Java classes, the syntax is quite verbose and not so easy to understand at the beginning. We can open these files with any text editor, even if we would miss important features like syntax highlighting and autocompletion. On the positive side, we can easily search strings with grep for example.

There are also a couple of tools to mention: one is an open source syntax highlighter, while the other one is fully featured solution which actually does more than smali editing.

Let’s try a very simple change just to have to deal with smali: if we click on the Print color option (it could be necessary first to click on the overflow menu icon), the following dialog appears on the screen.

Skip string

What we’re going to do is change Skip button text to Apktool: this example is significant because the string resource is used in a Java class and not in an XML resource file.

The resource name is action_common_skip: so let’s create a new string item in res/values/strings.xml, calling it action_common_skip_apktool. There are also Italian and French resources, but for this example it’s enough the default value.

Now, if we search for action_common_skip, we see that it’s present in the 3 string resource files (default, Italian and French) and in file called public.xml. That’s interesting, no smali files appears in the search results even though, looking at the original Java class, we know that this string resource is actually used in the source code. So, let’s open this XML file and also the smali file of the dialog, PrintJobDialogFragment.smali.

public.xml is the list of all the resources of the application, such as strings, layouts, drawables, colors, … and for each resource an hexadecimal id is set. These ids are actually the values present in the file create by the Android Build System when we build a project: that’s it, Apktool creates this XML file while it extracts the resources of an APK and it decompiles the code. As already pointed out in the previous article of this series, if we reference a resource in our Java class, such as an Activity, what it’s actually used is an id, an integer, which is stored in the generated class

So, let’s try to search the id of our resource in the smali file:

<public type="string" name="action_common_skip" id="0x7f070017" />

Interesting again! It’s actually used (please notice that using another application or building RGB Tool cloning the repository, could result in having a different id value from the one this example):

const v2, 0x7f070017

invoke-virtual {p0, v2}, Lcom/fastebro/androidrgbtool/fragments/PrintJobDialogFragment;->a(I)Ljava/lang/String;

move-result-object v2

So, the id value is stored in a const called v2, then it’s used as a parameter for a virtual method invocation (which would be setTitle). A good summary list of opcodes can be found here.

Now we have all the elements: we know we must update the public.xml file, adding our newly defined string, and also the id value in the smali file.

For the first change we need to be careful: as we can notice, the resources are ordered by type and the ids are sequential, so we cannot set any value we want. We need to search for the last string resource and then add the new one, adding 1 for the id (remember those are hexacedimal values). In the example, last string id is 0x7f070051, so that’s what is required to be added:

<public type="string" name="action_common_skip_apktool" id="0x7f070052" />

The second update is instead very simple, just replace the old id value with the new one in PrintJobDialogFragment.smali.

Now, let’s rebuild, sign and install the new APK on the device: as we can see our new string is displayed.

New string resource
New string resource

That’s all for this update and the main features of Apktool: I encourage you to test it using an APK for which you have the original source code. It’s really much easier to understand how resources decoding works and to read smali code. Modifying and rebuilding an APK really depends on the changes you perform and on the original version of the application.

In the next update I will focus on Androguard.

Android Reverse Engineering 101 – Part 3

In the first two articles of the series, I wrote about the APK format and the aapt tool.

In this post I will focus on dex2jar, a tool to work with Android  .dex and Java .class files: there are few mirrors, but you can point here for the official website.

The core feature of this tool is, as you would expect, converting the classes.dex file of an APK to classes.jar (or any name of your choice of course) or vice versa. So it’s possible, using any Java decompiler tool, to view the source code of an Android application.

What you get are .class files, don’t expect to get Java source code that was written by the application developer: however, as you’ll see later, it’s completely readable.


To get the latest available version, please go to one of the official repositories.

The installation process is quite straightforward: you just have to unzip the package in a folder of your choice and then add that location to your path. That’s it, you’re ready to start using dex2jar!

Note: it might be possible that you need to give execution rights to the script files contained in the folder.

At the time of writing, the latest stable release is 2.0, so this is the version used in the rest of the article.

version: reader-2.0, translator-2.0, ir-2.0

Before digging in the core features of the tool, if you take a look at the content of the dex2jar folder, you can notice that several scripts are available (both Unix/Mac and Windows versions): that’s because each major feature supported by dex2jar is provided in a separate script: I think it’s a good solution so you don’t have to pass too many arguments to one executable.

dex2jar folder content
dex2jar folder content

Let’s now move to the core feature of the tool: converting DEX classes to JAR.

If you have read the first part of this series, you know that executable code inside an APK file is in DEX format, which can be defined as an Android bytecode format. Of course, it would be better to have an easier to read format in order to analyze the code of one application and this is exactly where dex2jar can help you.

Before issuing the very first command, we need to pick an application from Google Play Store and also install a decompiler to view the source (on other hand what we get are .class files, not .java):

  • RGB Tool: it’s an open-source application, so it’s not a problem to reverse engineering it. You can directly get the APK here.
  • JD-GUI: yet another fast Java decompiler with a UI.

The first command we’re going to test, lets you extract the executable code of the application in JAR format: -f -o classes.jar FILENAME.apk

With the -o option, you specify the name of the output file of the command, while -f simply tells dex2jar to overwrite this file if it’s already existing.


If you open the output file with JD-GUI, you can see the source code of the application: again, what you get is not exactly what was written in the Java classes, but it’s enough clear to read. Underlined items are clickable, so it’s also very easy to navigate through the code.

JD-GUI classes.jar
JD-GUI classes.jar

Just for your reference, here you can find the original source code of the file displayed in the screenshot.

Where are the resources?

If you carefully look the screenshot, you have certainly noticed that instead of resource names, like, … there are numbers: these are the IDs stored in the class file as explained by the official documentation. This file is automatically generated at build time (don’t modify it manually!) and it can be found in the .../build/generated/source/r/... folder of your project. It’s essentially a final class which defines static final classes for each resource type, such as strings, layouts, arrays, colors, dimens, … and for each of them it defines static final int fields, you resource IDs. In this way, while implementing your application, you don’t have to deal with numbers directly.

IDs are stored in hexadecimal, so the 0x7f080000R.array.pick_color_array  in the original application source code) is the 2131230720 (decimal) used by getStringArray in the file extracted by dex2jar (you can see it in the screenshot above of SelectPictureDialogFragment.class).

Obfuscated code

I picked this specific application because I know its code has been shrunk and obfuscated with ProGuard: you can clearly see that because several packages and classes are named  a,  b,  c, …

In the screenshot here below, it’s evident the work done by ProGuard to change method and variables names and to scramble the flow of the code. However, the code is still quite readable and it’s not particularly difficult to find and understand specific algorithm or business logic.

Of course, not all the classes have been obfuscated, but this depends on the specific rules declared in the ProGuard configuration file: for the application used in this example, it can be found here on GitHub.

Obfuscated code
Obfuscated code
Out Of Memory Error

The current documentation is not updated about this topic, anyway it’s possible, while converting DEX to JAR or viceversa, to get an OutOfMemoryError issue: very likely you’re trying to translate a large size DEX file.

You need to increase the size of the memory of the JVM and in order to do that, you have to open the d2j_invoke script and look for this line:

java -Xms512m -Xmx1024m -classpath "${_classpath}" "$@"

Change the values accordingly to your system and needs: personally, in my experience, I just had to change the size of the memory allocation pool like this: -Xmx2048m .

Back to DEX

dex2jar supports also the conversion from .class to .dex: this is particularly interesting because it gives the possibility to put back executable code into the APK file.

The specific command is: -f -o classes.dex classes.jar

With the -o option, you specify the name of the output file of the command, while -f simply tells dex2jar to overwrite this file if it’s already existing.


The APK file is essentially a ZIP file, so the new DEX file can be inserted back quite easily:

zip -r FILENAME.apk classes.dex

Remember this operation alters the original APK file, so you can’t simply install it on your device, but you have to sign it again with jarsigner in order to regenerate the MANIFEST.MF file. This is a security safeguard against altering an application: if you do it, you have to resign the package and since you do not have the keystore and private key used for the original application, you can’t release your altered APK as an update of the original one.

When the system is installing an update to an application, it compares the certificate in the new version with those in the existing version. The system allows the update if the certificates match.


From the official page:

smali/baksmali is an assembler/disassembler for the dex format used by dalvik, Android’s Java VM implementation. The syntax is loosely based on Jasmin’s/dedexer’s syntax, and supports the full functionality of the dex format (annotations, debug info, line info, etc.).

Diving into details is beyond the scope of this article, but I wanted to introduce you anyway to smali and baksmali, just to let you know that is possible to get .smali files directly from the classes.dex file.

That means you can change the source code of an application directly working with this format.

The command is quite simple: FILENAME.apk


The tool creates a new folder, naming it appending the suffix -out to the APK file name: inside the files are organized by package name.

smali output folder
smali output folder

Just to give an idea, this is what a smali file looks like: it’s not so hard to read and once you get used to its syntax it becomes quite understandable.

Please notice this is the a.class file for which I have posted a screenshot here above, while talking about obfuscated code.

smali file
smali file


apktool is also able to manipulate smali files: I will show you in the next part of the series.

That’s all for this update and dex2jar: as you have seen, with a relatively simple to use tool, you can already extract (and possibly put back) a lot of information from and to an APK file. But the tool lacks the support for XML resources and they are an important part of any Android application.

In the next part I will introduce you to apktool and that’s where things get really interesting.