Friday, 26 August 2016

Firebase in Android - Getting started

Firebase is a cloud backend that enables you to quickly get synchronized data and use that for multi-user apps. This is important because nearly every mobile app these days requires authentication and real-time data updates.
Firebase is a gentle but very powerful introduction to storing and managing data. With just a few lines of code, you can read and write almost any data you could dream up from your own custom Firebase backend.
Furthermore, if your app needs any of the following features:
  • Online data storage
  • Real-time synchronization between many users
  • Authentication for Email/Password as well as OAuth providers
  • Data permissions and security
  • Offline access to data

then Firebase is the best solution now.

-Prerequisites:
  • A device running Android 2.3 (Gingerbread) or newer, and Google Play services 9.4.0 or newer
  • The Google Play services SDK from the Android SDK Manager
  • Android Studio 1.5 or higher
  • An Android Studio project and its package name

-Add Firebase to your app:

To add Firebase to your app you'll need a Firebase project and a Firebase configuration file for your app.
  • Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
  • Click Add Firebase to your Android app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  • When prompted, enter your app's package name. It's important to enter the package name your app is using; this can only be set when you add an app to your Firebase project.
  • At the end, you'll download a google-services.json file. You can download this file again at any time.
  • If you haven't done so already, copy this into your project's module folder, typically app/.
-Add the SDK:

If you would like to integrate the Firebase libraries into one of your own projects, you need to perform a few basic tasks to prepare your Android Studio project. You may have already done this as part of adding Firebase to your app.

First, add rules to your root-level build.gradle file, to include the google-services plugin:

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

Then, in your module Gradle file (usually the app/build.gradle), add the apply plugin line at the bottom of the file to enable the Gradle plugin:

apply plugin: 'com.android.application'

android {
  // ...
}

dependencies {
  // ...
  compile 'com.google.firebase:firebase-core:9.4.0'
}

// ADD THIS LINE AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

You should also add the dependencies for the Firebase SDKs you want to use. We recommend starting with com.google.firebase:firebase-core, which provides Firebase Analytics functionality.

-Add the Permissions:
The Firebase library requires the android.permission.INTERNET permission to operate. Your app will not work unless you add this permission to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />

-Setup Firebase on Android:
The Firebase library must be initialized once with an Android context. This must happen before any Firebase app reference is created or used. You can add the setup code to your Android Application file or Activity's onCreate method as follows:

@Override
public void onCreate() {
    super.onCreate();
    Firebase.setAndroidContext(this);
    .......
}

That's all. You are done with setting up of Firebase in your android app.
In the next blog we will going through other features of Firebase like
-Creating a user
-Authenticate a user
-Creating a database
-Writing values to database
-Reading database values.





Friday, 19 August 2016

India's 70th Independence Day Celebration

Independence Day is an annual observance celebrated every year on 15th of August. India’s Independence Day is a day of great significance for the people of India. At this day India got freedom from the British rule after long years of slavery. It has been declared as the National and Gazetted Holiday all across the India in order to independently commemorate the independence of country from British Empire on 15th of August in 1947.
Like other Indians on 15th august 2016 we also celebrated our 70th Independence Day but in a different way this time. We at HEADERLABS, celebrated our independence day with all our office-mates and also with our families. Some of us reached office (Headerlabs) at around 8.30 and then decorated our office with tri-colored balloons, small kites, Indian flags. Then at around 10 o'clock almost all people reached office. Not all but some people came along with their family members. Then at first we started our day of celebration by first introducing ourselves with everybody, everybody here were the family members for our other office-mates. Then we had some snacks, (Breadroll-yummy..!!), cold drinks and laddoo. After all this came the most funny and full of excitement part which was that we all started sharing our experiences, good or bad, funny or sad, at our office-Headerlabs. If i talk about myself personally, I was curiously waiting for my turn to come and share my experience from when I came here for the first time and till date. I was feeling very happy to memorize all those things at which we laughed and enjoyed together specially my pizza party..!! We heard the experiences from every person and also came to know about each other in a more better way and also some new things about everyone. We all indeed enjoyed a lot this Independence Day. Headerlabs for me is like my second home now. #STARTUPSWAG For this celebration and every other thing that has happened at Headerlabs I would like to thank all my colleagues and hope that we will be doing and maintaining this swag in our future also.
Some stills from our celebration:



Jai Hind Jai Bharat..!!

Friday, 12 August 2016

Resolving java.lang.OutOfMemoryError: GC overhead limit exceeded

Many a times while developing a project on android studio you get stuck with an irritating error that says
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define android/support/v7/app/activity
java.lang.OutOfMemoryError: GC overhead limit exceeded

One common indication of a memory leak is the java.lang.OutOfMemoryError exception. Usually, this error is thrown when there is insufficient space to allocate an object in the Java heap. In this case, The garbage collector cannot make space available to accommodate a new object, and the heap cannot be expanded further. Also, this error may be thrown when there is insufficient native memory to support the loading of a Java class. In a rare instance, a java.lang.OutOfMemoryError may be thrown when an excessive amount of time is being spent doing garbage collection and little memory is being freed.
When a java.lang.OutOfMemoryError exception is thrown, a stack trace is also printed.
The java.lang.OutOfMemoryError exception can also be thrown by native library code when a native allocation cannot be satisfied (for example, if swap space is low).
An early step to diagnose an OutOfMemoryError exception is to determine the cause of the exception. Was it thrown because the Java heap is full, or because the native heap is full? To help you find the cause, the text of the exception includes a detail message at the end, as shown in the following exceptions.

Exception in thread:-  thread_name: java.lang.OutOfMemoryError: GC Overhead limit exceeded
Cause: The detail message "GC overhead limit exceeded" indicates that the garbage collector is running all the time and Java program is making very slow progress. After a garbage collection, if the Java process is spending more than approximately 98% of its time doing garbage collection and if it is recovering less than 2% of the heap and has been doing so far the last 5 (compile time constant) consecutive garbage collections, then a java.lang.OutOfMemoryError is thrown. This exception is typically thrown because the amount of live data barely fits into the Java heap having little free space for new allocations.
Action: Increase the heap size. The java.lang.OutOfMemoryError exception for GC Overhead limit exceeded can be turned off with the command line flag -XX:-UseGCOverheadLimit.
The simple way to implement the solution to this error as follows:

1. In your build.gradle file add the following:

 defaultConfig {
        applicationId "yourpackage"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

        multiDexEnabled true
    }

2. add the following snippet also:

dexOptions {
        javaMaxHeapSize "4g"
    }
3. Your build.gradle file look something like this:

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.1' 
           ..........
      ..........
    defaultConfig {
        applicationId "yourpackage"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
.............
          ...........


4. Add the MultiDexApplication in your manifest as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourPackage">
    <application
        ...
        android:name="com.example.yourPackage.MultiDexApplication">
        ...
<activity
     ....
                 .........
</activity>
           ......
         ......
    </application>
</manifest>

5. Now clean & build your project and run.

That's all.. Enjoy and Code to make it better.
Reference: https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/memleaks002.html

Saturday, 6 August 2016

Tracking Uninstalls on Android

Is it possible to detect Android app UNINSTALL?
Well lets take an example, You launch an app, invest a lot of resources, spend like crazy on marketing, add all types of analytics to track users' every click and analyze it. One day, a user uninstalls your app. You don't know why he did it, you don't have any way to get back to him and ask for a feedback?
Users are the most important data/resource for an app to make its user database based upon which the particular application is considered to be popular. In such a case you would not like any of your user to stop using your application or if a user stops using your application there must be a way to hold him back to the app or at-least ask him the reason for stop using the app so that you can work on that point to improve.
For this, neither the operating system sends a trigger to your App at uninstall time nor it is available from the Appstore.
Solution to this problem is that there must be a way which can be used to see who is uninstalling your app and that way is the use of Push notification. Yes, use of push notification at an optimum frequency can help you track uninstalls. Once you know who has uninstalled, you can make use of your user data stored in your database to get in touch with that user.

Workaround:-
Send a push notification to all users at some frequency (say, daily). Send a special parameter in the body to determine that the push notification is only for tracking uninstalls. You shouldn't show anything on the device for such kind of notification, just process it silently.
Suppose, you send a push notification as follows:
{
"registration_ids": [
"csHKDjhH8n3Knr38nn8wsq88e2BnwujulIYhhHhHhiu89trerechbWQd3zh",
"fFN9eAHFqdQ:7VhMi DrndidjrxV25VM8ZglEsoio-mMFYRBHygCG7RkXRPA5M"
],
"data": {
"type": "track-uninstall"
}
}

The second id is of a device from which app has been removed. Let's check the response we get from GCM.
{
"multicast_id": 5559150596267635443,
"success": 1,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1438339632512460 %2930a2c7f9fd7ecd"
},
{
"error": "NotRegistered"
}
]
}

As you can clearly see, for the second id, it says that the device is not registered. You can find the user corresponding to the id from your database and try to get in touch with her/ him.
The next step would be to get a callback from the push notification service, find the user this id maps to in your database and let your server logic to handle that user now.

The complete flow of this procedure can be understood in a better way as follows:

A client app can be automatically unregistered after it is uninstalled. However, this process does not happen immediately. What happens in this scenario is:

  • The end user uninstalls the client app.
  • The app server sends a message to GCM connection server.
  • The GCM connection server sends the message to the GCM client on the device.
  • The GCM client on the device receives the message and detects that the client app has been uninstalled; the detection details depend on the platform on which the client app is running.
  • The GCM client on the device informs the GCM connection server that the client app was uninstalled.
  • The GCM connection server marks the registration token for deletion.
  • The app server sends a message to GCM.
  • The GCM returns a NotRegistered error message to the app server.
  • The app server should delete the registration token.

Note that it might take a while for the registration token to be completely removed from GCM. Thus it is possible that messages sent during step 7 above get a valid message ID as a response, even though the message will not be delivered to the client app. Eventually, the registration token will be removed and the server will get a NotRegistered error, without any further action being required from the app server. After this let your server logic to handle that user now to get hold of him back to the application.

References:
https://developers.google.com/cloud-messaging/registration#how-uninstalled-client-app-unregistration-works
https://leftshift.io/mobile-tracking-uninstalls-on-ios-and-android

Always code to make it better..!!