Long running background services in Android

We all know for service should be in running even when app is killed is through sticky service. Just override the onStartCommand() method and return START_STICKY. The code snippet is,

@Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY; }

Here one tricky situation could arise. If app is killed background service will restart, basically its onCreate() will get called and reinitialises every variables.  If your business logic doesn't want this situation, basically if the service is holding some state machine, then we may have to store the state details in a persistent way.

Another way we can ensure service doesn't restart even though app get killed is through notification. We should effectively call startForeground(id, Notification). We can do this in onCreate() of the service. The code snippet is,

@Override public void onCreate() { super.onCreate(); startForegro…

Messenger and Service in Android

Generally to get some result back from service or intent service we use Broadcast receiver. That is, service send a broadcast and in activity we register a receiver and and do some operations according to the result we got from service.

Here I am going to tell a alternate way to get the result back from service or intent service. It is a simple and effective way using Handler and Messenger.
Consider, we have to download a image from network

button.setOnclickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, DownloadService.class); intent.setData(Uri.parse("")); intent.putExtra(DownloadService.EXTRA_MESSENGER, new Messenger(handler)); startService(intent); } });
and our handler looks like this,

private Handler handler=new Handler() { @Override public void handleMessage(Message msg) { Toast.makeText(Mai…

Location Awareness service in Android


1. First we need to get the API key, go to terminal and type,

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
if JDK not installed, you will get a error like,
No Java runtime present, requesting install
A dialog appears click on more info and it will take directly to oracle JDK download site. Download JDK 9 and install and try again the above command. You will get the SAH1 and SAH256 fingerprints. 
2. Click on "Get key" button, then either select an existing project from google developer console or create a new project from this site

3. Now add the API_KEY to manifest file under <application> as <meta-data android:name="" android:value="@string/google_awareness_api_key"> </meta-data>
4.  Now we are ready to use Google awareness API in our app. Same like how we use fused location provider, create a googleApiClient and add the callbacks. …

How to get the list of Activities from BackStack

Two ways are there,

1. Using ADB Commands

Here is the complete list to get activities, services & processes 1. adb shell dumpsys activity activities -> displays list of activities in back stack 2. adb shell dumpsys activity process -> displays list process in back stack 3. adb shell dumpsys activity services -> displays list of services running in back stack
Another alternate way is through ActivityManager,
ActivityManager m = (ActivityManager) ctx.getSystemService( ctx.ACTIVITY_SERVICE ); List runningTaskInfoList = m.getRunningTasks(10); Iterator itr = runningTaskInfoList.iterator(); while(itr.hasNext()){ RunningTaskInfo runningTaskInfo = (RunningTaskInfo); int id =; CharSequence desc= runningTaskInfo.description; int numOfActivities = runningTaskInfo.numActivities; String topActivity = runningTaskInfo.topActivity.getShortClassName(); }

Event Bus using Green robot and Google guava

Event bus is a concept to pass events between components without knowing to whom the event is sending and who is going to receive the event. Components just push events to event bus and subscribers subscribe to the events will receive the event. Event enables decoupling of components. In android communication between components is cumbersome. This concept, event bus tries to solve the problem.

Green robot' event bus library is a latest in android which has a neat implementation of event bus. Here I am trying to explain the concept of event bus through a simple example. I have a receiver which will listens to events from Power manager. When ever device is charging or discharging, receiver component will push events to event bus. An activity which is subscribed to the event will receive the events and displayed in the screen.

The same example I tried with both libraries green robot and Google Guava.

You can find the green robot sample code in Git hub

The example for Guava imple…

Firebase cloud messaging - Step by step procedure

Implement FCM cloud messaging in Android app through Android studio is now simple. The step by step procedure is,

1. Create a new project in android studio

2. Click on tab Tools -> Firebase

3. Firebase assistant wiil open on right hand side of studio

4. A new dialog box appears to connect to firebase (This step creates a new project in the same name, here FCMMessaging in firebase console)

5. Then add FCM to app, through firebase assisstant, this step will add dependencies that is required for the app.

6. Now Create a service which should extend FirebaseInstanceIdService, which should override the method onTokenRefresh(), code snippet is as follows @Override public void onTokenRefresh() { super.onTokenRefresh(); // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.e("FirebaseInstanceID", "Refresh token: " + refreshedToken); }

7. Now create another service which should extend FirebaseMessagingSe…

Espresso test to check the max length in an editText

Espresso is a testing framework in android, which is used to test the UI elements in android like editText, textView, button, recyclerView and so on. One thing to note here is that Espresso synchronises all UI events. In case if we want to check network operations, we have to use IdlingResource, which I will explain in my upcoming tutorials.

Here I am verifying the mobile number (editText) can enter max 13 characters. I created a custom matcher, checkMaxLength which will check the max length of editText is 13 characters. We can pass any integer value as we wish. import android.os.Build; import android.os.SystemClock; import; import; import; import android.text.InputFilter; import android.view.View; import android.widget.TextView; import com.smartandroidians.myloci.activities.LoginActivity; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher…