Archive for Android

Android and https

I recently had to deal with using https with Apache’s http libraries. Not a simple task. If you just create a Uri with https in front of it, and your SSL certificate isn’t from a trusted authority, or if you’re using a self-signed certificate, you’re in for a world of hurt.

There’s a lot of solutions out there, and most of them involve trusting everyone, which isn’t so secure. The best solution I found is here:

Crazy Bob: Trusting SSL Certificates

It’s reasonably secure, but in order to use it, you’ll need the 1.6 JDK. You don’t need the Android SDK to create the needed keystore.


That method works if you’re only going to one domain. All other domains stop working with that method. A better method can be found at this Stack Overflow question:

The code here appends your KeyStores to Android’s list, which is a much better solution. You’ll still need the method for generating a keystore in the first link.

Comments off

Slow Android autocomplete in Eclipse Helios

Eclipse Helios has been slow for me for awhile, and it finally annoyed me enough to try to google a solution.

This guy found a good, relatively easy fix.

Basically, you’re just downloading the Android source, and adding it to your Android SDK directory. Hit the link for full details.

Comments off

Referencing drawables in HTML in Android’s WebView

Here’s another interesting Android quirk:

So let’s say you have a webview that you want to populate with HTML from an arbitrary source, and you want to use an image in the res/drawable directory. You could try webview.loadData(html, “text/html”, “UTF-8″), and within the HTML, use

<img src="file:///android_res/drawable/icon.png" />

or something, but that won’t work. Instead, this is what I had to do:

WebView webview = (WebView)this.findViewById(;
String html = "<html><head><title>TITLE!!!</title></head>";
html += "<body><h1>Image?</h1><img src="icon.png" /></body></html>";
webview.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "UTF-8", null);

So basically, for some reason, you absolutely have to use loadDataWithBaseURL.


This only seems to work with 2.2 (API level 8) and up.

Comments off

Basic authentication with HttpClient on Android using https and PUT

‘ve been beating my head against a wall for hours with this one. The examples I’d been using all returned HTTP 400 Bad Request, and Apache’s HttpClient is cryptic enough so that the reason for this wasn’t obvious. The reason for this response still isn’t obvious, but thanks to Kyle Lampe, I now have some code that actually works:

try {
    String data = "YOUR REQUEST BODY HERE";
    CredentialsProvider credProvider = new BasicCredentialsProvider();
    credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
        new UsernamePasswordCredentials("YOUR USER NAME HERE", "YOUR PASSWORD HERE"));
    DefaultHttpClient http = new DefaultHttpClient();
    HttpPut put = new HttpPut("YOUR HTTPS URL HERE");
    try {
        put.setEntity(new StringEntity(data, "UTF8"));
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "UnsupportedEncoding: ", e);
    put.addHeader("Content-type","SET CONTENT TYPE HERE IF YOU NEED TO");
    HttpResponse response = http.execute(put);
    Log.d(TAG, "This is what we get back:"+response.getStatusLine().toString()+", "+response.getEntity().toString());
} catch (ClientProtocolException e) {
    Log.d(TAG, "Client protocol exception", e);
} catch (IOException e) {
    Log.d(TAG, "IOException", e);

Comments off

Push notifications with Urban Airship on Android

So I’m testing out push notifications using Urban Airship’s system, and I’ve been ripping my hair out for the last day or so trying to get my app to respond to them. It turns out that the example code they have on their site doesn’t actually work. If you do everything exactly as they say, you’ll either get a ActivityNotFoundException when the BroadcastReceiver tries to start your activity, or you’ll get an ANR, and a log trace that looks like this:

E/Bundle  ( 1101): readBundle: bad magic number
E/Bundle  ( 1101): readBundle: trace = java.lang.RuntimeException
E/Bundle  ( 1101):      at android.os.Bundle.readFromParcelInner(
E/Bundle  ( 1101):      at android.os.Bundle.(
E/Bundle  ( 1101):      at android.os.Parcel.readBundle(
E/Bundle  ( 1101):      at android.os.Parcel.readBundle(
E/Bundle  ( 1101):      at android.content.Intent.readFromParcel(
E/Bundle  ( 1101):      at android.content.Intent.(
E/Bundle  ( 1101):      at android.content.Intent$1.createFromParcel(
E/Bundle  ( 1101):      at android.content.Intent$1.createFromParcel(
E/Bundle  ( 1101):      at
E/Bundle  ( 1101):      at
E/Bundle  ( 1101):      at android.os.Binder.execTransact(
E/Bundle  ( 1101):      at Method)

What’s happening is that you register a PushReceiver with the AirMail control panel app, which then creates and sends an intent to start your activity. The problem being, (I think) that the intent gets sent from the scope of the AirMail app, meaning it wont necessarily have access to your classes.

The way I finally got this to work is by using the setClassName(String, String) method of the intent to explicitly set the packagename and class name of the activity I wanted. Stick this in the onClick method of your PushReceiver:

Intent i = new Intent();
i.setClassName("com.example", "com.example.YourActivity");

Comments off

Google analytics drops metrics in Android if you send them too quickly

I just ran into this problem with the Google Analytics SDK for Android (v0.8). Basically, if you try to send too many pageviews too quickly, the tracker gets overwhelmed and forgets to track some of them.

My solution was just to space things out a bit with Timers and TimerTasks. I have a small wrapper around the analytics tracker, which has a timer, a static inner TimerTask class, and a long which is the soonest that a pageview should be sent. Whenever you want to send a pageview, you just call recordView, which looks like this:

public void recordView(String metric) {
        // The current time.
        long time = new Date().getTime();
        // We keep track of the next appropriate time to send a metric with sendTime. sendTime only gets updated
        // when we try to send something,
        if (this.sendTime > time) {
                time = this.sendTime;
        this.sendTimer.schedule(new TrackTask(this, metric), new Date(time));
        // I have sendInterval set to 2000, meaning pageviews are sent at a minimum, two seconds apart.
        this.sendTime = time + this.sendInterval;

Then, TrackTask looks like this:

protected static class TrackTask extends TimerTask {
        private WeakReference ref;
        private String metric;

        public TrackTask(Metrics met, String metric) {
                // WeakReference to avoid memory leaks.
                this.ref = new WeakReference(met);
                this.metric = metric;

        public void run() {
                // try catch block because our WeakReference has the possibility of being GCed out from under us.
                try {
                } catch (NullPointerException e) {

Comments off

Getting items in a ListView to show Alpha values

So I was trying to implement a ListView in Android the other day where the items would have varying levels of alpha transparency in the background. For some reason, every item’s background would go black whenever the ListView scrolled. (presumably for performance reasons.) Googling around yielded not much, but a co-worker had solved this problem in a previous app. Looking through the layout file, I saw that the android:cacheColorHint was set in his layout, but not mine. Adding it solved the problem.

Basically, just adding android:cacheColorHint=”#00000000″ to the ListView enabled transparency while scrolling.

Comments off

Android memory leaks

Since I’ve been banging my head against this for the last 12 hours, I thought I’d post a solution here, so other people might stumble across it and benefit.

I ran into two memory leaks in Android itself in WebView, and Typeface. Both are because of bugs in the OS, so if you’re encountering memory leaks, and all your code looks pretty watertight, (Meaning you never pass Activities as a Context to a View, and you use WeakReferences for static inner classes) you might be hitting one of these.

The first bug for WebView is described here.

The solution is just to call destroy() on your webview in the onDestroy() method of the containing activity, then set any references to that WebView to null, just in case. The app I’m working on is webview heavy, so this was causing some grief.

The second bug for Typeface is described here.

The issue was that I was creating a new Typeface from assets in the onCreate method of my activity. Every time I did this, it was allocating around 700k of memory, which then never got released. Big, big problems. The solution in this case is to initialize the typeface object in a static class (You can subclass Application and stick it there if you want, but be aware that you can’t call getAssets() before the first activity gets it’s onCreate method called.) and then use that one instance for any TextViews you may have.

The only way I managed to figure out what was causing the leaks was to go into adb shell, and then use dumpsys meminfo. That showed me a whole lot of bad.

Comments off

RemoteDroid controls robot remotely

Android + Arduino wireless from Guus Baggermans on Vimeo.

Well damn!

Comments off

RemoteDroid gets multitouch gestures

Thanks to Nicolas Frenay, RemoteDroid now has some cool multitouch gestures. You can now use two fingers to scroll, just like a macbook, as well as clicking the onscreen mouse buttons, and dragging using the touchpad, just like you always wanted. He’s using reflection to find out if your phone supports multitouch, which means that 1.6 devices aren’t left totally out in the cold, and I don’t have to worry about maintaining two different branches.

One note for Nexus One users, the Nexus One apparently has some pretty serious multitouch problems, making click and drag a bit wonky. I’d advise sticking to tap-to-click and hold for dragging items around.

Another change is that I’ve removed the trackball as mouse functionality. Now clicking the trackball acts as a CTRL key, and moving the trackball acts as a scrollwhell, making it more like ConnectBot, and making the user experience a little bit more consistent.

Lastly, I’ve added better support for the soft keyboard. All keys, except for the ones that don’t have direct analogues on your regular keyboard now work. (long-press keys still aren’t supported) In the future, because of differing physical keyboard layouts between devices, I’m going to try to get RemoteDroid to recognize which device you’re using, and change what it sends depending on that, but for now, at least the soft keyboard should be pretty consistent.

Comments off

Related Links

Resource Links