Android: Getting Started with Push

Urban Airship supports push notifications for Android devices via Google’s GCM (Google Cloud Messaging for Android) service.

This document explains how to get started sending notifications to your Android apps, both from the Google side and from the Urban Airship side.

Note

Urban Airship has been supporting push notifications longer than any commercial provider. Prior to the release of GCM, we provided client code and a cloud-based push service known as Helium, and we also provided push transport via Google’s predecessor to GCM, C2DM (Android Cloud to Device Messaging Framework).

For more information on support for legacy and/or deprecated push systems, please visit our Reference section. Also, have a look at this GCM FAQ.

Production vs Development Apps in Urban Airship

Begin by creating both a development and production version of your app, and test GCM functionality using the development app. All new apps use GCM by default. Apps pre-existing prior to UA GCM support currently require assistance from support. Please email support@urbanairship.com if you need assistance upgrading to GCM.

Google Setup

Google Cloud Messaging (GCM) is the transport method that Urban Airship supports for Android notifications.

If you are using a legacy transport method such as C2DM or Helium, please consult the Android Legacy Reference guide in order to update to GCM.

Get your API Key from Google

In order to configure your Urban Airship application for GCM, you must first obtain an API key from Google.

The steps are:

  1. Go to the Google Developers Console

  2. Create a project:

    ../_images/gcm-create-proj.png
  3. Enable GCM by selecting APIs & auth and turning the Google Cloud Messaging for Android toggle to ON.

    ../_images/google-api-console.png
  4. Generate an API Key.

    Urban Airship takes care of API Access authorization for you, so you do not need to create an OAuth 2.0 client ID.

    1. Select APIs & auth > Credentials.

    2. Under Public API access, click “Create new key”.

    3. In the Create a new key dialog, click “Server key”.

    4. Do not specify any IP addresses in the form, and click “Create”.

      ../_images/google-apis-console-server-key.png
    5. Copy your key for server apps.

      ../_images/google-apis-console-key.png

For more detailed instructions, we recommend reading the: GCM Getting Started guide from Google.

Setting up GCM support for your app

While you will not need in-depth knowledge of Google’s GCM platform in order to use the GCM transport option in Push, we recommend you review Google’s documentation before continuing, even if you have prior experience with C2DM, the previous incarnation of this service. GCM is similar to C2DM, although several setup details, including the authorization mechanism, have changed.

Before you can use GCM:

  1. Enable GCM for your sender account and obtain an API key and project number from Google.
  2. Open up your application in your Urban Airship web application (go.urbanairship.com).
  3. Follow the instructions for Configuring Your Services.
  4. Open your airshipconfig.properties file and add the following line, changing “Your Google API Project Number” to the project number that you created in Step 1. Note that this is distinct from the API key.
  5. Make sure you set developmentAppKey, developmentAppSecret, productionAppKey, and productionAppSecret.
  6. For rich push, you must set richPushEnabled to true.

airshipconfig.properties

gcmSender = Your Google API Project Number (allows multiple senders separated by commas)
transport = gcm
developmentAppKey = Your Development App Key
developmentAppSecret = Your Development App Secret
productionAppKey = Your Production App Key
productionAppSecret = Your Production App Secret
inProduction = false
richPushEnabled = true

From here, the configuration steps for Push will be identical for both transport layers. In the next section, we’ll take a look at setting up your AndroidManifest.xml file with the necessary receivers, services and permissions to start receiving push notifications.

Urban Airship Setup

Add the Library JAR to your Project

First, download the current client library jar from our resources page. This zip file contains the library JAR file, as well as Eclipse sample projects with the JAR file already included.

If you are using Eclipse to develop your project, add the JAR to the libs folder in your project directory.

Otherwise, if you’re using a different IDE, just add a reference to the urbanairship-lib-<version>.jarfile in your classpath, and ensure that it is bundled in your final application.

Modify the AndroidManifest.xml

AndroidManifest.xml modifications are required to use the Urban Airship Library.

Note

Replace any PACKAGE_NAME with the package name of your application. Entries that need further modification will have a comment “MODIFICATION REQUIRED”

Add the following permissions under the manifest tag:

<!-- Required for the Urban Airship library -->
<permission android:name="PACKAGE_NAME.permission.UA_DATA" android:protectionLevel="signature" />
<uses-permission android:name="PACKAGE_NAME.permission.UA_DATA" />

<!-- Required for Push -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>

<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />

<!-- This app has permission to register with GCM and receive message -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="PACKAGE_NAME.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="PACKAGE_NAME.permission.C2D_MESSAGE" />


<!-- Required only for location -->
<!-- Use ACCESS_COARSE_LOCATION if GPS access is not necessary -->
<!-- uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!--  OPTIONAL - This permission is only necessary if your app has multiple processes -->
<!--  <uses-permission android:name="android.permission.BROADCAST_STICKY" /> -->

Add the following services, provider, receivers, and activies under the application tag:

<!-- Required for the library -->
<provider android:name="com.urbanairship.UrbanAirshipProvider"
          android:authorities="PACKAGE_NAME.urbanairship.provider"
          android:permission="PACKAGE_NAME.permission.UA_DATA"
          android:exported="true"
          android:multiprocess="true" />

<!-- Required for Push -->
<service android:name="com.urbanairship.push.PushService"/>
<receiver android:name="com.urbanairship.CoreReceiver" />
<receiver android:name="com.urbanairship.push.GCMPushReceiver" android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

        <category android:name="PACKAGE_NAME" />
    </intent-filter>

    <!--  Required for detecting when the application is upgraded so it can request a new GCM ID -->
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_REPLACED" />
        <data android:scheme="package"/>
    </intent-filter>
</receiver>

<!-- Required for analytics -->
<service android:name="com.urbanairship.analytics.EventService"/>

<!-- Required for Rich Push -->
<service android:name="com.urbanairship.richpush.RichPushUpdateService"/>

<!-- Required for Actions -->
<activity android:name="com.urbanairship.actions.ActionActivity"/>
<service android:name="com.urbanairship.actions.ActionService"/>

<!-- Required for Landing Page Action -->
<activity
    android:name="com.urbanairship.actions.LandingPageActivity"
    android:parentActivityName="PACKAGE_NAME.MainActivity"
    android:exported="false">

    <!-- MODIFICATION REQUIRED set or remove the parent activity -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="PACKAGE_NAME.MainActivity" />

    <intent-filter>
        <action android:name="com.urbanairship.actions.SHOW_LANDING_PAGE_INTENT_ACTION"/>
        <data android:scheme="http" />
        <data android:scheme="https" />
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

Complete samples of the AndroidManifest.xml can be found in the Rich Push Sample and in the Push Sample. Please note that you cannot copy and paste the sample’s manifest verbatim. In particular, anywhere within the examples that you see the package name com.urbanairship.push.sample or com.urbanairship.richpush.sample, it must be replaced with your app’s fully qualified package name, including the intent filter categories for GCMPushReceiver, your custom intent receiver, and the C2D_MESSAGE permissions at the bottom of the example file. This is especially important when using GCM, as without proper permissions settings, your app will not receive registration responses from Google, and this will prevent your APID from being registered with Urban Airship.

Enabling Push Notifications

Enabling or disabling push notifications is a preference often best left up to the user, so by default, push is disabled in the client library. For testing purposes, enabling push at startup simply requires a few extra lines of code to your main application class.

The Urban Airship client library automatically starts push upon takeOff, so for basic support, the amount of setup required is next to zero. Here is a simple example:

Application.java

public class MyApplication extends Application {

     @Override
     public void onCreate(){
          UAirship.takeOff(this, options);
          PushManager.enablePush();
     }
}

In the code block above, we’ve added a call to PushManager.enablePush which persists the preference and registers the app for Push with Urban Airship. The APID is your application’s unique push identifier, and is required in order to target a specific device when sending a push notification. Don’t worry if this value initially comes back as null on your app’s first run (or after clearing the application data), as the APID will be created and persisted during registration.

The options are read from the airshipconfig.properties file, but it is also possible to specify these in code:

Application.java

// Configure your application
//
// This can be done in code as illustrated here,
// or you can add these settings to a properties file
// called airshipconfig.properties
// and place it in your "assets" folder
AirshipConfigOptions options = AirshipConfigOptions.loadDefaultOptions(this);
options.developmentAppKey = "Your development app key";
options.productionAppKey = "Your production app key";
options.inProduction = false; //determines which app key to use

// Take off initializes the services
UAirship.takeOff(this, options);

Handling Push Events

The Urban Airship library will automatically create and display any incoming notifications and it will send out a broadcast when a notification is received and again when it is opened. In order to trigger behavior from one of those events, such as launching the application when the user clicks it, create a broadcast receiver and register it with the UAirship after takeoff. Please read the Custom Handling of Push Events section for more information.

Example BroadcastReceiver that launches the application when a push is opened

This example checks if an action is defined in the push that may have already launched an activity before launching. See Android Actions for more information.

public class IntentReceiver extends BroadcastReceiver {
    // A set of actions that launch activities when a push is opened. Update
    // with any custom actions that also start activities when a push is opened.
    private static String[] ACTIVITY_ACTIONS = new String[] {
        DeepLinkAction.DEFAULT_REGISTRY_NAME,
        OpenExternalUrlAction.DEFAULT_REGISTRY_NAME,
        LandingPageAction.DEFAULT_REGISTRY_NAME
    };

    @Override
    public void onReceive(Context context, Intent intent) {

        if (PushManager.ACTION_PUSH_RECEIVED.equals(intent.getAction())) {
          // Push received
        } else if (PushManager.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {

            // Push opened

            // Only launch the main activity if the payload does not contain any
            // actions that might have already opened an activity
            if (!ActionUtils.containsRegisteredActions(intent.getExtras(), ACTIVITY_ACTIONS)) {
                Intent launch = new Intent(Intent.ACTION_MAIN);
                launch.setClass(context, MainActivity.class);
                launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(launch);
            }
        }
    }
}

Add the receiver to the manifest:

<receiver android:name="com.urbanairship.push.sample.IntentReceiver" />

Register the receiver in your application’s onCreate method after takeOff:

PushManager.shared().setIntentReceiver(IntentReceiver.class);

Retrieving your APID

The APID is a unique identifier that ties together an application/device pair on android. You can use this ID to target pushes to specific devices using the Urban Airship API. Once an APID is created, it will persist the application until it is either reinstalled, or its internal data is cleared.

The easiest way to get the APID on your test install is to print it out on the system console. This just requires adding a couple of extra lines to your application’s onCreate method:

String apid = PushManager.shared().getAPID();
Logger.info("My Application onCreate - App APID: " + apid);

Once you see the APID in your application’s console log, copy it down and save it for later – we’ll be using this string to send our first test push.

Configure Service With Urban Airship

In the UA web application, navigate to Settings then click Services to set up your application with GCM:

../_images/db-edit.png ../_images/configure-GCM.png

Add your GCM API Key from Google and your package here:

../_images/app_create_with_GCM.png

For more detail on configuring your apps as well as using the Urban Airship web application, check out the Dashboard User Guide.

Apple, StoreKit and iPhone are trademarks of Apple, Inc. Maponics Neighborhood Boundaries © Maponics 2012. DMA® is a registered service mark of The Nielsen Company. Used under License.