Showing posts with label Tools. Show all posts
Showing posts with label Tools. Show all posts

Sunday, 27 August 2023

Unveiling AES-256 Encryption: Safeguarding Data with Advanced Security.

 In the realm of modern cryptography, ensuring the security of sensitive data is paramount. Advanced Encryption Standard (AES) has emerged as one of the most widely used encryption algorithms, trusted by governments, corporations, and individuals alike. Among its variants, AES-256 stands out as the strongest and most robust encryption option. In this blog, we'll delve into the workings of the AES-256 algorithm, its significance, and how it maintains data confidentiality.

Understanding AES Encryption

AES, also known as Rijndael, was established as a U.S. federal government standard in 2001. It was designed to replace its predecessor, the Data Encryption Standard (DES), which was deemed inadequate against modern threats due to its relatively short key length and algorithmic vulnerabilities.

AES operates as a symmetric encryption algorithm, meaning it employs the same key for both encryption and decryption processes. However, the security lies in the complexity of the algorithm itself, making it practically impossible for unauthorized parties to deduce the original data from the encrypted version, even with knowledge of the algorithm.

AES Key Lengths

AES comes in three standard key lengths: 128 bits, 192 bits, and 256 bits. The numbers correspond to the length of the cryptographic key used in the algorithm. AES-256, the focus of this blog, utilizes a 256-bit key length, providing an immense number of possible key combinations. This large key space contributes significantly to the algorithm's security, as it becomes computationally infeasible to launch brute-force attacks.

AES-256 Encryption Process

Key Expansion: The initial 256-bit encryption key is expanded into a set of round keys. Each round key is used in subsequent rounds of the encryption process.

Initial Round: The data is divided into blocks, typically 128 bits each. In the initial round, each byte of the block is combined with the corresponding byte of the round key through a process called "AddRoundKey."

Main Rounds: The number of main rounds depends on the key length. For AES-256, there are 14 main rounds. Each main round consists of four operations: SubBytes, ShiftRows, MixColumns, and AddRoundKey. These operations introduce confusion and diffusion, making the relationship between the key and the ciphertext highly complex.

  • SubBytes: Non-linear substitution of each byte in the block using a predefined substitution table (S-box).
  • ShiftRows: Byte rows are shifted by varying offsets to introduce diffusion.
  • MixColumns: Columns are mixed through a mathematical transformation, enhancing the algorithm's security.
  • AddRoundKey: The round key is XORed with the block's state, adding a layer of confusion.

Final Round: The final round is similar to the main rounds but lacks the MixColumns operation.

Output: After the final round, the transformed block is the encrypted ciphertext, which can be transmitted or stored securely.

Security and Strengths

AES-256's strength lies in its combination of substitution, permutation, and mixing operations, making it highly resistant to cryptanalysis. The large key size and the multiple rounds of transformation contribute to its robustness against various attacks, including brute force, differential, and linear attacks. The security of AES-256 is also underpinned by its ability to effectively dissipate statistical patterns, ensuring that even small changes in input data result in significant changes in the ciphertext.

Decryption Process

The decryption process is essentially the reverse of encryption, involving the application of inverse operations to retrieve the original plaintext from the ciphertext. The same round keys used in encryption are applied in reverse order.

Conclusion

The AES-256 algorithm represents the pinnacle of data security through its robust encryption process and utilization of a 256-bit key length. Its widespread adoption in critical applications demonstrates its effectiveness against modern cryptographic threats. Understanding the complexities of AES-256 not only underscores the importance of data protection but also highlights the intricate beauty of cryptography in the digital age.

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.

Friday, 1 September 2017

HB Blog 143: Implementing Video Call using Sinch Android SDK.

Introduction

The Sinch SDK is a product that makes adding voice calling and/or instant messaging to mobile apps easy. It handles all the complexity of signalling and audio management while providing you the freedom to create a stunning user interface.
Refer the below link for complete sample code:-

Download Sample Code

First time setup

Below is a step-by-step guide on setting up the Sinch SDK for the first time.

Register an Application
1.    Register a Sinch Developer account at http://www.sinch.com/signup.
2.    Setup a new Application using the Dashboard where you can then obtain an Application Key and an Application Secret.

Download
The Sinch SDK can be downloaded at www.sinch.com/download/. It contains: the library aar, this user guide, reference documentation, and sample apps for calling and instant messaging.

Add the Sinch library
The Sinch SDK library is distributed in AAR format. To use it in your project choose File -> New -> New Module -> Import .JAR/.AAR Package option

Permissions
A minimum set of permissions are needed for the app to use the Sinch SDK. These are specified in the AndroidManifest.xml file. If the calling functionality will be used, all five permissions listed here are needed. However, if the calling functionality isn’t used, the last three (RECORD_AUDIO, MODIFY_AUDIO_SETTINGS and READ_PHONE_STATE) can be omitted.
1
2
3
4
5
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Note: By default, the Sinch SDK hangs up any Sinch call if the regular phone app has an active call. This functionality requires the permission READ_PHONE_STATE. However, if this default functionality isn’t wanted, turn it off by calling sinchClient.getCallClient().setRespectNativeCalls(false); and the permission READ_PHONE_STATE is not needed.

Sinch client

The SinchClient is the Sinch SDK entry point. It is used to configure the user’s and device’s capabilities, as well as to provide access to feature classes such as the CallClient, MessageClient and AudioController.

Create a SinchClient
1
2
3
4
5
6
7
8
// Instantiate a SinchClient using the SinchClientBuilder.
android.content.Context context = this.getApplicationContext();
SinchClient sinchClient = Sinch.getSinchClientBuilder().context(context)
.applicationKey("<application key>")
.applicationSecret("<application secret>")
.environmentHost("sandbox.sinch.com")
.userId("<user id>")
.build();
The Application Key and Application Secret are obtained from the Sinch Developer Dashboard. The User ID should uniquely identify the user on the particular device.
Note: All listener callbacks emitted from the Sinch SDK are invoked on the same thread that the call to SinchClientBuilder.build is made on. If the invoking thread is not the main-thread, it needs to have an associated Looper.

Start the Sinch client
Before starting the client, add a client listener
1
2
3
4
5
6
7
8
sinchClient.addSinchClientListener(new SinchClientListener() {
public void onClientStarted(SinchClient client) { }
public void onClientStopped(SinchClient client) { }
public void onClientFailed(SinchClient client, SinchError error) { }
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration registrationCallback) { }
public void onLogMessage(int level, String area, String message) { }
});
sinchClient.start();
Terminate the Sinch client
When the app is done using the SinchClient, it should be stopped. If the client is currently listening for incoming events, it needs to stop listening as well. After terminate is called, any object retrieved directly from the client object (that is, CallClient, MessageClient, and AudioController) is considered invalid.
Terminating the client:
1.    sinchClient.stopListeningOnActiveConnection();
2.    sinchClient.terminate();

Setting up a video call
Just like audio calls, video calls are placed through the CallClient and events are received using the CallClientListener. The call client is owned by the SinchClient and accessed using sinchClient.getCallClient(). Calling is not enabled by default. 

Showing the video streams
Once you have created a VideoCallListener and added it to a call, the onVideoTrackAdded() method will be called.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@Override
public void onVideoTrackAdded(Call call) {
// Get a reference to your SinchClient, in the samples this is done through the service interface:
VideoController vc = getSinchServiceInterface().getVideoController();
View myPreview = vc.getLocalView();
View remoteView = vc.getRemoteView();
// Add the views to your view hierarchy
}

After the call has ended, dont forget to remove the views from your view hierarchy again.
@Override
public void onCallEnded(Call call) {
// Remove Sinch video views from your view hierarchy
}
Pausing video stream
To pause the local video stream, use the pauseVideo() method on the call.
1.        // User pause the video stream
2.        call.pauseVideo();

Resuming video stream
To resume the local video stream, use the resumeVideo() method on the call.
1.       // User resumes the video stream
2.       call.resumeVideo();

Pausing video stream delegates
Once you have created a VideoCallListener and added it to a call, the onVideoTrackPaused() method will be called when the remote user pause the video stream.
1.       @Override
2.       public void onVideoTrackPaused(Call call) {
3.            // Implement what to be done when remote user pause video stream.
4.       }

Resuming video stream delegates
Once you have created a VideoCallListener and added it to a call, the onVideoTrackResumed() method will be called when the remote user resumes the video stream..
1.       @Override
2.       public void onVideoTrackResumed(Call call) {
3.            // Implement what to be done when remote user resumes video stream.
4.       }

Video content fitting and aspect ratio
How the remote video stream is fitted into a view can be controller by the setResizeBehaviour() method with possible arguments VideoScalingType.ASPECT_FIT, VideoScalingType.ASPECT_FILL and VideoScalingType.ASPECT_BALANCED. The local preview will always use VideoScalingType.ASPECT_FIT.

Switching capturing device
The capturing device can be switched using videoController.setCaptureDevicePosition(int facing) with possible values Camera.CameraInfo.CAMERA_FACING_FRONT and Camera.CameraInfo.CAMERA_FACING_BACK. Use videoController.toggleCaptureDevicePosition() to alternate the two.

Accessing video frames of the remote streams
The Sinch SDK can provide access to raw video frames via a callback function. This callback can be used to achieve rich functionality such as applying filters, adding stickers to the video frames, or saving the video frame as an image.
Your video frame handler needs to implement VideoFrameListener interface by implementing the onFrame() callback. Note that it is important to explicitly release the video frame by calling release().
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Example:
import com.sinch.android.rtc.video.VideoFrame;
import com.sinch.android.rtc.video.VideoFrameListener;
public class YourVideoFrameHandler implements VideoFrameListener {
public synchronized void onFrame(String callId, VideoFrame videoFrame) {
// Process videoFrame
videoFrame.release(); // Release videoFrame}}

Use setVideoFrameListener() to register your video frame handler as the callback to receive video frames.

Example:
YourVideoFrameHandler videoFrameHandler = new YourVideoFrameHandler();
VideoController vc = getSinchServiceInterface().getVideoController();
vc.setVideoFrameListener(videoFrameHandler);

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.

Monday, 1 May 2017

HB Blog 134: Improve Android Applications Performance.

Hey guys, I hope you liked my previous post on app performance HB Blog 132: Does Your Phone Get Hang? Know Why...  . I got few mails and suggestions for posting similar kind of posts. So, here is my one more post for optimize your app's performance in various ways to improve its responsiveness and battery efficiency.
Basically, user expects app to launch app faster as well as load UI without any glitches. App launch can take place in one of three states, each affecting how long it takes for your app to become visible to the user: cold start, warm start, and lukewarm start. In a cold start, your app starts from scratch. In the other states, the system needs to bring the app from the background to the foreground.
At the beginning of a state, the system has three tasks. These tasks are:
  1.     Loading and launching the app.
  2.     Displaying a blank starting window for the app immediately after launch.
  3.     Creating the app process.
As soon as the system creates the app process, the app process is responsible for the next stages. These stages are:
  1.     Creating the app object.
  2.     Launching the main thread.
  3.     Creating the main activity.
  4.     Inflating views.
  5.     Laying out the screen.
  6.     Performing the initial draw.
There are few safety measures we can take for improving application performance such as,
  1. Remove unused resource IDs:- We often declare and find a view using android:id="@+id/view". But, while actual calling it in java classes is not needed. Sometimes, we don't need any changes in that particular view so e can avoid creating this ids. Because, these ids are creating public static final constant variable which are taking up unneeded memory.
  2. Remove unused resource:- Many times we keep on changing UI/UX so in that case we might add up resource but won't remove it once they are unused, so try to remove unused resource it may be images, icons as well as layout and other XML.
  3. Minimize load on onCreate():-  When your application launches, the blank starting window remains on the screen until the system finishes drawing the app for the first time. At that point, the system process swaps out the starting window for your app, allowing the user to start interacting with the app. If you’ve overloaded Application.oncreate() in your own app, the system invokes the onCreate() method on your app object. Afterwards, the app spawns the main thread, also known as the UI thread, and tasks it with creating your main activity. From Android 4.4 (API level 19), logcat includes an output line containing a value called Displayed. This value represents the amount of time elapsed between launching the process and finishing drawing the corresponding activity on the screen. We understand that which activity is taking more time for loading and using tools like Method Tracer, Inline Tracer, etc. It also gives which methods are the culprits, most of the time it is onCreate() method. We need to optimize the load of these method by initializing resource that are needed at startup itself. We can also use methods such as reportFullyDrawn() to let the system know that your activity is finished with its lazy loading.
  4. Use injection framework like Dagger:- Whether the problem lies with unnecessary initialization or disk I/O, the solution calls for lazy-initializing objects: initializing only those objects that are immediately needed. We can have a dependency injection framework like Dagger that creates objects and dependencies are when they are injected for the first time.
  5. Use Asynchronous operation:- Using a background thread ("worker thread") removes strain from the main thread so it can focus on drawing the UI. In many cases, using AsyncTask provides a simple way to perform your work outside the main thread. AsyncTask automatically queues up all the execute() requests and performs them serially. This behavior is global to a particular process and means you don’t need to worry about creating your own thread pool. For background database operations we can use compile statements can be used. Have a look on similar post for more information, HB Blog 95: How To Compile SQL Statement Into Reusable Pre-compiled Statement Object???
  6. Avoid Virtualization:- If you don't need to access an object's fields, make your method static. Invocations will be about 15%-20% faster. It's also good practice, because you can tell from the method signature that calling the method can't alter the object's state. In native languages like C++ it's common practice to use getters (i = getCount()) instead of accessing the field directly (i = mCount). This is an excellent habit for C++ and is often practiced in other object oriented languages like C# and Java, because the compiler can usually inline the access, and if you need to restrict or debug field access you can add the code at any time. However, this is a bad idea on Android. Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.
  7. Use Enhanced For Loop Syntax:- The enhanced for loop (also sometimes known as "for-each" loop) can be used for collections that implement the Iterable interface and for arrays. There are several alternatives for iterating through an array:
     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
    static class Foo {
        int mSplat;
    }
    
    Foo[] mArray = ...
    
    public void zero() {
        int sum = 0;
        for (int i = 0; i < mArray.length; ++i) {
            sum += mArray[i].mSplat;
        }
    }
    
    public void one() {
        int sum = 0;
        Foo[] localArray = mArray;
        int len = localArray.length;
    
        for (int i = 0; i < len; ++i) {
            sum += localArray[i].mSplat;
        }
    }
    
    public void two() {
        int sum = 0;
        for (Foo a : mArray) {
            sum += a.mSplat;
        }
    }
    

    • zero() is slowest, because the JIT can't yet optimize away the cost of getting the array length once for every iteration through the loop. 
    • one() is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance benefit. 
    • two() is fastest for devices without a JIT, and indistinguishable from one() for devices with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language.
  8. Avoid complex Layout Hierarchies:- Layouts are a key part of Android applications that directly affect the user experience. If implemented poorly, your layout can lead to a memory hungry application with slow UIs. The Android SDK includes tools to help you identify problems in your layout performance, which will help to implement smooth scrolling interfaces with a minimum memory footprint. In the same way a complex web page can slow down load time, your layout hierarchy if too complex can also cause performance problems. If your application UI repeats certain layout constructs in multiple places, you can use the <include/> and <merge/> tags to embed another layout inside the current layout. Beyond simply including one layout component within another layout, you might want to make the included layout visible only when it's needed, sometime after the activity is running. Deferring loading resources is an important technique to use when you have complex views that your app might need in the future. You can implement this technique by defining a ViewStub for those complex and rarely used views.
  9. Use View Holder for listview:- Listview is one of the most important and very excessively used view. The key to a smoothly scrolling ListView is to keep the application’s main thread (the UI thread) free from heavy processing. Ensure you do any disk access, network access, or SQL access in a separate thread. The key to a smoothly scrolling ListView is to keep the application’s main thread (the UI thread) free from heavy processing. Ensure you do any disk access, network access, or SQL access in a separate thread. A way around repeated use of findViewById() is to use the "view holder" design pattern. A ViewHolder object stores each of the component views inside the tag field of the Layout, so you can immediately access them without the need to look them up repeatedly.
  10. Use 3rd party libraries carefully:- Actually, we use available libraries and resources for fasten our development time. It might not work as expected all the time and not all the design patterns and precautions are followed in these kinda libraries. So do explore complete libraries and then go for it. Android Arsenal is one of the interesting and helpful site which has categorized directory of libraries and tools for Android.

Wednesday, 1 March 2017

HB Blog 130: How To Scan Network With Nmap GUI.

Nmap is popular network scanner software that can actively probe a particular host or a network to infer in-depth information about them. Nmap can conduct host discovery, service detection, OS version identification, port scanning, network stack fingerprinting, etc. It will help you to discover hosts, protocols, open ports, services and its configuration and vulnerabilities on networks. While Nmap itself is a command-line utility, you can run it along with its GUI front-end called Zenmap. Network Mapper is an Android frontend for well known Nmap scanner. Frontend will help you to download and install Nmap as well as use it. Frontend supports all known Android architectures: arm, mips and x86. Nmap binaries are transferred using HTTPS by default.

In this tutorial, I will describe how to scan particular hosts or networks by using Nmap GUI.
The following screenshot shows the main window of Zenmap.
Scan Particular Host(s):-
Using Zenmap interface, you can probe a particular host. Fill in the IP address or host name of a destination host in "Target" field, and choose a desired scan profile from "Profile" drop down menu. Then, click on "Scan" button. For multiple hosts, you can specify them in a comma-separated list.
To check the detailed system information of a particular host after scanning, highlight a host in the left panel, and click on "Host Details" tab on the right panel.
To view available services and open ports of a host, click on "Ports / Hosts" tab.
Scan an Entire Network:-
Zenmap can also probe an entire local network by specifying an address prefix (e.g., 192.168.1.0/24) in the "Target" field.
Once network scanning is completed, you can view the topology of discovered hosts by clicking on "Topology" tab.
To view a list of available services, click on "Services" button on the left panel. You can see a list of all discovered services and their associated hosts, as shown below.

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, 15 November 2016

HB Blog 123: Android PowerPoint Viewer Tutorial.

Microsoft PowerPoint is a slide show presentation program currently developed by Microsoft, for use on both Microsoft and Apple Macintosh operating systems. PowerPoint, initially named "Presenter", was created by Forethought Inc.. Microsoft's version of PowerPoint was officially launched on May 22, 1990, as a part of the Microsoft Office suite. PowerPoint is useful for helping develop the slide-based presentation format and is currently one of the most commonly used slide-based presentation programs available. Microsoft has also released the PowerPoint mobile application for use on Apple and Android mobile operating systems.

PowerPoint presentations consist of a number of individual pages or "slides". The "slide" analogy is a reference to the slide projector. Slides may contain text, graphics, sound, movies, and other objects, which may be arranged freely.


Microsoft Office PowerPoint Viewer is a program used to run presentations on computers that do not have PowerPoint installed. Office PowerPoint Viewer (or in PowerPoint 2007 and later, a link to a viewer download) is added by default to the same disk or network location that contains one or more presentations packaged by using the Package for CD feature. PowerPoint Viewer is installed by default with a Microsoft Office 2003 installation for use with the Package for CD feature. The PowerPoint Viewer file is also available for download from the Microsoft Office Online Web site. Presentations password-protected for opening or modifying can be opened by PowerPoint Viewer. The Package for CD feature allows packaging any password-protected file or setting a new password for all packaged presentations. PowerPoint Viewer prompts for a password if the file is open password-protected. PowerPoint Viewer supports opening presentations created using PowerPoint 97 and later. In addition, it supports all file content except OLE objects and scripting. PowerPoint Viewer is currently only available for computers running on Microsoft Windows.

For Android mobile platform OS we have itsrts-pptviewer.jar library which acts as PowerPoint Viewer in the Android application,

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

activity_main.xml
1
2
3
4
5
6
7
8
9
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.itsrts.pptviewer.PPTViewer
        android:id="@+id/pptviewer"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

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
package com.example.harshalbenake.pptviewer;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import com.itsrts.pptviewer.PPTViewer;

public class MainActivity extends Activity {
    PPTViewer pptViewer;
    public static final String sdCardPath = Environment.getExternalStorageDirectory() + "/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pptViewer = (PPTViewer) findViewById(R.id.pptviewer);
        String path = sdCardPath +"Bestowal" + "/" + "PPT1.ppt";
        pptViewer.setNext_img(R.drawable.next).setPrev_img(R.drawable.prev)
                .setSettings_img(R.drawable.settings)
                .setZoomin_img(R.drawable.zoomin)
                .setZoomout_img(R.drawable.zoomout);
        pptViewer.loadPPT(this, path);
    }
}