Category: Android

Android applications are bundled and distributed as apk(s), aka Android application package.To make an APK file, a program for Android is first compiled, and then all of its parts are packaged into one file. An APK file contains all of that program’s code (such as .dex files), resources, assets, certificates, and manifest file. As is the case with many file formats, APK files can have any name needed, provided that the file name ends in “.apk”.

Apk Contents:

An APK file is an archive that usually contains the following files and directories:

  • META-INF directory:
    • MANIFEST.MF: the Manifest file
    • CERT.RSA: The certificate of the application.
    • CERT.SF: The list of resources and SHA-1 digest of the corresponding lines in the MANIFEST.MF file; for example:
 Signature-Version: 1.0
 Created-By: 1.0 (Android)
 SHA1-Digest-Manifest: wxqnEAI0UA5nO5QJ8CGMwjkGGWE=
 Name: res/layout/exchange_component_back_bottom.xml
 SHA1-Digest: eACjMjESj7Zkf0cBFTZ0nqWrt7w=
 Name: res/drawable-hdpi/icon.png
 SHA1-Digest: DGEqylP8W0n0iV/ZzBx3MW0WGCA=
  • lib: the directory containing the compiled code that is specific to a software layer of a processor, the directory is split into more directories within it:
    • armeabi: compiled code for all ARM based processors only
    • armeabi-v7a: compiled code for all ARMv7 and above based processors only
    • arm64-v8a: compiled code for all ARMv8 arm64 and above based processors only[7][8]
    • x86: compiled code for x86 processors only
    • x86_64: compiled code for x86 64 processors only
    • mips: compiled code for MIPS processors only
  • res: the directory containing resources not compiled into resources.arsc (see below).
  • assets: a directory containing applications assets, which can be retrieved by AssetManager.
  • AndroidManifest.xml: An additional Android manifest file, describing the name, version, access rights, referenced library files for the application. This file may be in Android binary XML that can be converted into human-readable plaintext XML with tools such as AXMLPrinter2, android-apktool, or Androguard.
  • classes.dex: The classes compiled in the dex file format understandable by the Dalvik virtual machine
  • resources.arsc: a file containing precompiled resources, such as binary XML for example.

Decompilation process:

Our prerequisite would be these 3 tools:

  • dex2jar: Used to convert the apk to jar file. Can be downloaded from here.

  • JD-GUI: Used to view the contents/source from the jar file decompiled in previous step. Details are here.

  • apktool: For reverse engineering the apk to extract files and folders. This can be used to extract the manifest individually and then reading from it. It is available here for download.

dex2jar and JD-GUI are used together. dex2jar converts apk to jar file and JD-GUI provides the editor to browse that jar file. To use dex2jar:

  1. Download dex2jar from here and extract it to a separate folder.
  2.  Execute the following command to decompile an apk:

    sh testapp.apk

  3. It might happen that terminal might show you a permissions error related to while executing step 2, if that happens then provide with appropriate permissions by executing:

    sudo chmod +x

  4. Post above steps, testapp.jar should be generated which can be opened and browsed via JD-GUI. This file contains all the decompiled code(.class files)


We are already able to browse the source code using dex2jar and JD-GUI, however, another important tool in the arsenal is apktool, which is a tool for reverse engineering 3rd party, closed, binary Android apps. It can decode resources to nearly original form and rebuild them after making some modifications. It also makes working with an app easier because of the project like file structure and automation of some repetitive tasks like building apk, etc. Apps/Apks. Decoding of an apk via apktool can be done by using following command:

apktool d test.apk

Repackaging as an apk can be done by:

apktool b test

JD-GUI, d2j and apktool is the essential tooling required to get an effective and deep insight into 3rd party apps which often exist as black boxes. As shown above, the usage is simple and pretty straight forward. I would request you to share your inputs and experiences in comments with these tools or any others that you might have explored for decoding Android or any other platform apps.


  • X items on the visible list means x items inflated/created means x times getView() gets called with convertView as null.
  • Items in recycler at this time: 0
  • User scrolls up.
  • One more time getView() gets called, 2 things happen.
  • getView() gets called with convertView as null. getView() inflates and returns the view that just became visible.
  • The view that just disappeared gets dumped in the recycler.
  • Total views : number of views on screen+1 in recycler.
  • User scrolls further, View recycling kicks in, convertView is no longer null.


Custom Android, Custom USB

I have been working with a custom Android device for sometime now. This is a decently powerful 2.3.4 device(It is not a phone). It has USB capabilities too, but for some arcane reasons the vendor does not want to support the USB accessory api and hence one has to rely on native linux to handle the USB drive. The vendor’s app runs as a System app and needs to have the RW access to the USB. 


We were easily able to map the USB to mnt/udisk by having a quick look at the vol.fstab, which showed:

dev_mount usb /mnt/udisk auto /devices/platform/ehci-omap.0/usb1/

Since auto-mount was already enabled so it was not much of a hassle and things looked Vanilla and easy. But, Alas, everything went well until the code responsible for R/W was deployed. The Java code simply refused to acknowledge that the USB was plugged in and had data in it. Other apps, eg: Eclipse File Explorer, And Explorer, shell(OK, let’s leave this one out as it has root privileges), were easily able to acknowledge the existence of the USB. Now, what could have gone wrong with one small piece of File R/W Java code. The permissions looked pretty much Ok(other apps were already accessing the drive).

Few hours and 3 cups of coffee later, we had an aha moment when we released that the app was running as a System App and not a normal one. Putting the theory to test we ran the app as a normal one i.e. we immediately updated the debug.keystore to use the default one plus the manifest and yes everything was sunny again.


Hmmm….The issue at hand was solved now and the Vendor has been notified about the glitch, but This makes us think about the Android Security mechanisms. There should be a way to make system apps access USB but I haven’t found the answer to that yet. Will update as soon as I stumble on something.

Android Preference Framework is among st the mostly widely used building blocks of Android. Almost every Android application makes use of the Preferences file in some way or the other and our app is no different.

Our app uses the Android Preferences to store some general keys like,

  • Hardware Make
  • Hardware Model
  • Software Version
  • Date
  • Time
  • Connection State

All the above mentioned values are being retrieved from a sensor and are stored by the App in the preferences, to be displayed to the User in a User Friendly Manner.  However, we ran into a weird problem which had its roots in the Android Preferences during one of our test-runs.

Superficially speaking about the problem, whenever the user tried to retrieve the above mentioned data from the Sensor, the process seemingly happened fine, but whenever the app was restarted after any such scenario, all of the previously stored data in the Preferences file was lost, i.e., the App behaved as a freshly installed app and being launched for the first time! We tried various lenses to view this problem, our most prominent lens(wild guess actually) being that somehow something was overwriting the preferences file to default settings. Another programmer also suggested that “Somehow the Preference object was being null“. We tried to be nice and please everybody by incorporating their hypothesis and applying the suggested fixes and ended up wasting like 2 hours over this so called conventional wisdom!

After blaming the Preference Framework for those 2 hours and interrogating the data associated with it, we could not extract anything meaningful out of it except the OnSharedPreferenceChangeListener. So we decided to find somebody else to blame for the mess being created and turned our attention to the Sensor framework(as the bug always popped out whenever the Sensor data was retrieved). After tracking the changes in the preferences via OnSharedPreferenceChangeListener, it became clear that the Sensor Framework was not only retrieving the data, but was also storing like 10 of those values in the Preferences in a rapid succession and the code doing this looked something like,

updatePreferences(key1, value1);

updatePreferences(key2, value2);


updatePreferences(key10, value10);

As soon as this code was commented, the app behaved normally :-).

This made us realize that it was not about Android Preferences but about the manner in which we were updating those and hence we derived a few cardinal rules about the same,

  • Shared Preferences are NOT designed for storing data which changes often and/or large amounts of data.
  • Shared Preferences are just a file – it has to be opened, parsed, updated and closed every time we do an update operation on it. Doing update operation in a rapid succession might just corrupt the file and restore it to default values which was our case exactly.
  • Do not access Shared Preferences from multiple threads.
  • ‘Conventional wisdom’ can be wrong.

Happy Coding!

Android ScrollView Trick

Recently I had a problem with one of my layouts, where I was trying to put a variable length content in a ScrollView. All I wanted was to keep the height of the ScrollView fixed, inspite of the length of the content. I was trying to avoid hardcoding the height parameter due to the obvious choice of multitude of the devices I wanted to cover with my layout(shown in figure below).
My initial attempts with the ScrollView(shown with a green highlight), were about messing with(a combination of) the height/width/fillViewPort parameters, but nothing helped. Since the content inside the ScrollView was getting rendered dynamically, the ScrollView used to extend and occupy more than the top-half of the screen and the price was payed by the controls contained in the bottom LinearLayout which just dissappeared. This was fixed by wrapping the bottom LinearLayout in a ScrollView(shown below) and weirdly, now the top ScrollView always rendered the dynamic content within the top half boundries, which was what I initially intended.

Genesis-1, Enjoying the View!

After uploading 2 casual gaming titles(Powered By And Engine: on the Android Market(Search: Lunar Monk), We at Lunar Monk have been digging into the internals of the Android Graphics and Gaming capabilities(And Engine is good for your basic first game, but native is better). Our adventure begins from Replica Island (, One of the early games written for Android by Chris Pruett, which is open-source ( too. A read only copy can be checked out using Cygwin by giving the following command on Cygwin Bash,

svn checkout replicaisland-read-only
 Just Make sure you have the svn package installed with Cygwin.
Our next step is building the Source, which is a bit of a daunting task due to this error: Conversion to Dalvik format failed with error 1. Let’s see how to eliminate this error.
First thing first, the source which is checked out is setup to be built on android 1.5 and as most of us know that there are not much of those android versions alive today, So we chose to build on android 4.0. But if we are configuring the project in Eclipse, then it is easy to spot that it fails to create, which is due to the 2 anim files  activity_fade_in.xml & activity_fade_out.xml. Both the files use a linear interpolater for animation which is internal to android. To fix this, we need to create another xml with name linear_interpolator.xml. The contents of this xml would be,

<?xml version=”1.0″ encoding=”utf-8″?>
<linearInterpolator xmlns:android=””/&gt;

Moving further we would be linking this xml to our activity_fade_in.xml & activity_fade_out.xml by changing the android:interpolator entry in these two files to, android:interpolator=”@anim/linear_interpolator”.Now cleaning the project and rebuilding it would result in successful compilation, but an attempt to install it on a device will result in the dreaded Conversion to Dalvik format failed with error 1. This is due to the fact because the compiler is confused due to the multiple entries/pointers to few classes being linked from different places in this project which is resulting in a path as well as name space conflict. To fix this, We need to first remove all the other jars included in Replica Island except the android.jar(Can be done by Right Click the Project -> Properties -> Java Build Path). Now we need to open the classpath file present in the project directory and replace its contents by,
<?xml version=”1.0″ encoding=”UTF-8″?>
<classpathentry kind=”src” path=”src”/>
<classpathentry kind=”src” path=”gen”/>
<classpathentry kind=”con” path=””/>
<classpathentry kind=”output” path=”bin”/>

Cleaning the project and rebuilding it now should fix the bug now.

However, If the dreaded error is seen again then this might be the cause(the fix is provided too):

Android, Life of a ListView

The Listview in android could need a little getting used to if you are a newbie. I first met the listview while looking to design a custom list of items, which exhibits a unique behaviour classified into 2 categories,

1. All of items in the list would have a radiobutton and would be uniquely selectable.

2. A specific set of items would have an edit button(along with the radiobutton) & the item title would become editable if the edit button is clicked.

All in all I wanted my layout to look like,


Above Image is a collection of those items which dos not have an edit button. Other set of that this list contains would look like,


On selecting a particular item and then pressing the button, user would be greeted with an EditText Dialog as shown below,


Let’s see step by step that how one should go about achieving this functionality

The primary requirement of the list in question is a listview. We can define a simple ListView in a listlayout.xml file,

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android=""

Now the listview contains several row items, so to accomplish this we would be needing a row template which would define the layout of each row item. This can be defined in a file listrowtemplate.xml(Both the xml files will go inside the layout folder),

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
	android:layout_width="fill_parent" android:layout_height="wrap_content"
	android:padding="5dip" android:orientation="horizontal"
	<RadioButton android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:id="@+id/btn_radio" />

	<TextView android:id="@+id/triggerLabel" android:layout_width="fill_parent"
		android:layout_height="wrap_content" style="@style/BodyTextBigGrey"
		android:padding="5dip" android:gravity="center_horizontal|center_vertical"
		android:textSize="20dip" android:layout_weight="1" />
	<Button android:id="@+id/buttonEdit" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:text="Edit"
		android:layout_gravity="right" />

Now,To take this further to the next level, One must know that a ListView exhibits an arcane property called as View Recycling i.e. The rows that are not getting displayed are recycled to save memory. Although sounding simple, this can sometimes become a bit dicey especially for custom lists(the one like ours) as we will need to maintain the state of our selected radio button if it undergoes the recycling process.

There can be numerous approaches to tackle this problem. We discuss one such approach here. We will need a model to main tain the current state of our rows & this is where the developer meets the Trigger class(Shakespere said, What’s in a Name?). The Trigger class is our model to maintain the state of various trigger rows added to our list. This is what the trigger class looks like,(Please mind that I’m posting the development code here and not the release one so one can always encounter a few trivial redundancies),

public class Trigger {

    private String triggerName;
    private boolean triggerStatus;
    protected TextView text;
    protected RadioButton radiobutton;
    protected Button button;

    public String getTriggerName() {
        return triggerName;
    public void setTriggerName(String triggerName) {
        this.triggerName = triggerName;
    public boolean getStatus() {
        return triggerStatus;
    public void setStatus(boolean triggerStatus) {
        this.triggerStatus = triggerStatus;

Now, Our ListView can maintain an ArrayList of these Triggers and we can also take care of the View Recycling process using the various getters and setters defined in our Trigger Class.
The bond between the ListView and its Data(Trigger items) is forged by something called as an Adapter. We would be needing a custom adapter class, to override its its getView method which has a signature like public View getView(final int position, View convertView, ViewGroup parent). Doing this would give us a fine control over the view recycling process because if a view has been recycled then the android system call the getView with convertView as null and this is how we would come to know that we need to reinstantiate that view and also restore it to its previous state i.e. as it was before recycling. Considering this, below is the implementation of our Trigger Adapter,

public class TriggerAdapter extends ArrayAdapter<Trigger> {

	private ArrayList<Trigger> items = null;
	private Context context = null;
	private String tracker = null;
	private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();

	public TriggerAdapter(Context context, int textViewResourceId,
			ArrayList<Trigger> items) {
		super(context, textViewResourceId, items);
		this.context = context;
		this.items = items;
		for (int i = 0; i < this.items.size(); i++) {
			itemChecked.add(i, false); // initializes all items value with false

public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
	LayoutInflater vi = (LayoutInflater) context
	v = vi.inflate(R.layout.listrowtemplate, null);
final Trigger trigger = items.get(position);
if (trigger != null) {
	trigger.text = (TextView) v.findViewById(;
	trigger.radiobutton = (RadioButton) v.findViewById(;
	trigger.button = (Button) v.findViewById(;
	if (trigger.text != null) {

	if (trigger.button != null) {
		if (position > 10) {
		} else {
	trigger.button.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
			final Trigger trigger = items.get(position);
			if (!trigger.getStatus()) {
			AlertDialog.Builder alert = new AlertDialog.Builder(
			// Set an EditText view to get user input
			final EditText input = new EditText(context);
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int whichButton) {
					String value = input.getText()
					// Do something with value!
					final Trigger trigger = items
					items.add(position, trigger);
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int whichButton) {
					// Canceled.
	if (trigger.radiobutton != null) {
		trigger.radiobutton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
		     for (int i = 0; i < items.size(); i++) {
			final Trigger trig = items.get(i);
			if (trig.getStatus()) {
			ListView list = (ListView) (((LinearLayout) v
			for (int j = 0; j < list.getChildCount(); j++) {
			LinearLayout l = (LinearLayout) list
			RadioButton rd = (RadioButton) l
			if (rd.isChecked()) {
				((RadioButton) v).setChecked(true);
				final Trigger trigger = items.get(position);
				items.add(position, trigger);
return v;


All in all, our list is now complete and we just need an activity with a button to display it(It actually depends on your choice how you want to display it), Mine is a simple activity with a button and on the click of the button the list is displayed,

On the click of the button, we actually create an AlertDialog and set the ListView as its content after populating it,

public class CustomListActivity extends Activity {

	private ArrayList<Trigger> mTriggers = null;
	private TriggerAdapter mAdapter = null;
	ListView list = null;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		((Button) findViewById(

	protected void onStart() {
		String[] trigger_name = getResources().getStringArray(R.array.triggers);
		mTriggers = new ArrayList<Trigger>();
		for (int i = 0; i < trigger_name.length; i++) {
			final Trigger trigger = new Trigger();
		list = (ListView) getLayoutInflater()
		.inflate(R.layout.listlayout, null);


	OnClickListener mClickListener = new OnClickListener() {
		public void onClick(final View view) {
			final AlertDialog.Builder builder = new AlertDialog.Builder(view
			mAdapter = new TriggerAdapter(CustomListActivity.this,
					R.layout.listrowtemplate, mTriggers);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
			final AlertDialog alert = builder.create();
			if (!alert.isShowing()) {;

So this was a bit about creating Custom Lists in android. Hope you enjoyed it.

If you have any questions/doubts/improvements, please feel free to post those.

A blob refers to a binary large object. A BLOB usually comes into picture with Sqlite, ususally it is some data(image, audio file) which needs to be stored in a database purely on need basis. Although it is not a very good approach to do this but some times it is just the requirement. So actually, I demonstrate here to store an icon image into the android sqlite as a BLOB(byte array) and then retrieve and show it on the screen.

    • Step 1 would be to convert the image into a byte array,


Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); byte[] bitmapdata = bos.toByteArray();

    • Step 2 would be to store this in the database,


SQLiteDatabase db=this.openOrCreateDatabase(“imagedatabase”, this.MODE_PRIVATE, null); db.execSQL(“CREATE TABLE IF NOT EXISTS imagetable (“ + “_id INTEGER PRIMARY KEY AUTOINCREMENT,” + “image BLOB” + “);”); ContentValues values = new ContentValues(); values.put(“image”, bitmapdata); long row_id=db.insert(“imagetable”, null, values);

    • Step 3 would be to retrieve and display it back on screen,


Cursor cursor = db.query(“imagetable”, new String[]{“image”}, null, null, null, null,null); System.out.println(“—–getcolumn count”+cursor.moveToFirst()); //get it as a ByteArray byte[] mybyte=cursor.getBlob(0); //the cursor is not needed anymore cursor.close(); //convert it back to an image ByteArrayInputStream imageStream = new ByteArrayInputStream(mybyte); Bitmap theImage = BitmapFactory.decodeStream(imageStream); ((ImageView)findViewById(;

A simple 3 step process!

Powerful Intentions 2

There are a few ways in which one can launch intents,

First lets see how you create a basic intent,

new Intent(context, helloactivity.class);

Above is an example of an explicit intent which does not require any intent filter to be present in the android manifest, as the target activity has already been specified as the second parameter.

Another way can be,

new Intent(Intent.ACTION_VIEW,uri);

The uri plays an important role here as described below,

  1. http: or https:, will display a link in the browser.
  2. ge0: used to perform google maps related stuff on appropriately supplied longitude and latitude
  3. tel: or voicemail: for telephony stuff

In our real world, our actions and expressions translate our intentions. Virtual world is no different than this, android java gives us developers the power to perform actions on the android system using intentions(really??), and here’s where the android jargon of, intents, intent filters and intent resolution finds a meaning. Whenever you have an intention, you launch an intent. You wanna launch an activity from another activity, go ahead use an explicit intent, make judicious use of, setClass method and android system will do it for you. You wanna launch a service, intents at your disposal. You wanna call John doe, use an intent. Its that simple. Whenever you have an intention, you launch an intent.

Any intent is composed of 2 essential parts,

  1. Action.
  2. Data.

Hence, intent has complete information about, any action to be performed on a given piece of data.

We shall delve more deeper into this just a bit later, but for now, let’s skim the surface a bit more,

Intents come in 2 specific flavors,

  1. Explicit–>Here you explicitly specify the action you want to perform using methods like,

setComponent(ComponentName) or setClass(Context, Class).

These methods allow you to specify components(activities, services,providers,receivers) or more specifically exact classes that are to be executed via launch of the intent.

2. Implicit–>This is where the intent-filters(now what are they??), specified in your android manifest come into play and a process called as Intent Resolution takes place which goes on till the android system finds a match for your intention.

An intent filter usually exists within an activity node within your android manifest and looks something like……..


<action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 The above mentioned Intent filter will exist inside an activity node in the android manifest........and its intention will be to
make that activity as primary activity and entry point when the user launches your application.