BatteryStats and Battery Historian in Android

While developing android apps, it is our duty as developers to make sure that our apps are good citizens in terms of Battery consumption. Android framework has two main tools, BatteryStats and Battery Historian.  

First will explain BatteryStats and Battery Historian.

BatteryStats Batterystats is a tool to dump the battery data of the device to the development machine.

BatteryHistorian Battery Historian converts the report from batterystats to a HTML visualization that we can see in the browser.

Through these tools we can identify
where and how processes are drawing the battery & identifying tasks which can be deferred or even removed to improve the battery life.
Steps to install BatteryHistorian are,

1. Install docker software from here

2. Git clone the repo from here

3. Then run the command in terminal
docker run -d -p 9999:9999 bhaavan/battery-historian
4. Type in address bar of the browser,
5. Then run the command in terminal
adb bugreport > bugre…

Retrofit2 - Simple basic example

Here, I am going to explain the use of retrofit library in android. The tutorial has two api calls, one to get the model class and another to get the JSON as string. Another point is, according to the response we need, we have to pass the appropriate "ConverterFactory" to retrofit object.

The step by step tutorial

1. First add the dependencies in gradle,

compile 'com.squareup.retrofit2:retrofit:2.1.0' compile '' compile 'com.squareup.retrofit2:converter-gson:2.1.0' // for scalar converter factory compile 'com.squareup.retrofit2:converter-scalars:2.1.0'

2. Then create a ApiInterface class and add the api calls we need. The return type of the methods are "Call". One point to note in Call is execute() call is a synchronize call and enqueue() is an asynchronous call. In addition to that, BASE_URL should end with "/", else we will get an IllegalArgumentException

public interface APIInterf…

Implicit Intents

When using implicit intents, we have to check at least one app has to be there in the device to handle the intent. The way to check the sendIntent is,

Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage); sendIntent.setType(HTTP.PLAIN_TEXT_TYPE); // "text/plain" MIME type startActivity(sendIntent); if (sendIntent.resolveActivity(getPackageManager()) != null) { startActivity(sendIntent); }

Spiral Order Matrix Represention

Print the matrix in spiral order.


1. Declare four variables TOP, LEFT, RIGHT, BOTTOM
2. Then declare another variable called "dir"
3. first travel from Left to right ->, top to bottom , right to left <- amp="" bottom="" finally="" p="" to="" top="">4. increment the direction by one and change the four variables accordingly.
5. another point to note is as we travel through one node, remove the node. This is done by changing the four variables accordingly.
6. if the value of dir variable increases beyond 4, take the remainder of the direction by 4.

public class PrintSpiral { static int[][] A = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} }; public static void main(String[] args) { printSpiral(A, 4, 4); } private static void printSpiral(int[][] A, int row, int col) { int TOP= 0, LEFT= 0, BOTTOM= row-1, RIGHT= col-1; int dir = 0; while (TOP<=…

Swap two variables without a third variable

The code snippet to swap two variables a & b without a third variable,

private static void swap(int a, int b) { a = a + b; b = a - b; a = a - b; System.out.println("a: "+a+" b: "+b); }

Shortcut for System.out.println in intelliJ is cntrl+SPACE

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…