Showing posts with label Android build system. Show all posts
Showing posts with label Android build system. Show all posts

Wednesday, 1 March 2023

A Journey Through Android History: Remembering the Technological Evolution.

 In the fast-paced world of mobile development, it's easy to get caught up in the latest trends and technologies. However, it's essential for developers to remember and appreciate the rich history that paved the way for the current state of Android. By understanding the past, we can better appreciate the present and anticipate the future. Join us on a journey through Android's remarkable history, from its humble beginnings to the powerhouse platform it is today.

The Birth of Android (2003-2007):

Our story begins in 2003 when Andy Rubin, Rich Miner, Nick Sears, and Chris White founded Android Inc. The initial vision of the company was to develop an advanced operating system for digital cameras. However, as the mobile industry started gaining momentum, Android Inc. shifted its focus to smartphones. In 2005, Google acquired Android Inc., setting the stage for what was to come.

Android OS 1.0: The Cupcake Era (2008):

In September 2008, Google released the first version of the Android operating system, Android 1.0, which was aptly named "Cupcake." This release introduced essential features such as push notifications, widgets, and the Android Market (now known as Google Play Store). Developers could now create and distribute applications, marking a significant turning point for the platform.

Maturing with Donut, Eclair, and Froyo (2009-2010):

With subsequent updates like Donut, Eclair, and Froyo, Android expanded its feature set and improved overall performance. These versions introduced features such as voice-guided navigation, live wallpapers, support for multiple screen sizes, and enhanced performance through JIT (Just-In-Time) compilation. Android started to gain popularity among both users and developers alike.

The Gingerbread and Honeycomb Divide (2010-2011):

The release of Gingerbread (Android 2.3) in 2010 marked the platform's focus on refining user experience and optimizing performance. Gingerbread introduced features like NFC support and a refined user interface.

Simultaneously, Honeycomb (Android 3.0) was developed exclusively for tablets. It introduced a revamped interface optimized for larger screens. Although Honeycomb's adoption was limited, it laid the groundwork for future tablet-oriented releases.

Ice Cream Sandwich and Jelly Bean: A Unified Experience (2011-2013):

In 2011, Android 4.0, code-named Ice Cream Sandwich (ICS), aimed to provide a unified experience across smartphones and tablets. It brought a refreshed UI design, improved multitasking, and introduced Face Unlock.

Jelly Bean (Android 4.1-4.3) followed, focusing on performance improvements and introducing features like Google Now, expandable notifications, and Project Butter, which significantly enhanced the platform's responsiveness.

KitKat, Lollipop, and Material Design (2013-2014):

Android 4.4, known as KitKat, brought further optimizations, focusing on lower memory requirements, improved battery life, and a more immersive user experience. This release also introduced the Google Now launcher and enhanced voice search capabilities.

The subsequent release, Lollipop (Android 5.0-5.1), introduced the iconic Material Design language, offering a vibrant and visually appealing UI. Lollipop also introduced significant under-the-hood changes, including ART (Android Runtime) as the default runtime environment, improving app performance.

Marshmallow, Nougat, and Oreo: Refinements and Features (2015-2017):

Marshmallow (Android 6.0) introduced granular app permissions, Doze mode for improved battery life, and Google Now on Tap for contextual information. Nougat (Android 7.0-7.1) built upon these enhancements, introducing split-screen multitasking, direct reply notifications, and the Vulkan API for better graphics performance.

Oreo (Android 8.0-8.1) brought further refinements, including picture-in-picture mode, notification channels, and Project Treble, which aimed to streamline the Android update process.

Android P to R: AI Integration and Privacy Focus (2018-2021):

With Android 9.0 (Pie) and subsequent versions, Google focused on integrating AI capabilities into the platform. Features like Adaptive Battery, App Actions, and Digital Wellbeing aimed to enhance user experiences by leveraging machine learning.

Android 10 (Q) introduced a system-wide dark mode, enhanced privacy controls, and improved gesture navigation. Android 11 and 12 continued building upon these foundations, emphasizing privacy and providing better support for foldable devices.

Conclusion:

The history of Android is a testament to the remarkable journey of a platform that started as a vision and grew into a global powerhouse. From humble beginnings to a dominant force in the mobile industry, Android has continually evolved, pushing technological boundaries and enabling developers to create innovative applications.

As developers, we must never forget the lessons of the past. By understanding Android's history, we gain valuable insights into the platform's evolution, which can inform our decisions and shape the future of mobile development. Let's appreciate the achievements, learn from the challenges, and continue pushing the boundaries of what Android can do.

Friday, 1 December 2017

HB Blog 149: Cross Platform Development.

In computing, cross-platform software (also multi-platform software or platform-independent software) is computer software that is implemented on multiple computing platforms. Cross-platform software may be divided into two types; one requires individual building or compilation for each platform that it supports, and the other one can be directly run on any platform without special preparation. Cross-platform programming is the practice of actively writing software that will work on more than one platform.
There are a number of tools which are available to help facilitate the process of cross-platform programming:
  1.     8th: A cross-platform development language, which utilizes Juce as its GUI layer. The platforms it currently supports are: Android, iOS, Windows, macOS, Linux and Raspberry Pi.
  2.     Anant Computing: A mobile application platform that works in all Indian languages, including their keyboards, which is also supports AppWallet and Native performance inside all operating systems.
  3.     Appcelerator: It helps in building native apps by deploying just a single JavaScript code base. It provides your web content in a native application, ensuring your code is not wrapped around a web container unlike few other such solutions.
  4.     AppearIQ: A framework that supports the workflow of app development and deployment in an enterprise environment. Natively developed containers present hardware features of the mobile devices or tablets through an API to HTML5 code thus facilitating the development of mobile apps that run on different platforms.
  5.     Cairo: A free software library used to provide a vector graphics-based, device-independent API. It is designed to provide primitives for 2-dimensional drawing across a number of different backends. Cairo is written in C and has bindings for many programming languages.
  6.     Cocos2d: An open source toolkit and game engine for developing 2D and simple 3D cross-platform games and applications.
  7.     Delphi: A cross platform IDE, which uses Pascal language for Development. Currently it supports Android, iOS, Windows, macOS.
  8.     Ecere SDK: A cross platform GUI & 2D/3D graphics toolkit and IDE, written in eC and with support for additional languages such as C and Python. Currently it supports Linux, FreeBSD, Windows, Android, macOS and the Web through Emscripten or Binaryen (WebAssembly)
  9.     Eclipse: An open source cross-platform development environment. Implemented in Java with a configurable architecture which supports many tools for software development. Add-ons are available for several languages, including Java and C++.
  10.     FLTK: Another open source cross platform toolkit, but more lightweight because it restricts itself to the GUI.
  11.     fpGUI: An open source widget toolkit that is completely implemented in Object Pascal. It currently supports Linux, Windows and a bit of Windows CE.
  12.     GeneXus: A Windows rapid software development solution for cross-platform application creation and deployment based on knowledge representation and supporting C#, COBOL, Java including Android and BlackBerry smart devices, Objective-C for Apple mobile devices, RPG, Ruby, Visual Basic, and Visual FoxPro.
  13.     GLBasic: A BASIC dialoect and compiler that generates C++ code. It includes cross compilers for many platforms and supports numerous platform (Windows, Mac, Linux, Android,iOS and some exotic handhelds).
  14.     GTK+: An open source widget toolkit for Unix-like systems with X11 and Microsoft Windows.
  15.     Haxe: An open source cross-platform language.
  16.     Juce: An application framework written in C++, used to write native software on numerous systems (Microsoft Windows, POSIX, macOS), with no change to the code.
  17.     Lazarus: A programming environment for the FreePascal Compiler. It supports the creation of self-standing graphical and console applications and runs on Linux, MacOSX, iOS, Android, WinCE, Windows and WEB.
  18.     Max/MSP: A visual programming language that encapsulates platform-independent code with a platform-specific runtime environment into applications for macOS and Windows.
  19.     MechDome: A cross-platform Android runtime. It allows unmodified Android apps to run natively on iOS and macOS
  20.     MonoCross: An open-source model-view-controller design pattern where the model and controller are shared cross-platform but the view is platform-specific.
  21.     Mono: An open-source cross-platform version of Microsoft .NET (a framework for applications and programming languages)
  22.     MoSync: An open-source SDK for mobile platform app development in the C++ family
  23.     Mozilla application framework: An open source platform for building macOS, Windows and Linux applications
  24.     OpenGL: A cross-platform 3D graphics library.
  25.     PhoneGap: It enables software programmers to build applications for mobile devices using CSS3, HTML5, and JavaScript instead of relying on platform-specific APIs like those in Android, iOS, or Windows Phone.
  26.     PureBasic: A proprietary cross-platform language and IDE for building macOS, Windows and Linux applications
  27.     Qt: An application framework and widget toolkit for Unix-like systems with X11, Microsoft Windows, macOS, and other systems—available under both open source and proprietary licenses.
  28.     Simple and Fast Multimedia Library: A multimedia C++ API that provides low and high level access to graphics, input, audio, etc.
  29.     Simple DirectMedia Layer: An open-source cross-platform multimedia library written in C that creates an abstraction over various platforms’ graphics, sound, and input APIs. It runs on many operating systems including Linux, Windows and macOS and is aimed at games and multimedia applications.
  30.     Smartface: A cross platform native app development tool to create mobile applications for Android and iOS, using WYSIWYG design editor with JavaScript code editor.
  31.     Tcl/Tk
  32.     Ultimate++: A C++ cross-platform rapid application development framework focused on programmers productivity. It includes a set of libraries (GUI, SQL, etc..), and an integrated development environment. It supports Windows and Unix-like OS-s. The U++ competes with popular scripting languages while preserving C/C++ runtime characteristics. It has its own integrated development environment, TheIDE, which features BLITZ-build technology to speedup C++ rebuilds up to 4 times.
  33.     Unity: Another cross-platform SDK which uses Unity Engine.
  34.     Unreal: A cross-platform SDK which uses Unreal Engine.
  35.     V-Play Engine: V-Play is a cross-platform development SDK based on the popular Qt framework. V-Play apps and games are created within Qt Creator.
  36.     WaveMaker: A Cross-platform low-code development tool to create responsive web and hybrid mobile (Android & iOS) applications.
  37.     WinDev: Integrated Development Environment for Windows, Linux, .Net and Java (also with support for Internet and Intranet)
  38.     wxWidgets: An open source widget toolkit that is also an application framework.[14] It runs on Unix-like systems with X11, Microsoft Windows and macOS. It permits applications written to use it to run on all of the systems that it supports, if the application does not use any operating system-specific programming in addition to it.
  39.     Xamrin: With a C#-shared codebase, developers can use Xamarin tools to write native Android, iOS, and Windows apps with native user interfaces and share code across multiple platforms, including Windows and macOS. 
  40.     Xojo: A RAD IDE developed by Xojo, Inc. that uses an object-oriented programming language to create desktop, web and iOS apps. Xojo makes native, compiled desktop apps for macOS, Windows, Linux and Raspberry Pi. It creates compiled web apps that can be run as standalone servers or through CGI. And it recently added the ability to create native iOS apps.

Tuesday, 15 August 2017

HB Blog 142: Android Configure Using Build Variants - Part 2.

Hello friends, Thanks for reading my previous post on HB Blog 141: Android Configure Build Variants - Part 1.
This post will show you how you can configure build variants to create different versions of your app from a single project, and how to properly manage your dependencies and signing configurations.
Build variants are the result of Gradle using a specific set of rules to combine settings, code, and resources configured in your build types and product flavors. Although you do not configure build variants directly, you do configure the build types and product flavors that form them. Each build variant represents a different version of your app that you can build. For example, you might want to build one version of your app that's free, with a limited set of content, and another paid version that includes more. You can also build different versions of your app that target different devices, based on API level or other device variations.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//build.gradle
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.harshalbenake.buildvariant"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }

    /**
     * The following sample specifies an applicationIdSuffix for the debug build type,
     * and configures a "jnidebug" build type that is initialized using settings from
     * the debug build type.
     */
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            applicationIdSuffix ".debug"
        }

        /**
         * The 'initWith' property allows you to copy configurations from other build types,
         * so you don't have to configure one from the beginning. You can then configure
         * just the settings you want to change. The following line initializes
         * 'jnidebug' using the debug build type, and changes only the
         * applicationIdSuffix and versionNameSuffix settings.
         */
        jnidebug {
            // This copies the debuggable attribute and debug signing configurations.
            initWith debug

            applicationIdSuffix ".jnidebug"
            jniDebuggable true
        }
    }

    // Specifies the flavor dimensions you want to use. The order in which you
    // list each dimension determines its priority, from highest to lowest,
    // when Gradle merges variant sources and configurations. You must assign
    // each product flavor you configure to one of the flavor dimensions.
    flavorDimensions "api", "mode"

    /**
     * The following code sample creates "demo" and "full" product flavors
     * which provide their own applicationIdSuffix and versionNameSuffix.
     * The following code sample uses the flavorDimensions property
     * to create a "mode" flavor dimension to group the "full" and "demo" product flavors,
     * and an "api" flavor dimension to group product flavor configurations based on API level
     */
    productFlavors {
        demo {
            applicationIdSuffix ".demo"
            versionNameSuffix "-demo"
            // Assigns this product flavor to the "mode" flavor dimension.
            dimension "mode"
            resValue "string", "app_name", "HB Demo"
        }
        full {
            applicationIdSuffix ".full"
            versionNameSuffix "-full"
            dimension "mode"
            resValue "string", "app_name", "HB Full"
        }

        // Configurations in the "api" product flavors override those in "mode"
        // flavors and the defaultConfig block. Gradle determines the priority
        // between flavor dimensions based on the order in which they appear next
        // to the flavorDimensions property above--the first dimension has a higher
        // priority than the second, and so on.
        minApi24 {
            dimension "api"
            minSdkVersion '24'
            // To ensure the target device receives the version of the app with
            // the highest compatible API level, assign version codes in increasing
            // value with API level. To learn more about assigning version codes to
            // support app updates and uploading to Google Play, read Multiple APK Support
            versionCode 30000 + android.defaultConfig.versionCode
            versionNameSuffix "-minApi24"
        }

        minApi23 {
            dimension "api"
            minSdkVersion '23'
            versionCode 20000  + android.defaultConfig.versionCode
            versionNameSuffix "-minApi23"
        }

        minApi21 {
            dimension "api"
            minSdkVersion '21'
            versionCode 10000 + android.defaultConfig.versionCode
            versionNameSuffix "-minApi21"
        }
}

    /**
     * Using the build configuration from the previous section as an example,
     * suppose you plan to support only API levels 23 and higher for the demo version of the app.
     * You can use the variantFilter block to filter out all build variant configurations that
     * combine the "minApi21" and "demo" product flavors.
     */
    variantFilter { variant ->
        def names = variant.flavors*.name
        // To check for a certain build type, use variant.buildType.name == "<buildType>"
        if (names.contains("minApi23") && names.contains("full")) {
            // Gradle ignores any variants that satisfy the conditions above.
            setIgnore(true)
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.3.1'
}

Tuesday, 1 August 2017

HB Blog 141: Android Configure Using Build Variants - Part 1.

The Android build system compiles app resources and source code, and packages them into an Android Application Package (APK), that you can test, deploy, sign, and distribute.  Android Studio uses Gradle, an advanced build toolkit, to automate and manage the build process, while allowing you to define flexible custom build configurations.
 The build process for a typical Android app module follows these general steps:
  1.     The compilers convert your source code into DEX (Dalvik Executable) files, which include the bytecode that runs on Android devices, and everything else into compiled resources.
  2.     The APK Packager combines the DEX files and compiled resources into a single APK. Before your app can be installed and deployed onto an Android device, however, the APK must be signed.
  3.     Before generating your final APK, the packager uses the zipalign tool to optimize your app to use less memory when running on a device.
At the end of the build process, you have either a debug APK or release APK of your app that you can use to deploy, test, or release to external users.

Gradle and the Android plugin help you configure the following aspects of your build:

 Build Types :-
    Build types define certain properties that Gradle uses when building and packaging your app, and are typically configured for different stages of your development lifecycle. For example, the debug build type enables debug options and signs the APK with the debug key, while the release build type may shrink, obfuscate, and sign your APK with a release key for distribution. You must define at least one build type in order to build your app—Android Studio creates the debug and release build types by default.

 Product Flavors :-
    Product flavors represent different versions of your app that you may release to users, such as free and paid versions of your app. You can customize product flavors to use different code and resources, while sharing and reusing the parts that are common to all versions of your app. Product flavors are optional and you must create them manually.

 Build Variants :-
    A build variant is a cross product of a build type and product flavor, and is the configuration Gradle uses to build your app. Using build variants, you can build the debug version of your product flavors during development, or signed release versions of your product flavors for distribution. Although you do not configure build variants directly, you do configure the build types and product flavors that form them. Creating additional build types or product flavors also creates additional build variants.

 Manifest Entries :-
    You can specify values for some properties of the manifest file in the build variant configuration. These build values override the existing values in the manifest file. This is useful if you want to generate multiple APKs for your modules where each of the apk files has a different application name, minimum SDK version, or target SDK version.

 Dependencies :-
    The build system manages project dependencies from your local filesystem and from remote repositories. This prevents you from having to manually search, download, and copy binary packages of your dependencies into your project directory.

 Signing :-
    The build system enables you to specify signing settings in the build configuration, and it can automatically sign your APKs during the build process. The build system signs the debug version with a default key and certificate using known credentials to avoid a password prompt at build time. The build system does not sign the release version unless you explicitly define a signing configuration for this build.
For more details, visit my post, HB Blog 120: How To Sign Your APKs Using Android Studio.

 ProGuard :-
    The build system enables you to specify a different ProGuard rules file for each build variant. The build system can run ProGuard to shrink and obfuscate your classes during the build process.
For more details, visit my post, HB Blog 139: ProGuard - Shrinks, Optimizes, And Obfuscates Your Code.

 Multiple APK Support :-
    The build system enables you to automatically build different APKs that each contain only the code and resources needed for a specific screen density or Application Binary Interface (ABI).

Custom Build Configurations :-

Creating custom build configurations requires you to make changes to one or more build configuration files, or build.gradle files. These plain text files use Domain Specific Language (DSL) to describe and manipulate the build logic using Groovy, which is a dynamic language for the Java Virtual Machine (JVM).

When starting a new project, Android Studio automatically creates some of these files for you, as shown in below image, and populates them based on sensible defaults.
 ......Continue, to read more on Build Variant gradle in my next post, Android Configure Using Build Variants - Part 2.

Saturday, 1 July 2017

HB Blog 139: ProGuard - Shrinks, Optimizes, And Obfuscates Your Code.

The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. The result is a smaller sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your application harder to reverse engineer, it is important that you use it when your application utilizes features that are sensitive to security like when you are Licensing Your Applications.

ProGuard is integrated into the Android build system, so you do not have to invoke it manually. ProGuard runs only when you build your application in release mode, so you do not have to deal with obfuscated code when you build your application in debug mode. Having ProGuard run is completely optional, but highly recommended.
1. Shrinking – detects and removes unused classes, fields, methods, and attributes.
2. Optimization – analyzes and optimizes the bytecode of the methods.
3. Obfuscation – renames the remaining classes, fields, and methods using short meaningless names.

How to Enable Proguard in Android Studio ?
  • In Android Studio project, the minifyEnabled  property in the build.gradle file enables and disables Proguard for release builds.
  • The minifyEnabled property is part of the buildTypes release block that controls the settings applied to release builds.
  • The getDefaultProguardFile(‘proguard-android.txt’) method obtains the default Proguard settings from the Android SDK tools/proguard folder.
  • Android Studio adds the proguard-rules.pro file at the root of the module, which helps to add custom Proguard rules.

Friday, 19 May 2017

HB Blog 136: Android Automation Testing Using Espresso Framework.

Android tests are based on JUnit, and you can run them either as local unit tests on the JVM or as instrumented tests on an Android device. This post provides an introduction to the concepts and tools for building Android tests.
When using Android Studio to write any of your tests, your test code must go into one of two different code directories (source sets). For each module in your project, Android Studio includes both source sets, corresponding to the following test types:
Local unit tests:-
Located at module-name/src/test/java/.
These tests run on the local JVM and do not have access to functional Android framework APIs.

Instrumented tests:-
Located at module-name/src/androidTest/java/.
These are all tests that must run on an Android hardware device or an Android emulator.
Instrumented tests are built into an APK that runs on the device alongside your app under test. The system runs your test APK and your app under tests in the same process, so your tests can invoke methods and modify fields in the app, and automate user interaction with your app.
        Building Instrumented Unit Tests: Build complex unit tests with Android dependencies that cannot be satisfied with mock objects.
        Automating User Interface Tests: Create tests to verify that the user interface behaves correctly for user interactions within a single app or for interactions across multiple apps.
        Testing App Component Integrations: Verify the behavior of components that users do not directly interact with, such as a Service or a Content Provider.
However, the local unit tests and instrumented tests described above are just terms that help distinguish the tests that run on your local JVM from the tests that run on the Android platform (on a hardware device or emulator). The real testing types that you should understand when building a complete test suite are described in the following table.

TypeSubtype Description
Unit tests
Local Unit Tests Unit tests that run locally on the Java Virtual Machine (JVM). Use these tests to minimize execution time when your tests have no Android framework dependencies or when you can mock the Android framework dependencies.
Instrumented unit tests Unit tests that run on an Android device or emulator. These tests have access to Instrumentation information, such as the Context of the app you are testing. Use these tests when your tests have Android dependencies that mock objects cannot satisfy.
Integration Tests
Components within your app only This type of test verifies that the target app behaves as expected when a user performs a specific action or enters a specific input in its activities. For example, it allows you to check that the target app returns the correct UI output in response to user interactions in the app’s activities. UI testing frameworks like Espresso allow you to programmatically simulate user actions and test complex intra-app user interactions.
Cross-app Components This type of test verifies the correct behavior of interactions between different user apps or between user apps and system apps. For example, you might want to test that your app behaves correctly when the user performs an action in the Android Settings menu. UI testing frameworks that support cross-app interactions, such as UI Automator, allow you to create tests for such scenarios.
JUnit
You should write your unit or integration test class as a JUnit test class. The framework offers a convenient way to perform common setup, teardown, and assertion operations in your test.
A basic JUnit test class is a Java class that contains one or more test methods. A test method begins with the @Test annotation and contains the code to exercise and verify a single functionality (that is, a logical unit) in the component that you want to test.
The following snippet shows an example JUnit integration test that uses the Espresso APIs to perform a click action on a UI element, then checks to see if an expected string is displayed.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityInstrumentationTest {

    @Rule
    public ActivityTestRule mActivityRule = new ActivityTestRule<>(
            MainActivity.class);

    @Test
    public void sayHello(){
        onView(withText("Say hello!")).perform(click());

        onView(withId(R.id.textView)).check(matches(withText("Hello, World!")));
    }
}

In your JUnit 4 test class, you can call out sections in your test code for special processing by using the following annotations:
  • @Before: Use this annotation to specify a block of code that contains test setup operations. The test class invokes this code block before each test. You can have multiple @Before methods but the order in which the test class calls these methods is not guaranteed.
  • @After: This annotation specifies a block of code that contains test tear-down operations. The test class calls this code block after every test method. You can define multiple @After operations in your test code. Use this annotation to release any resources from memory.
  • @Test: Use this annotation to mark a test method. A single test class can contain multiple test methods, each prefixed with this annotation.
  • @Rule: Rules allow you to flexibly add or redefine the behavior of each test method in a reusable way. In Android testing, use this annotation together with one of the test rule classes that the Android Testing Support Library provides, such as ActivityTestRule or ServiceTestRule.
  • @BeforeClass: Use this annotation to specify static methods for each test class to invoke only once. This testing step is useful for expensive operations such as connecting to a database.
  • @AfterClass: Use this annotation to specify static methods for the test class to invoke only after all tests in the class have run. This testing step is useful for releasing any resources allocated in the @BeforeClass block.
  • @Test(timeout=): Some annotations support the ability to pass in elements for which you can set values. For example, you can specify a timeout period for the test. If the test starts but does not complete within the given timeout period, it automatically fails. You must specify the timeout period in milliseconds, for example: @Test(timeout=5000).
Use the JUnit Assert class to verify the correctness of an object's state. The assert methods compare values you expect from a test to the actual results and throw an exception if the comparison fails. Assertion classes describes these methods in more detail.

Saturday, 1 April 2017

HB Blog 132: Does Your Phone Get Hang? Know Why...

Android phone sometimes gets hang. Does your phone also have same problem? Don't blame OEMs the original equipment manufacturers or Open Handset Alliance for these problems. At least, not completely because Android applications are more responsible for that.
Developers call it as memory leaks in technical terms. Now a days, lot of devices with unlimited memory are coming in the market. But, it is not the SD card memory that we are having scarcity. It is the heap size or the application size.

So what is the heap size?
Android is a full multitasking system so it’s possible to run multiple programs at the same time and obviously each one can’t use all of your device memory. For this reason there is a hard limit on your Android application’s heap size: if your application needs to allocate more memory and you have gone up to that heap size already, you are basically going to get a “out of memory error”.
Heap size limit is device dependent and it has changed a lot over the years, the first Android phone (the G1) has 16MB heap size limit.

Even if you do not plan on using all of this memory, you should use as little as possible to let other applications run without getting them killed. The more applications Android can keep in memory, the faster it will be for the user to switch between his apps. If these memory is allocated more by the application, your phone gets hang and we get a memory leaks issues.

There are many reasons why we face these kind of problems such as large bitmaps, resources, etc. But, most of time it is the context that are kept long-lived references. In Android, a Context is used for many operations but mostly to load and access resources. This is why all the widgets receive a Context parameter in their constructor. In a regular Android application, you usually have two kinds of Context, Activity and Application. It's usually the first one that the developer passes to classes and methods that need a Context. This means that views have a reference to the entire activity and therefore to anything your activity is holding onto, usually the entire View hierarchy and all its resources. Therefore, if you leak the Context ("leak" meaning you keep a reference to it thus preventing the GC from collecting it), you leak a lot of memory. Leaking an entire activity can be really easy if you're not careful.
When the screen orientation changes the system will, by default, destroy the current activity and create a new one while preserving its state. In doing so, Android will reload the application's UI from the resources.

Basically, we can avoid configuration changes by locking screen rotation. But, it is something that wont provide user experience. Such as watching movie in just portrait mode without landscape feature. So we can go for config change attribute in Android Manifest file as below snippet,


1
2
3
<activity android:name=".MyActivity"
    android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">


also, do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself), try using the context-application instead of a context-activity.
Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. And, many more ways to explore time to time while developing Android applications...

Wednesday, 1 February 2017

HB Blog 128: Android Jack And Jill Toolchain.

Jack is a new Android toolchain that compiles Java source into Android dex bytecode. It replaces the previous Android toolchain, which consists of multiple tools, such as javac, ProGuard, jarjar, and dx.
For information related to Android Build System visit post HB Blog 51: Android Build System - How Android Apk Is Built.

The Jack toolchain provides the following advantages:
  • Completely open source
    Available in AOSP; partners are welcome to contribute. 
  • Speeds compilation time
    Jack has specific supports to reduce compilation time: pre-dexing, incremental compilation and a Jack compilation server. 
  • Handles shrinking, obfuscation, repackaging and multidex
    Using a separate package such as ProGuard is no longer necessary.
Jack has its own .jack file format, which contains the pre-compiled dex code for the library, allowing for faster compilation (pre-dex).
The Jill tool translates the existing .jar libraries into the new library format, as shown below.
How to use Jack in Android build?
You don’t have to do anything differently to use Jack — just use your standard makefile commands to compile the tree or your project. Jack is the default Android build toolchain for M.
The first time Jack is used, it launches a local Jack compilation server on your computer:
  •     This server brings an intrinsic speedup, because it avoids launching a new host JRE JVM, loading Jack code, initializing Jack and warming up the JIT at each compilation. It also provides very good compilation times during small compilations (e.g. in incremental mode).
  •     The server is also a short-term solution to control the number of parallel Jack compilations, and so to avoid overloading your computer (memory or disk issue), because it limits the number of parallel compilations.
The Jack server shuts itself down after an idle time without any compilation. It uses two TCP ports on the localhost interface, and so is not available externally. All these parameters (number of parallel compilations, timeout, ports number, etc) can be modified by editing the $HOME/.jack file.

Jack and Jill are available in Build Tools version 21.1.1, and greater, via the SDK Manager. Complementary Gradle and Android Studio support is also already available in the Android 1.0.0+ Gradle plugin.'
Using Gradle, add the following to your module-level build config file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
android {
    ...
    buildToolsVersion '21.1.2'
    defaultConfig {
      // Enable the experimental Jack build tools.
       jackOptions {
         enabled true
       }
    }
    ...
}

Jack limitations:
  • The Jack server is mono-user by default, so can be only used by one user on a computer. If it is not the case, please, choose different port numbers for each user and adjust SERVER_NB_COMPILE accordingly. You can also disable the Jack server by setting SERVER=false in your $HOME/.jack.  
  •  CTS compilation is slow due to current vm-tests-tf integration. 
  •  Bytecode manipulation tools, like JaCoCo, are not supported. 

Tuesday, 1 November 2016

HB Blog 122: Android Tools For Analyzing RAM Usage.

Random-access memory (RAM) is a valuable resource in any software development environment, but it's even more valuable on a mobile operating system where physical memory is often constrained. Although both the Android Runtime (ART) and Dalvik virtual machine perform routine garbage collection, this does not mean you can ignore when and where your app allocates and releases memory. You still need to avoid introducing memory leaks, usually caused by holding onto object references in static member variables, and release any Reference objects at the appropriate time as defined by lifecycle callbacks.
Tools for analyzing RAM usage :-
Before you can fix the memory usage problems in your app, you first need to find them. Android Studio and the Android SDK include several tools for analyzing memory usage in your app,

  1. The Device Monitor has a Dalvik Debug Monitor Server (DDMS) tool that allows you to inspect memory allocation within your app process. You can use this information to understand how your app uses memory overall. For example, you can force a garbage collection event and then view the types of objects that remain in memory. You can use this information to identify operations or actions within your app that allocate or leave excessive amounts of objects in memory. 
  2. The Memory Monitor in Android Studio shows you how your app allocates memory over the course of a single session. The tool shows a graph of available and allocated Java memory over time, including garbage collection events. You can also initiate garbage collection events and take a snapshot of the Java heap while your app runs. The output from the Memory Monitor tool can help you identify points when your app experiences excessive garbage collection events, leading to app slowness.
  3. Garbage collection events also show up in the Traceview viewer. Traceview allows you to view trace log files as both a timeline and as a profile of what happened within a method. You can use this tool to determine what code was executing when a garbage collection event occurred. 
  4. The Allocation Tracker tool in Android Studio gives you a detailed look at how your app allocates memory. The Allocation Tracker records an app's memory allocations and lists all allocated objects within the profiling snapshot. You can use this tool to track down parts of your code that allocate too many objects.

Friday, 20 May 2016

HB Blog 111: NDK - Hello World Tutorial.

The Native Development Kit (NDK) is a set of tools that allow you to leverage C and C++ code in your Android apps. You can use it either to build from your own source code, or to take advantage of existing prebuilt libraries. However, it can be useful in cases in which you need to,
  • Squeeze extra performance out of a device for computationally intensive applications like games or physics simulations.
  • Reuse your own or other developers' C or C++ libraries.
In this post, I will explain how to setup NDK as well as run a Hello World program. It's pretty simple.
Basically, installing and setting up the NDK is similar to our normal Android SDK. 
To install and configure the NDK, follow these steps,
  1. Get and install the Android SDK.
  2. Download and extract the NDK, making sure to download the correct version for your development platform. You may place the unzipped directory anywhere on your local drive.
  3. Update your PATH environment variable with the location of the directory that contains the NDK.
  4. Set ndk.dir path in local.properties.
  5. Finally, run normal gradle sync to check it all files are installed clearly. 
There are 2 important files that plays a role in building our NDK application namely, Android.mk and Application.mk. They are actually the make files. Android.mk files defines properties specific to individual modules, or libraries. Whereas, Application.mk defines properties for all the modules that you use in your app.

Android.mk: - The Android.mk file resides in a subdirectory of your project's jni/ directory, and describes your sources and shared libraries to the build system. The syntax of the Android.mk allows you to group your sources into modules. A module is either a static library, a shared library, or a standalone executable. Below is a sample file,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Defines the root to all other relative paths
# The macro function my-dir, provided by the build system,
# specifies the path of the current directory (i.e. the
# directory containing the Android.mk file itself)
LOCAL_PATH := $(call my-dir)

# Clear all LOCAL_XXX variables with the exception of
# LOCAL_PATH (this is needed because all variables are global)
include $(CLEAR_VARS)

# List all of our C/C++ files to be compiled (header file
# dependencies are automatically computed)
LOCAL_SRC_FILES := HelloWorldC.c

# The name of our shared module (this name will be prepended
# by lib and postfixed by .so)
LOCAL_MODULE := helloworld

# We need to tell the linker about our use of the liblog.so
LOCAL_LDLIBS += -llog

# Collects all LOCAL_XXX variables since "include $(CLEAR_VARS)"
#  and determines what to build (in this case a shared library)
include $(BUILD_SHARED_LIBRARY)

Application.mk: - The Application.mk file is really a tiny GNU Makefile fragment that defines several variables for compilation. It usually resides under $PROJECT/jni/, where $PROJECT points to your application's project directory. Below is a sample file,
1
2
3
4
5
6
7
8
ANDROID_JPEG_NO_ASSEMBLER := true
APP_PLATFORM := android-9
APP_STL := gnustl_static #gnustl_shared
# ARMv7 is significanly faster due to the use of the hardware FPU
APP_ABI := armeabi armeabi-v7a x86 
APP_OPTIM := release
#APP_CPPFLAGS += -frtti
APP_BUILD_SCRIPT := Android.mk

Now, for creating our Hello World application we need to add this Android.mk and Application.mk make files in jni folder under main folder.We need C or C++ files to be added into the same jni folder. We need header and C main file as per our program functionality. I will show a sample code to display HelloWorld message from C program into java textview. Then, run "javah" utility for compiling this C files, which produces shared output(.so) files in libs folder based on CPUs and Architectures defined in our make files.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//HelloWorldC.h
1
2
3
4
5
6
7
8
//
// Created by harshal.benake on 27-04-2016.
//

#ifndef NDKHELLOWORLD_HELLOWORLDC_H
#define NDKHELLOWORLD_HELLOWORLDC_H
JNIEXPORT jstring JNICALL Java_com_example_harshalbenake_ndkhelloworld_MainActivity_getMessage(JNIEnv *, jobject);
#endif //NDKHELLOWORLD_HELLOWORLDC_H

//HelloWorldC.c
1
2
3
4
5
6
7
#include <jni.h>
#include <string.h>
#include "HelloWorldC.h"

JNIEXPORT jstring Java_com_example_harshalbenake_ndkhelloworld_MainActivity_getMessage(JNIEnv *env, jobject thisObj) {
   return (*env)->NewStringUTF(env, "Hello World from native code running successfully");
}

//MainActivity.java 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.example.harshalbenake.ndkhelloworld;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
    static {
        System.loadLibrary("helloworld"); // "helloworldjni.dll" in Windows, "libhelloworldjni.so" in Unixes
    }

    // A native method that returns a Java String to be displayed on the
    // TextView
    public native String getMessage();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Create a TextView.
        TextView textView = new TextView(this);
        // Retrieve the text from native method getMessage()
        textView.setText(getMessage());
        setContentView(textView);
    }
}

Tuesday, 1 March 2016

HB Blog 105: Overview Of Build Automation Tools.

Build automation is the process of automating the creation of a software build and the associated processes including: compiling computer source code into binary code, packaging binary code, and running automated tests.

Basically, a build automation was accomplished through makefiles. A makefile is a file that contains a set of directives used with the make build automation tool. Build automation tool are divided into 2 categories namely,
  1. Build automation utility: - Whose primary purpose is to generate build artifacts through activities like compiling and linking the source code.
  2. Build automation servers: - These are general web based tools that execute build automation utilities on a scheduled or triggered basis; a continuous integration server is a type of build automation server. 
There are various tools that automates the process of compiling computer source code into binary code based on creation of make file.
Make-based tools such as GNU make, make, mk, etc.
Non-Make-based tools such as Apache Ant, Apache Maven, Gradle, etc.
Earlier, we used to use Eclipse for our Android development where, we used dx, aapt, etc. tools for Apk creation. Now, have you ever wondered why the res folder is in the same directory as your src folder? This is where the build system enters the picture. The build system automatically takes all the source files (.java or .xml), then applies the appropriate tool (e.g. takes java class files and converts them to dex files), and groups all of them into one compressed file, our beloved APK. This build system uses some conventions: an example of one is to specify the directory containing the source files (in Eclipse it is \src folder) or resources files (in Eclipse it is \res folder). Now, in order to automate all these tasks, there has to be a script; you can write your own build system using shell scripting in linux or batch files syntax in windows.

Gradle is another build system that takes the best features from other build systems and combines them into one. It is improved based off of their shortcomings. It is a JVM based build system, what that means is that you can write your own script in Java, which Android Studio makes use of. One more thing about gradle is that it is a plugin based system. This means if you have your own programming language and you want to automate the task of building some package (output like a JAR for Java) from sources then you can write a complete plugin in Java or Groovy, and distribute it to rest of world.

Have a look on few code snippets,

//build.gradle 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.user.myapplication"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
}

Tuesday, 1 September 2015

HB Blog 91: Android Studio's Attractive Features.

Android Studio is the official IDE for Android application development, based on IntelliJ IDEA.
Android Studio offers:
    Flexible Gradle-based build system
    Build variants and multiple apk file generation
    Code templates to help you build common app features
    Rich layout editor with support for drag and drop theme editing
    lint tools to catch performance, usability, version compatibility, and other problems
    ProGuard and app-signing capabilities
    Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine
    And much more.


Most attractive features of android studio from a developer perspective are as follows:-

1)Android Studio allows you to work with layouts in both a Design View. Easily select and preview layout changes for different device images, display densities, UI modes, locales, and Android versions (multi-API version rendering).
From the Design View, you can drag and drop elements from the Palette to the Preview or Component Tree. The Text View allows you to directly edit the XML settings, while previewing the device display.
It updates preview of the layout xml while creating UI which provides read–eval–print loop (REPL) kind of features.

2)Android Studio provides a memory and CPU monitor view so you can more easily monitor your app's performance and memory usage to track CPU usage, find deallocated objects, locate memory leaks, and track the amount of memory the connected device is using. With your app running on a device or emulator, click the Android tab in the lower left corner of the runtime window to launch the Android runtime window. Click the Memory or CPU tab.
When you're monitoring memory usage in Android Studio you can, at the same time, initiate garbage collection and dump the Java heap to a heap snapshot in an Android-specific HPROF binary format file. The HPROF viewer displays classes, instances of each class, and a reference tree to help you track memory usage and find memory leaks.
Android Studio allows you to track memory allocation as it monitors memory use. Tracking memory allocation allows you to monitor where objects are being allocated when you perform certain actions. Knowing these allocations enables you to adjust the method calls related to those actions to optimize your app's performance and memory use.

3)Android Studio projects contain a top-level build file and a build file for each module. The build files are called build.gradle, and they are plain text files that use Groovy syntax to configure the build with the elements provided by the Android plugin for Gradle. In most cases, you only need to edit the build files at the module level. For example, the build file for the app module in the BuildSystemExample project looks like this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile project(":lib")
    compile 'com.android.support:appcompat-v7:19.0.1'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

 4)The build system can help you create different versions of the same application from a single project. This is useful when you have a demo version and a paid version of your app, or if you want to distribute multiple APKs for different device configurations on Google Play.
The build system uses product flavors to create different product versions of your app. Each product version of your app can have different features or device requirements. The build system also uses build types to apply different build and packaging settings to each product version. Each product flavor and build type combination forms a build variant. The build system generates a different APK for each build variant of your app.
To define two product flavors, edit the build file for the app module to add the following configuration:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
...
android {
    ...
    defaultConfig { ... }
    signingConfigs { ... }
    buildTypes { ... }
    productFlavors {
        demo {
            applicationId "com.buildsystemexample.app.demo"
            versionName "1.0-demo"
        }
        full {
            applicationId "com.buildsystemexample.app.full"
            versionName "1.0-full"
        }
    }
}
...
The product flavor definitions support the same properties as the defaultConfig element. The base configuration for all flavors is specified in defaultConfig, and each flavor overrides any default values. The build file above uses the applicationId property to assign a different package name to each flavor: since each flavor definition creates a different app, they each need a distinct package name.

5)With smart rendering, Android Studio displays links for quick fixes to rendering errors. For example, if you add a button to the layout without specifying the width and height attributes, Android Studio displays the rendering message Automatically add all missing attributes. Clicking the message adds the missing attributes to the layout.
While debugging, you can now right-click on bitmap variables in your app and invoke View Bitmap. This fetches the associated data from the debugged process and renders the bitmap in the debugger.
When referencing images and icons in your code, a preview of the image or icon appears (in actual size at different densities) in the code margin to help you verify the image or icon reference. Pressing F1 with the preview image or icon selected displays resource asset details, such as the dp settings.