Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Challenge: Notifications on Android Wear


notification. It should be unique across your application. If you post a second notification with this
same ID, it will replace the last notification you posted with that ID. This is how you would implement
a progress bar or other dynamic visuals.


And that is it. Run your app and turn polling on. You should eventually see a notification icon appear
in the status bar. In the notification tray you will see a notification indicating that new photo results are
available.


After you are satisfied that everything is working correctly, change your alarm constant to be
something more sensible. (Using one of AlarmManager’s predefined interval constants ensures that
your app will get inexact repeating alarm behavior on pre-KitKat devices.)


Listing 28.18  Changing to a sensible alarm constant (PollService.java)


public class PollService extends IntentService {
private static final String TAG = "PollService";


// Set interval to 1 minute
private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(1);
private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(15);


}


Challenge: Notifications on Android Wear


Since you used NotificationCompat and NotificationManagerCompat, your notifications will
automatically appear on an Android Wear device if the user has it paired with an Android device
running your app. Users who receive the notification on a Wear device can swipe left to be presented
with the option to open the app on the connected handheld device. Pressing Open on the Wear device
will issue the notification’s pending intent on the handheld device.


To test this, set up an Android Wear emulator and pair it with a handheld device running your app.
Details about how to do this can be found on developer.android.com.


For the More Curious: Service Details


We recommend using IntentService for most service tasks. If the IntentService pattern does
not suit your architecture for a particular app, you will need to understand more about services to
implement your own. Prepare for an infobomb, though – there are a lot of details and ins and outs to
using services.


What a service does (and does not do)


A service is an application component that provides lifecycle callbacks, just like an activity. Those
callbacks are even performed on the main UI thread for you, just like in an activity.


A service does not run any code on a background thread out of the box. This is the #1 reason we
recommend IntentService. Most nontrivial services will require a background thread of some kind,
and IntentService automatically manages the boilerplate code you need to accomplish that.

Free download pdf