Code Painters The Art of Coding

17Jan/120

How to obtain GTalk Android ID

While googling around, I've stumbled upon an interesting project - Android Market API. This project is clearly a result of some Android reverse engineering work, still it's hosted on Google Code site. Funny, isn't it? Oh, by the way - the Android Market protocol uses Google's Protocol Buffers with HTTP as a transport layer.

Anyway, to play with the API you need a Google account (obviously), but also a sort of device identifier referred to as "Android ID". Funny enough, this is not the Android ID which can be obtained using android.provider.Settings.Secure class etc., the right ID can be obtained by "dialing" *#*#8255#*#* - look for Device ID, remove `android-` prefix.

But is there a way to retrieve this ID programmatically? It required a bit of hacking to reveal, but here's the recipe:

	private static final Uri URI = Uri
			.parse("content://com.google.android.gsf.gservices");
	private static final String ID_KEY = "android_id";

	String getAndroidId(Context ctx) {
		String[] params = { ID_KEY };
		Cursor c = ctx.getContentResolver()
				.query(URI, null, null, params, null);

		if (!c.moveToFirst() || c.getColumnCount() < 2)
			return null;

		try {
			return Long.toHexString(Long.parseLong(c.getString(1)));
		} catch (NumberFormatException e) {
			return null;
		}
	}

This code requires extra com.google.android.providers.gsf.permission.READ_GSERVICES permission, be sure to add the following line to your AndroidManifest.xml:

<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

That's it!