Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

動手做一個能收推送的 Android 應用:Urban Airship Helium 篇

編輯:關於 Android 程式設計

Urban Airship 的 Helium 是自家維護的推送通道,設定比 GCM 單純,很適合當作第一次接推送服務的練習。以下從建專案一路做到收到通知。

步驟一、建立專案

建立一個 Android 應用。這裡有個硬性要求:App 的 package 名稱必須與你在 Urban Airship 後台建立的 application 完全一致,否則永遠收不到訊息。

步驟二、加入 SDK

把 urbanairship-lib-2.0.1.jar 放進 libs 目錄並加入 classpath。

步驟三、設定 AndroidManifest.xml

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="urbanairship.client"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />

    <application
        android:name="urbanairship.client.MyApplication"
        android:enabled="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="com.urbanairship.CoreReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.ACTION_SHUTDOWN" />
            </intent-filter>
        </receiver>

        <service android:name="com.urbanairship.push.PushService"
            android:label="Push Notification Service"
            android:process=":com.urbanairship.process" />
        <service android:name="com.urbanairship.push.PushWorkerService"
            android:label="Push Notification Worker Service"
            android:process=":com.urbanairship.process" />
        <service android:name="com.urbanairship.analytics.EventService"
            android:label="Event Service"
            android:process=":com.urbanairship.process" />

        <service android:name="com.urbanairship.push.PushService" />
        <receiver android:name="urbanairship.client.IntentReceiver" />

        <provider
            android:name="com.urbanairship.UrbanAirshipProvider"
            android:authorities="urbanairship.client.urbanairship.provider"
            android:exported="false"
            android:multiprocess="true" />
    </application>

</manifest>

步驟四、建立 airshipconfig.properties

在 assets 目錄下新增這個檔案,填入後台提供的金鑰:

developmentAppKey = Your Development App Key
developmentAppSecret = Your Development App Secret
productionAppKey = Your Production App Key
productionAppSecret = Your Production App Secret

# transport 可為 "gcm" 或 "helium"
transport = helium

# gcmSender = GCM sender ID(Google API project ID,僅 GCM 模式需要)
gcmSender =

inProduction = false
iapEnabled = false

# 2 = VERBOSE; 3 = DEBUG; 4 = INFO; 5 = WARN; 6 = ERROR; 7 = ASSERT
developmentLogLevel = 3
productionLogLevel = 6

原文範例把 App Key 與 App Secret 填成了同一個值,實作時務必分辨清楚:Key 是識別,Secret 是憑證,兩者不可互換。另外 inProduction = false 決定走哪組金鑰,上正式環境前記得改回 true。

步驟五、補字串資源

<resources>
    <string name="app_name">urbanairship-client</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="enable_push">Enable Push</string>
    <string name="notification_subject">Subject</string>
    <string name="notification_message">Message</string>
</resources>

步驟六、寫兩個佈局

主畫面放一個 CheckBox 作為推送開關(此時 IDE 可能因為 Java 檔還沒建立而報紅,先忽略即可):

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

    <CheckBox
        android:id="@+id/enable_push"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="31dp"
        android:text="@string/enable_push" />

</RelativeLayout>

再來是自訂的通知樣式 notification.xml,讓通知長得像你的 App:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView android:id="@+id/icon"
        android:contentDescription=""
        android:layout_width="24dip"
        android:layout_height="24dip" />

    <TextView android:id="@+id/subject"
        android:text="@string/notification_subject"
        android:layout_alignTop="@+id/icon"
        android:layout_toRightOf="@+id/icon"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:maxLines="1" />

    <TextView android:id="@+id/message"
        android:textSize="14dip"
        android:textColor="#FF000000"
        android:text="@string/notification_message"
        android:maxLines="1"
        android:layout_marginTop="3dip"
        android:layout_height="wrap_content"
        android:layout_below="@+id/subject"
        android:layout_width="wrap_content" />

</RelativeLayout>

步驟七、Java 程式碼

7.1 MainActivity:推送開關與 APID

APID(Airship Push ID)是裝置的推送識別碼,後台推播時要用到它,因此先把它印到 log。

public class MainActivity extends Activity {

    private static final String logTag = MainActivity.class.getName();
    private CheckBox enablePush;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        enablePush = (CheckBox) this.findViewById(R.id.enable_push);
        enablePush.setEnabled(true);
        enablePush.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (enablePush.isChecked()) {
                    PushManager.enablePush();
                    PushPreferences pref = PushManager.shared().getPreferences();
                    Log.i(logTag, "APID: " + pref.getPushId());
                } else {
                    PushManager.disablePush();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

7.2 IntentReceiver:接收推送事件

這個廣播接收器負責把 SDK 的四類事件分流處理:收到訊息、使用者點擊通知、註冊完成、以及 GCM 訊息被刪除。

public class IntentReceiver extends BroadcastReceiver {

    private static final String logTag = IntentReceiver.class.getName();

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(logTag, "Received intent: " + intent.toString());
        String action = intent.getAction();

        if (action.equals(PushManager.ACTION_PUSH_RECEIVED)) {
            int id = intent.getIntExtra(PushManager.EXTRA_NOTIFICATION_ID, 0);
            Log.i(logTag, "收到推送,內容:" + intent.getStringExtra(PushManager.EXTRA_ALERT)
                    + " [NotificationID=" + id + "]");
            logPushExtras(intent);

        } else if (action.equals(PushManager.ACTION_NOTIFICATION_OPENED)) {
            Log.i(logTag, "使用者點了通知:" + intent.getStringExtra(PushManager.EXTRA_ALERT));
            logPushExtras(intent);

            Intent launch = new Intent(Intent.ACTION_MAIN);
            launch.setClass(UAirship.shared().getApplicationContext(), MainActivity.class);
            launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            UAirship.shared().getApplicationContext().startActivity(launch);

        } else if (action.equals(PushManager.ACTION_REGISTRATION_FINISHED)) {
            Log.i(logTag, "註冊完成。APID:" + intent.getStringExtra(PushManager.EXTRA_APID)
                    + ",有效:" + intent.getBooleanExtra(PushManager.EXTRA_REGISTRATION_VALID, false));

        } else if (action.equals(PushManager.ACTION_GCM_DELETED_MESSAGES)) {
            Log.i(logTag, "GCM 已刪除 "
                    + intent.getStringExtra(PushManager.EXTRA_GCM_TOTAL_DELETED) + " 則訊息。");
        }
    }

    private void logPushExtras(Intent intent) {
        Set<String> keys = intent.getExtras().keySet();
        for (String key : keys) {
            Log.i(logTag, "推送額外欄位:[" + key + " : " + intent.getStringExtra(key) + "]");
        }
    }
}

7.3 MyApplication:初始化與自訂通知樣式

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        AirshipConfigOptions options = AirshipConfigOptions.loadDefaultOptions(this);
        UAirship.takeOff(this, options);
        Logger.logLevel = Log.VERBOSE;

        CustomPushNotificationBuilder cpnb = new CustomPushNotificationBuilder();
        cpnb.statusBarIconDrawableId = R.drawable.ic_launcher;
        cpnb.layout = R.layout.notification;
        cpnb.layoutIconDrawableId = R.drawable.ic_launcher;
        cpnb.layoutIconId = R.id.icon;
        cpnb.layoutSubjectId = R.id.subject;
        cpnb.layoutMessageId = R.id.message;

        PushManager.shared().setNotificationBuilder(cpnb);
        PushManager.shared().setIntentReceiver(IntentReceiver.class);
    }
}

驗收與提醒

執行應用、勾選 Enable Push,從 logcat 取得 APID,把它帶到 Urban Airship 後台發送訊息,通知欄應該就會出現你自訂的樣式。

最後補一句現實狀況:Urban Airship 已改名為 Airship,本文對應的 2.x SDK 與 Helium 通道皆已停維。若用於新專案,請以 Airship 官方最新 SDK 為準;但這套「設定檔帶金鑰 → Application 初始化 → 自訂通知樣式 → Receiver 分流事件」的骨架,放到任何推送服務商身上都通用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved