Disabling logs on Android using ProGuard

A quick way of disabling the logs for release builds is using ProGuard to take care of it. To do it in our current project we’ve created two ProGuard configurations, the one that applies for all the builds and the one that only applies for the release build.

Then, we can configure the build.gradle file like this:

apply plugin: 'com.android.application'

// snip...

android {

    // snip...

    buildTypes {
        release {

            // snip...

            // Enable ProGuard
            minifyEnabled true

            // Common release options
            zipAlignEnabled true
            debuggable false
            jniDebuggable false

            // Notice that the default ProGuard file (SDK-provided) also enables optimization
            // Here we also include a third file which disables the logging (see below)
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro', 'proguard-rules-disable-logging.pro'

        debug {
            // We enable ProGuard also for debug builds
            minifyEnabled true

            // Notice that the default ProGuard file (SDK-provided) differs from the release one
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

The file to disable logging is as simple as that:

## Disable logging

# Disable Android logging
-assumenosideeffects class android.util.Log {
    public static boolean isLoggable(java.lang.String, int);
    public static int v(...);
    public static int i(...);
    public static int w(...);
    public static int d(...);
    public static int e(...);

# This gets rid of System.out.println() and System.out.print()
# WARNING: if you're using this functions for other PrintStreams in your app, this can break things!
-assumenosideeffects class java.io.PrintStream {
    public void println(...);
    public void print(...);

Android compatibility with 32-bit libraries on a 64-bit device

Recently I run into a problem with an app we’re working on: suddenly it stopped to work on a Samsung Galaxy S6 Edge. It was still working on all the other, older devices. The first idea was: the app is using a JNI library, so it’s a 64-bit compatibility problem. And bingo! This was the reason… but in an unexpected way.

The strange thing was that the app used to work on this device, and with this library (SQLcipher, to keep data secure on rest). So we started to see what changed: the OS recently got an update, to 5.1.1. Maybe there was a compatibility provision on the OS, but after this OS upgrade this had been disabled.

After some investigation, I found the following post in stackoverflow.com: Use 32-bit jni libraries on 64-bit android. Basically the answer stated that as far as you use System.loadLibrary() to load your JNI libraries, a 64-bit OS will try to load the 32-bit version of your library if it doesn’t find a 64-bit version. But this was not happening any more!

After some further investigation, I found that recently we added a module provided by a third party, which had a dependency to another library that had compatibility to both 32 and 64-bit. I’ve added ** next to each of the offending files.

$ unzip -l myapp-development-debug.apk
  186244 09-10-15 11:31 lib/armeabi/libdatabase_sqlcipher.so
 2478904 09-10-15 11:31 lib/armeabi/libsqlcipher_android.so
  390456 09-10-15 11:31 lib/armeabi/libstlport_shared.so
  182156 09-10-15 11:31 lib/armeabi-v7a/libdatabase_sqlcipher.so
 2421584 09-10-15 11:31 lib/armeabi-v7a/libsqlcipher_android.so
  374076 09-10-15 11:31 lib/armeabi-v7a/libstlport_shared.so
 1580868 09-10-15 11:31 lib/x86/libdatabase_sqlcipher.so
 3897372 09-10-15 11:31 lib/x86/libsqlcipher_android.so
  563148 09-10-15 11:31 lib/x86/libstlport_shared.so
   34224 09-09-15 13:29 lib/arm64-v8a/libpl_droidsonroids_gif.so **
    9624 09-09-15 13:29 lib/arm64-v8a/libpl_droidsonroids_gif_surface.so **
   38064 09-09-15 13:29 lib/armeabi/libpl_droidsonroids_gif.so
   17572 09-09-15 13:29 lib/armeabi/libpl_droidsonroids_gif_surface.so
   29884 09-09-15 13:29 lib/armeabi-v7a/libpl_droidsonroids_gif.so
   13488 09-09-15 13:29 lib/armeabi-v7a/libpl_droidsonroids_gif_surface.so
   73488 09-09-15 13:29 lib/mips/libpl_droidsonroids_gif.so **
   71132 09-09-15 13:29 lib/mips/libpl_droidsonroids_gif_surface.so **
   41544 09-09-15 13:29 lib/mips64/libpl_droidsonroids_gif.so **
   10360 09-09-15 13:29 lib/mips64/libpl_droidsonroids_gif_surface.so **
   33868 09-09-15 13:29 lib/x86/libpl_droidsonroids_gif.so
    9280 09-09-15 13:29 lib/x86/libpl_droidsonroids_gif_surface.so
   34416 09-09-15 13:29 lib/x86_64/libpl_droidsonroids_gif.so **
    9816 09-09-15 13:29 lib/x86_64/libpl_droidsonroids_gif_surface.so **
   95397 09-14-15 15:31 META-INF/MANIFEST.MF
   95426 09-14-15 15:31 META-INF/CERT.SF
    1318 09-14-15 15:31 META-INF/CERT.RSA
 --------               -------
 44599565               947 files

By simply using unzip tool we can clearly see the directories for the arm64-v8a and x86_64 architectures, and also the mips and mips64. In this directories the only present library are libpl_droidsonroids_gif and libpl_droidsonroids_gif_surface.

A quick and dirty solution to get rid of this libraries is to manually use “zip -d” to remove the unwanted architectures, like this:

zip -d myapp-app-development-debug.apk "lib/x86_64/*"
zip -d myapp-app-development-debug.apk "lib/mips64/*"
zip -d myapp-app-development-debug.apk "lib/mips/*"
zip -d myapp-app-development-debug.apk "lib/arm64-v8a/*"

Of course, this is useful to test that this is the cause of the crash, but not something you want to do on each build.

So, to automate this steps in Gradle we can use packagingOptions.exclude in the android section, like this (parts omitted):

android {
    compileSdkVersion Integer.parseInt(project.ANDROID_COMPILE_SDK_VERSION)
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION

    defaultConfig {


    packagingOptions {
        exclude 'META-INF/LICENSE.txt'

        exclude 'lib/arm64-v8a/libpl_droidsonroids_gif.so'
        exclude 'lib/arm64-v8a/libpl_droidsonroids_gif_surface.so'
        exclude 'lib/x86_64/libpl_droidsonroids_gif.so'
        exclude 'lib/x86_64/libpl_droidsonroids_gif_surface.so'
        exclude 'lib/mips/libpl_droidsonroids_gif.so'
        exclude 'lib/mips/libpl_droidsonroids_gif_surface.so'
        exclude 'lib/mips64/libpl_droidsonroids_gif.so'
        exclude 'lib/mips64/libpl_droidsonroids_gif_surface.so'


Notice that exclude doesn’t allow globs or wildcards, and we have to specify each file manually.

Language change detection in Android Jellybean 4.2+

In the current project I’m working on we had to detect system language change. We wanted to rely on Android configuration change mechanism, that handles this for us, but we had to do some additional state modifications beside UI.

So, the easy way is to detect configuration changes and handle them, following Handling Runtime Changes. Ok, so we decided to add a android:configChanges attribute with a value “locale” to the activity and add override onConfigurationChanged in the activity… and surprisingly nothing happened.

After some investigation we found that the problem happens on API 17+ and that the reason is that for this API, both “locale” and “layoutDirection” has to be specified, as Android now generates both in response to a language change (similarly to what happened in API 13+ with “orientation” and “screenSize”). The original answer came from StackOverflow.

BTW at the end we didn’t use this solution. Instead we used a BroadcastReceiver for the intent ACTION_LOCALE_CHANGED. The reason is this way we allow Android normal mechanism to handle the Activity restart for us (handling the configuration change by ourselves sidesteps this) and at the same time detect the language change.


Xcode switch tip

Today I’ve found a tip from Google about iOS development, on their “Route 85” Youtube video series. I always code defensively, and adding a default case option is one of the things you usually do on a switch when programming defensively. But in the case they show, this is a bad thing. When you write a switch statement for an enum, Xcode will warn you if you’re missing any value, except if you rule this option out by means of a default. See the video for more information and an example.

Nice tip guys!

Generating Repetitive CSS with Loops in LESS

Less is an amazing tool for simplifying your CSS: allows you to “extend” selectors (i.e. put selectors inside other selectors), to use mixins (i.e. a kind of “functions” that allow repeating optionally parametrized sets of CSS rules) and to use variables.

One missing feature is not having loops, for example to create a repetitive rule. Luckily enough, the language is powerful enough and there are smart people capable of taking advantage of that.

In this article I found the solution, which boils down to this:

// variables
@num-tiles-in-suit: 9;

// mixin with a guard to create a series of bamboo tiles
.makeTiles(@i) when (@i > 0) {
    @tile-value: @i - 1;
    // create the current tile rule
    .tile-@{tile-value} {
        background-image: url('/img/tiles/bamboo_@{i}.png');

    // next iteration
    .makeTiles((@i - 1));

// create bamboo tiles numbered 0-8

Finally, I also found this other article, which didn’t work, probably because it was written for an older version of Less (the article is almost two years old).

Converting a physical machine to VM

After many years in software development, I’ve switched machines many times. But I always tried to keep the old ones stored, just in case. Today I’ve finally decided to convert this old machines to a VM, and store only a hard disk and not the whole hardware.

First of all, I started the conversion using VMware vCenter Converter: I installed it to the physical machine (booting it was a small adventure by itself…), and made an image of the disk.

Then, I moved the image to my current system, and started VirtualBox. You can use VMware disk images in VirtualBox. The problem you can find is making Windows to boot. The machine I was converting was an old Windows XP, and switching from real hardware to virtual one poses a problem for this OS: the disk drivers used to boot the system up are “hardwired” at installation time, making this switch somewhat tricky.

So, I tried using the following parameters for the VM with no luck:

  • chipset: PIIX3
  • IO APIC disabled
  • PAE/NX enabled
  • IDE controller PIIX4 (original disk was ATAPI)

On first boot and next several attempts I got a STOP 0x0000007B. After some search, I found the solution was a registry tweak (Mergeide.reg) to be done before moving the system (i.e. before creating the disk image), plus unpacking some drivers to system32\drivers.

So, my solution instead of recreating the disk image was to attach the disk image to another working Windows XP VM, unpack the drivers and do the registry tweaks with this particular changes:

  • Load the system registry hive from the (still) non-functioning disk image by following this procedure. Where it reads “Highlight the HKEY_LOCAL_MACHINE-window and select the root of the tree” this means to select the HKEY_LOCAL_MACHINE key. I used the name “_system” (underscore preceding system).
  • You must tweak the mergeide.reg to point to “HKEY_LOCAL_MACHINE\_system” instead of “HKEY_LOCAL_MACHINE\system” and to “ControlSet00x” instead of “CurrentControlSet”. As I was not sure of which ControlSet was the active one (ControlSet001 or ControlSet003) I repeated the steps for both.
    WARNING: if you apply the changes to system instead of _system you can damage your working VM.
    Second WARNING: if you apply the changes to “CurrentControlSet” the system will not boot, with a STOP 0x67: CONFIG_INITIALIZATION_FAILED. To correct this, load the system hive again and remove the whole “CurrentControlSet” key, and then apply the registry patch again for “ControlSet00x”

That’s it! The system should boot now. After that, you will have to install Guest Additions, configure drivers, etc.

Atomically increment a limited value in MySQL and PHP

Sometimes you need to acquire a limited resource in an atomically, concurrent way. This is what semaphores are for. But when this resource is in a MySQL row, apparently there is no straightforward way of doing it.

In my case, I had a row with two fields used to limit maximum resource usage: ‘used’ and ‘limit’, both integer fields. Let’s complete it with an ‘id’, and then all the remaining information you need. To give you a more concrete example, I used this to limit the number of times you could possibly use a discount coupon.

So, while investigating the best way to do it, I considered the following options:

  • Using table locking: the problem is that, if you use a MyISAM table, this locking is done at a table level. Also, you statement gets more complicated, because you have to lock, modify and unlock.
  • Using transactions: this is not supported by MyISAM engine, and in my case I was adding this to an already existing table (not created by me, BTW…).

Finally, I came with the following method, which I think is pretty clear, clean and compatible. First of all, the query uses an atomically UPDATE statement, like the one you can found in this Stack Overflow question: Is incrementing a field in MySQL atomic?

$query = "UPDATE coupon SET used = used + 1 WHERE ID_coupon='" . $this->id . "' AND used < limit";

Now, notice the WHERE clause. It selects the row by two criteria: row id (as usual) and the condition that the 'used' field is less than the 'limit' field. So, what does mean? If the number of used coupons is less than the limit, the condition will be fulfilled and the row will be found by the database engine and updated, but if it is not it won't be found, thus the update will not happen, effectively limiting the 'used' value.

Finally, the other reason of doing this way is that MySQL returns the number of rows affected by the query. Usually, this will be 1, but if we've already reached the limit the condition will not be fulfilled and the number of affected rows will be 0. So, in PHP we can check this condition with something like this (in my case I was using PEAR DB, but you can find the equivalent statement to "affectedRows()" for MySQLi or PDO):

// Error handling omitted for brevity
$rows = $dbhm->affectedRows();
if ($rows > 0) {
  // We where able to use one coupon :D
  return true;
} else {
  // All the coupons have already been used :(
  return false;

Notice that probably this technique works on other DBs, and also can be applied to other languages than PHP.

Switching to Firefox again

The other day I stumbled upon the article Windows Timer Resolution: Megawatts Wasted and to make long story short, I ran powercfg -energy duration 5 on my system and found that Chrome, Spotify and Naver’s Line client for Windows were making my system to increase timer resolution to 1 ms, wasting energy and making my laptop run warmer than expected.

So I’ll be switching back to Firefox after quite a while using Chrome as my main browser, at least for regular browsing. Let’s hope Google fixes this soon.

Also, I’ve switched to Windows Store App version of Line client (my system runs Windows 8.1), and I’m considering what to do with Spotify.

UPDATE: maybe I’ve switched browsers too fast: now I’m seeing Firefox also increasing timer resolution to 1 ms! Possible causes:

  • Plugins (Flash, maybe?)
  • Google Mail
  • donno…

I’ll keep you posted.

Disabling right click and swipe on Windows Store Apps without using code-behind

A month ago I was working on a Windows Store project and I needed to disable right click and swipe for some grid controls. Of course, the property to disable/enable swipe is well known: IsSwipeEnabled. Just put a false there and you’re ready to go! But I could not find an equivalent property to disable right-click, and IsSwipeEnabled does exactly what it says: disable swipe touch gesture, but has no effect on right-click (which you may expect it will, because right-click is the equivalent manipulation using mouse).

Anyway, I found that the only way to disable right-click was to handle the right-click event, using code. So, my first thought was using code behind, and add an event handler and tell the remaining handlers that I handled the event already. So an event handler like this one should do it:

private static void RightClickEnabledProperty_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e)
    e.Handled = true;

But then, I thought I rather had a property implemented to be able to use it whenever I wanted without having to add more code behind to each XAML. So, here is the implementation for this property:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace App.Properties
    public class RightClickEnabledProperty
        public static readonly DependencyProperty IsRightClickEnabledProperty =
            DependencyProperty.RegisterAttached("IsRightClickEnabled", typeof(bool), typeof(RightClickEnabledProperty),
                                                new PropertyMetadata(true, IsRightClickEnabledPropertyChanged));

        public static void SetIsRightClickEnabled(DependencyObject attached, bool value)
            attached.SetValue(IsRightClickEnabledProperty, value);

        public static bool GetIsRightClickEnabled(DependencyObject attached)
            return (bool)attached.GetValue(IsRightClickEnabledProperty);

        private static void IsRightClickEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            bool? value = e.NewValue as bool?;
            if (!value.HasValue || value.Value)
                (d as UIElement).RightTapped -= RightClickEnabledProperty_RightTapped;
                (d as UIElement).RightTapped += RightClickEnabledProperty_RightTapped;

        private static void RightClickEnabledProperty_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e)
            UIElement control = sender as UIElement;
            if (control == null)

            if (!GetIsRightClickEnabled(control))
                e.Handled = true;


The downside of this is that the property must be defined in the item itself (usually in the top-level control or container inside the ItemTemplate), while the IsSwipeEnabled property is defined in the Grid or ListView itself.

See an example (remember to define the namespace in the root node of the XAML, like: xmlns:properties="using:App.Properties"):

    ItemsSource="{Binding ElementList}"
    SelectedItem="{Binding SelectedElement, Mode=TwoWay}"
                Text="{Binding ElementName}"

Hope this helps to keep your XAML a little more clean, with less code-behind.