Android 101: Services, AsyncTasks and Notifications

With AsyncTasks you can perform operations in the background without freezing the main UI thread.

AsyncTasks

The AsyncTask is kind of like a thread, only easier to use as you don’t need to manipulate threads or handlers. It allows you to perform operations in the background without freezing the main UI thread, but you can still manipulate the UI from it.

You need to create a subclass of AsyncTask in order to use it. So you’ll need to override its methods, being the most relevant the doInBackground(Params...) and as its name indicates it will execute the work that needs to be done in the background.

In our application we needed to load the Buzz stream, so the best way to do this would be with an AsyncTask. This will free up the main thread of the application, meaning the user won’t see any freezing of the UI, or worse, a warning to shut down the app because its taking too long to respond. See more details on how to design your app for responsiveness.

Here’s an example from our app of the usage of AsyncTask:

class LoadBuzzes extends AsyncTask<Void, Void, ArrayList< Buzz>> {
    @Override
    protected void onPreExecute() {
        getHoneybuzzActivity().showProgress(); // show loading screen
    }

    @Override
    protected ArrayList<Buzz> doInBackground(Void... params) {
        try {
            // we’re caching the data so we’ll check if we need to update it from the server or just load from cache
            boolean refresh = Buzz.getUpdateChachedBuzzes(getActivity());
            Buzz.setUpdateChachedBuzzes(getActivity(), false);
            return Buzz.getBuzzes(getBuzz(), getActivity(), refresh);
        }
        catch (Exception e) {
            handleException(e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(ArrayList< Buzz> feed) {
        getHoneybuzzActivity().hideProgress(); // hide loading screen
        if (feed != null) {
            try {
                // load buzzes list onto the UI
            }
            catch(Exception e) {
                Logging.e("Error loading buzzes", e);
            }
        }
    }
}

And this is how you’d launch this task:

new LoadBuzzes().execute();

Services

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

To fetch the user stream from Google Buzz we used a Service that runs in the background and checks for updates. When updates are found, the service creates a new user notification. Here are the most important code bits from our sync service class.

private Timer mTimer = new Timer();
private NotificationManager mNM;

@Override
public void onCreate() {
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    // the time interval between checks is saved in the app’s preferences
    SharedPreferences prefs = HoneybuzzApplication.getSharedPreferences();
    int intervalMinutes = Integer.parseInt(prefs.getString(HoneybuzzApplication.PREFERENCE_INTERVAL, String.valueOf(30)));
    int intervalMiliseconds = intervalMinutes * 60 * 1000;
    mTimer.schedule(mUpdateTask, intervalMiliseconds, intervalMiliseconds);
}

private TimerTask mUpdateTask = new TimerTask() {
    @Override
    public void run() {
        try {
            String lastUpdated = com.quasibit.honeybuzz.Buzz.getLastUpdated(getApplicationContext());
            String serverUpdate = com.quasibit.honeybuzz.Buzz.getServerUpdated(HoneybuzzApplication.buzz, getApplicationContext());

            // check if the last update to the server is the same as the last update available in cache
            if (!lastUpdated.equals(serverUpdate)) {
                Buzz.getBuzzes(HoneybuzzApplication.buzz, getApplicationContext(), true);

                // after the updates are loaded the user gets a notification
                showNotification();
            }
        }
        catch(Exception e) {
            Logging.e(e);
        }
    }
};

Here’s a nice article with the comparison between AsyncTask, Service, Thread and IntentService.

Notifications

A Notification is a message that will show up in the system’s status bar warning the user of something he should know about. Its implementation is very simple.

In the case of our app we’re notifying the user whenever we find updates in the user’s Buzz stream. Here’s how we launch our notification:

private NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

private void showNotification() {
    String msg = getApplicationContext().getString(R.string.notif_buzzupdates);
    Notification notification = new Notification(R.drawable.ic_launcher_honeybuzz, msg, System.currentTimeMillis());
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, HoneybuzzListActivity.class), 0);
    notification.setLatestEventInfo(this, getApplicationContext().getString(R.string.app_name), msg, contentIntent);
    mNM.notify(NOTIFICATION, notification);
}

Optionally you can add a ticker-text message, an alert sound, vibration and/or flashing LED to your notification.

Dércia Silva
Posted by Dércia Silva on December 7, 2011

Related articles