Auto ‘versionCode’ increment when building production apk’s

Android, Smartphone, Android Developer, Android Studio

Since I adopted Fabric as a way to monitor vital app stats such as ‘Time in App per User‘ and it’s Beta distribution platform to distribute test builds, increasing APK’s versionCode numbers became a tedious task.

I decided to simplify the things by letting Gradle to do auto versionCode increments when producing release APK’s

Our implementation of build number increments will consist of a property file named version.properties located in the root folder of our project.

The property file will contain 2 variables, one defining the version name such as “2.3” and one defining the version code such as 15

VERSION_NAME=2.3
VERSION_CODE=19

In our app module build.gradle file

build.gradle

we will define a function which takes care of retrieving the a bough mentioned values from the properties file and increment the VERSION_CODE if needed.

/**
 * Get's value from 'version.properties' file
 * @param varName the name of the variable which value we wan't to get.
 * @return the variable value.
 */
def getVersionPropertiesValue(def varName)
{
    def propertiesFile = file('version.properties')
 
    if(!propertiesFile.canRead()) {
        throw new GradleException("Could not read " + propertiesFile.name)
    }
 
    Properties properties = new Properties();
    properties.load(new FileInputStream(propertiesFile))
 
    def propertyValue = properties[varName]
    if(varName == 'VERSION_CODE')
    {
        // If we are building release increment the version code
        List gradleTasksNames = gradle.startParameter.getTaskNames();
        for(String taskName : gradleTasksNames)
        {
            if(taskName.contains("Release"))
            {
                propertyValue = propertyValue.toInteger() + 1
                properties[varName] = propertyValue.toString()
                properties.store(propertiesFile.newWriter(), null)
                break
            }
        }
    }
 
    return propertyValue
}

In the defaultConfig section of the gradle build script we will call this function to retrieve values for the versionName and versionCode of our app.

android {
    compileSdkVersion 28
 
    defaultConfig {
        applicationId "com.example.foo"
        versionCode Integer.valueOf(getVersionPropertiesValue('VERSION_CODE'))
        versionName getVersionPropertiesValue('VERSION_NAME')
        minSdkVersion 14
        targetSdkVersion 28
    }
}

Now each time a release build is made, the version code will increment automatically. If we want to change the version name we can do so by changing the value of VERSION_NAME property.

If you liked this article and think it is useful use the buttons below.

Copying Cyrillic URLs in Google Chrome and Firefox

Using Google Chrome, I encountered strange bug affecting the copying and pasting of cyrillic urls.

When pasting, the non ASCII characters in the Url are converted to Punycode.

Performing some tests revealed that the same behaviour is present also in Firefox.

Punycode produced by Google Chrome and Firefox
Punycode produced by Google Chrome and Firefox

Doing some research led me to Issue 68718, unfortunately marked as WontFix stating:

Links on Wikipedia itself are a red herring, as comment 50 notes -- they're escaped in the page source.  The actual issue here is demonstrated by the link in comment 0.  We escape URLs when copying them.  This behavior matches Firefox 4 (by default) and Safari 5, though not IE9.

We added this behavior on  issue 2820  to fix a variety of problems in languages like Japanese.  Because those problems resulted in users unable to navigate to the pasted links, whereas this issue seems to be solely about cosmetics (in that escaped URLs are ugly and hard to read), preserving that behavior change seems like the more important thing to do.

Workarounds

Few things can be done if this issue is affecting your day to day usage of Google Chrome…

  • Before copying the URL add any character at the end of it, then erase it. After this operation the copied URL will preserve its structure not producing punycode when pasted.
  • Use the COPY URL extension.
  • Use a different browser. Microsoft Edge on Windows and Safari on OSX are producing the expected results.

Featured Image: https://wallpapercave.com/w/A7ZAUTz

If you liked this article and think it is useful use the buttons below.

Settings.canDrawOverlays() allays returns ‘false’ on Android O

I was updating one of my clients app, and testing it how it behaves on Android O (API 26). The app requires permissions to draw over system windows (android.permission.SYSTEM_ALERT_WINDOW). On Android 6 (API 23) and up, you are obligated to request ‘special’ permissions while the app is running.

The ‘SYSTEM_ALERT_WINDOW’ permission is a special permission that breaks the rules set by the new permission model available on Android 6 (API 23) and up. It’s request involves calling Settings.canDrawOverlays() and if it returns ‘false‘ starting ‘Settings‘ where the user can choose to grant your app the ability to draw overlays or not.

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
   // On API 23 and later ask the user to grant us permission to draw system overlay
   // windows.
   if (!Settings.canDrawOverlays(this))
   {
      Intent intent = new Intent(
             Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
             Uri.parse("package:" + getPackageName()));
 
      startActivityForResult(intent, REQUEST_PERMISSION_SYSTEM_OVERLAY_RESULT);
   }
}

There is a bug with Settings.canDrawOverlays() (only) on API 26 where it will always return ‘false’ disregarding the actual user decision. The workaround provided here is a bit ugly, but does not involves restarting the app (which will be quite annoying for the user) after the permission is granted.

The code below first checks the result of System.canDrawOverlays() if it returns ‘true’ it continues with the rest of the application flow. If it returns ‘false’ a check if we are running on Android O (API 26) is performed. If that’s the case, we are calling our ‘workaround’ method.

The ‘workaround’ method tries to add an invisible overlay window on the screen, and if that’s OK we assume that we have a permission to draw overlays, else an exception is thrown.

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
 
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return; if(requestCode == REQUEST_PERMISSION_SYSTEM_OVERLAY_RESULT) { if(Settings.canDrawOverlays(this)) { m_permissionSystemOverlayWindowGranted = true; if(m_permissionReadPhoneStateGranted && m_permissionProcessOutgoingCallsGranted) { startService(new Intent(this, EstatePlusService.class)); m_layoutNoPermissions.setVisibility(View.INVISIBLE); m_progressBar.setVisibility(View.INVISIBLE); m_layoutLogin.setVisibility(View.VISIBLE); } } else if(Build.VERSION.SDK_INT == Build.VERSION_CODES.O) { // NOTE: This is a workaround to fix the bug in Android O where the // Settings.canDrawOverlays() will always return 'false' if(canDrawOverlays(this)) { m_permissionSystemOverlayWindowGranted = true; if(m_permissionReadPhoneStateGranted && m_permissionProcessOutgoingCallsGranted) { startService(new Intent(this, EstatePlusService.class)); m_layoutNoPermissions.setVisibility(View.INVISIBLE); m_progressBar.setVisibility(View.INVISIBLE); m_layoutLogin.setVisibility(View.VISIBLE); } } } } } /** * Workaround for Android O */ public static boolean canDrawOverlays(Context context) { try { WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (windowManager == null) { return false; } final View viewToAdd = new View(context); WindowManager.LayoutParams params = new WindowManager.LayoutParams( 0, 0, android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ?
                                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT);
            viewToAdd.setLayoutParams(params);
            windowManager.addView(viewToAdd, params);
            windowManager.removeView(viewToAdd);
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
 
        return false;
    }
If you liked this article and think it is useful use the buttons below.

I brought myself a Christmas present

After being upgraded to June 2017 iMac 27″ 5k Retina at work, and using it for a week, I decided it’s about time to purchase myself an iMac. My first impression with this machine is fantastic, everything just works (fast and smooth) and the 5K Retina is amazing.

Today (after being financially stable, after some time 🙂 ) I ordered 27″ iMac 5K Retina equipped with 4.2GHz Quad-Core Intel Core i7, 16GB 2400MHz DDR4 (will be upgraded to 32 or 64 GB later), 2TB Fusion Drive and Radeon Pro 580 with 8GB VRAM.

It will arrive around 20 Jan 2018. It will be a nice time to start developing apps for iOS and bring VMSoft to the app store as well. Also a lot of my clients were asking me when will I start developing for iOS.

If you liked this article and think it is useful use the buttons below.

Fighting spammers: Removing Website URL Field from Comment Form

I’m tired of receiving massive amount of spam comments on my blog (1280 spam comments for about a month) and doing:

DELETE FROM `wp_comments` WHERE `comment_approved` = 0

Beside using SI Captcha Anti-Spam which does pretty good job in keeping some of the automated spam bots at bay, I noticed some trend in the spam comments flooding my posts, they are all full of SEO keywords and they are heavy abusing the Website field in the comment form.

Here is a small “plugin” which will remove (unset) the URL field in the comments form:

<?php
/*
Plugin Name: Remove Website field from comments.
*/
function custom_comment_fields( $fields ){
  if(isset($fields['url']))
    unset($fields['url']);
  return $fields;
}
 
add_filter( 'comment_form_default_fields', 'custom_comment_fields' );

Create a file in /wp-content/plugins/ with the code a bough. Go to the ‘Plugins’ section of the admin panel and activate the newly created plugin named “Remove Website field from comments”.

Yey, no more “Website” field in the “Leave a Reply” section 🙂

If you liked this article and think it is useful use the buttons below.