Friday, March 4, 2011

Showing the current activity of the app from a notification in Android

Showing an error message from a long running background thread is easy on Windows (you can get the topmost window and show above that, or show a message somewhere in the main window). On Android it is recommended to alert the user with a Notification. Nonetheless, I tried to show a dialog from the background thread. But because AlertDialog.Builder.create gives an exception with the application context, even if it is called from the thread of getMainLooper, I've given up.

Here is the error notification I ended up with. The trick for showing the current activity is Intent.CATEGORY_LAUNCHER.
* Shows an error message as a notification.
private void showError(int notificationId, String text) {
// see the help for the Application class,
// for how to implement getInstance
Context ctx = MyApplication.getInstance();

Intent intent = new Intent();
intent.setComponent(new ComponentName(ctx, HomeActivity.class));

PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0);

Notification notification =
new Notification(R.drawable.launch_icon, text, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(ctx, text, null, pendingIntent);

NotificationManager nm = (NotificationManager)
nm.notify(notificationId, notification);