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(Bundle.java:1580)
E/Bundle  ( 1101):      at android.os.Bundle.(Bundle.java:82)
E/Bundle  ( 1101):      at android.os.Parcel.readBundle(Parcel.java:1381)
E/Bundle  ( 1101):      at android.os.Parcel.readBundle(Parcel.java:1366)
E/Bundle  ( 1101):      at android.content.Intent.readFromParcel(Intent.java:5479)
E/Bundle  ( 1101):      at android.content.Intent.(Intent.java:5453)
E/Bundle  ( 1101):      at android.content.Intent$1.createFromParcel(Intent.java:5444)
E/Bundle  ( 1101):      at android.content.Intent$1.createFromParcel(Intent.java:5446)
E/Bundle  ( 1101):      at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:132)
E/Bundle  ( 1101):      at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:1480)
E/Bundle  ( 1101):      at android.os.Binder.execTransact(Binder.java:288)
E/Bundle  ( 1101):      at dalvik.system.NativeStart.run(Native 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.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setClassName("com.example", "com.example.YourActivity");
YourApplication.this.startActivity(i);

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 {
                        this.ref.get().tracker.trackPageView(this.metric);
                        this.ref.get().tracker.dispatch();
                } 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

Adobe AIR 2.0 adds support for UDP

One of the things I’ve always wanted to see in Flash has been support for UDP sockets. As anyone whose tried to write a real-time networked game knows, TCP/IP is just too slow for the sorts of fast-twitch reactions used for first-person shooters, or anything real-time at all.

Apparently, Adobe AIR 2.0 has now added support for UDP, and this post by Jeff Winder shows how he’s added accelerometer support to RemoteDroid, and is using it to control an Adobe AIR application. Check out the video below:

Comments off

RemoteDroid has been open sourced

I’ve finally gotten around to open-sourcing RemoteDroid, and putting it up on Google code. You can get to it at:

http://code.google.com/p/remotedroid/

You’ll also always be able to find the latest .apk and server files there.

Part of my reason for open-sourcing it is that I’m just one person, with just one phone. Like or not, Android has already fragmented, and will probably fragment even more in the future, so support for every Android device out there will become increasingly difficult. That’s where open-source comes in.

I’m looking for contributors to help debug on platforms other than the G1. There are several issues that I simply can’t fix because I have no way of replicating them. Additionally, other people might think of features that I haven’t or haven’t had time to implement. If nothing else, people might be curious about how RemoteDroid works, and open-source is a great way of dealing with these issues.

If you’d like to help, feel free to email me at admin@remotedroid.net, or use the feedback form.

Comments off

Android browser caching

I just wanted to get this out there, Android’s browser caches like a madman. It completely ignores POST variables. This is particularly relevant when doing AJAX calls. You can’t simply add a timestamp to POST and expect the Android browser to give you new page data. You have to append to timestamp to the GET query string.

Pragma: no-cache, and all the other server-side headers also have no effect as far as I can tell.

It makes sense though. Since the browser’s on a mobile network, and since they want to minimize network traffic as much as possible, caching is going to be extremely aggressive.

Comments off

Maintaining an object through an orientation change

One of the head-scrathers about Android for me has been that when you open the keyboard on a device with a slide-out keyboard, the current activity is totally destroyed, then rebuilt again. I understand why it’s done, since all of a sudden, you’ve got a new resolution, and a new set of capabilities, but I never knew how to differentiate an orientation change from an Activity being destroyed because you’re going to a new Activity.

An example of this might be if you have a game thread, or some process going that you don’t want to have to shut down and restart just because you suddenly have to deal with a keyboard. The solution to this is Activity’s onRetainNonConfigurationInstance() method, as described here:

http://android-developers.blogspot.com/2009/02/faster-screen-orientation-change.html

Now you know!

Comments off

Slot Depo 5k yang Memberikan Fleksibilitas dalam Bermain

Banyak pemain kini mencari permainan yang memungkinkan mereka untuk bermain dengan deposit yang terjangkau. Slot Depo 5k menawarkan fleksibilitas ini, membuatnya menjadi pilihan yang populer di kalangan berbagai pemain. Dengan modal yang kecil, Anda dapat menikmati berbagai permainan dan peluang menang yang menarik.

Pentingnya memilih slot dengan RTP slot gacor tertinggi hari ini tidak bisa diabaikan jika pemain ingin mendapatkan hasil terbaik dalam permainan slot online. Dengan memantau RTP live, pemain bisa mengetahui slot mana yang memberikan peluang menang terbaik berdasarkan persentase pembayaran yang aktual. Slot gacor hari ini sering kali menawarkan RTP tinggi, memberikan pemain lebih banyak kesempatan untuk meraih kemenangan besar. RTP slot adalah alat penting bagi pemain yang ingin bermain dengan strategi dan meningkatkan potensi keuntungan mereka.

Related Links

Resource Links