Thursday, August 2, 2012

How to determine if your application runs in debug...

Sometimes there are actions your Android application should perform while it runs in release, but not in debug, and vice verse.

The issue is that Android methods of checking whether the application is debuggable or not, are not reliable, and there are three of them...

This is highly frustrating.

The best solution I've found, which served me well, is to determine in runtime whether the apk which runs the application is signed with a debug certificate or not. I've tested this on tens of phones ranging from version 2.1 - 4.0.4.

Here is the code sample:

PackageManager pm = context.getPackageManager();
Signature sig = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(sig.toByteArray()));
String dn = cert.getIssuerDN().getName();
boolean debuggable=dn.contains(myDebugCertificateName);

On most development environment the default debug certificate name is:
myDebugCertificateName = "Android Debug"

The problem I noticed people having is that they don't even understand this is what they really need... they just solve it in the build, and add a flag during CI to the manifest and later extract the value at runtime, I find it ridicules!