Android集成指南

运行环境和集成流程

集成流程

  1. 注册登录推送宝,创建 Android 应用程序
  2. 下载推送宝 Android SDK
  3. 配置 SDK,调用推送宝的初始化代码
  4. 通过推送宝网站或者推送宝 Open API 推送消息
  5. 应用程序实时获得推送的消息

准备工作

基本概念

推送宝针对国内无法访问 Google 的服务以及无法满足 GCM 的推送条件,推送宝构建了自己的实时推送服务TPS(Tuisongbao Push Service)。 推送宝的 Android SDK 使用专属的长链接,可以保证实时的将推送消息推送到设备客户端。同时,多个安装推送宝 SDK 的 app 可以共享同一条推送通道,节省用户的电量以及网络流量。

集成前准备工作

下载 SDK

通过下载 SDK页面下载 Android SDK。

SDK 中主要包括以下内容:

  • libs
    • tuisongbao_push_android_v{version}.jar
    • hmssdk-2_4_0_300.jar
    • MiPush_SDK_Client_3_1_2.jar
    • armeabi-v7a/libpush-jni.so
    • armeabi/libpush-jni.so
  • demo

导入 SDK

Eclipse
  • 在文件管理器中打开工程。
  • 将所有 jar 文件,armeabi/libpush-jni.soarmeabi-v7a/libpush-jni.so 复制到 libs目录下(如果没有,则新建libs)。
  • 在 Eclipse 中打开工程。
  • 在你的 Android 工程上,点击右键 -> Property -> Java BuildPath,添加对tuisongbao_push_android_v{version}.jar的引用。
Android Studio
  • 在文件管理器中打开工程。
  • armeabi/libpush-jni.soarmeabi-v7a/libpush-jni.so 复制到 app/src/main/jniLibs 目录下(如果没有,则新建 jniLibs)。
  • 将所有 jar 文件复制到 app/libs 目录下(如果没有,则新建 libs )。
  • 在 Android Studio 中打开工程。
  • 在右侧(默认位置,请根据实际情况调整)的 Gradle projects 的窗口中,点击左上角的 Refresh all gradle projects,加载已添加的依赖。

配置详解

推送宝 SDK 的配置文件

assets (Android Studio 是在 app/src/main/assets) 目录下新建 pushconfig.properties 文件并填写以下内容:

MIPUSH_APP_ID = 654321
MIPUSH_APP_KEY = 987654

PUSH_APP_ID = 123456
PUSH_APP_KEY = myappkey1234
LOCATION_TRACK = true
SDK_SECRET = 012345678901234567890123
PUSH_MSG_PROCESSOR = com.tuisongbao.push.demo.app.NotificationIntentService
DEBUG_SWITCH = true

说明

  • PUSH_APP_ID:推送宝网站上注册的 APP ID。
  • PUSH_APP_KEY:对于从老版本迁移过来的 APP,需要设置此参数为老版本 APP 的 APP Key。 否则,请 删除 此参数。
  • LOCATION_TRACK: 地理位置追踪选项。推送宝会采集用户的地理位置,并可以在推送宝的网站上查看用户的地理分布;地理围栏的推送也基于此选项。注意,令此选项生效还需要在 AndroidManifest.xml 文件中添加地理位置相关的 permissionService如何使用基于地理位置的推送
  • SDK_SECRET:SDK API 基本身份验证时使用的 password,可以从 APP ID 的页面上获得。
  • MIPUSH_APP_IDMIPUSH_APP_KEY:小米推送服务的 App Id 和 App Key,如何使用小米推送?
  • PUSH_MSG_PROCESSOR: 自定义消息处理服务,需要与 AndroidManifest.xml 中的声明一致,结合该示例,在 AndroidManifest.xml 文件中应该有:

      <service android:name="com.tuisongbao.push.demo.app.NotificationIntentService" />
    
  • DEBUG_SWITCH: 调试日志开关。

应用程序的 AndoirdManifest.xml

  1. 声明 Android 版本,推送宝 SDK 可以支持 Android2.2(api 8)以上所有版本,xxx 是一个 int 值,表示开发者开发应用时主要针对哪个 Android 版本进行开发的。Android Studio 的开发者请在 build.gradle 中配置。

     <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="xxx" />
    
  2. 加入自定义权限,这样应用程序才可以接收到来自推送宝的推送:

     <permission android:name="{my_app_package}.permission.PUSH" android:protectionLevel="signature" />
     <uses-permission android:name="{my_app_package}.permission.PUSH" />
    

    这里定义的权限必须是{my_app_package}.permission.PUSH,其中my_app_package是你的应用程序的包名。

  3. 加入以下权限:

     <!-- TPS 推送需要网络连接 -->
     <uses-permission android:name="android.permission.INTERNET" />
    
     <!-- 接收到新的推送消息,需要唤醒应用程序的进程 -->
     <uses-permission android:name="android.permission.WAKE_LOCK" />
    
     <!-- 推送宝需要根据以下信息产生设备的唯一识别码 -->
     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    
     <!-- 开机启动和读取网络状态,使得 Service 运行稳定 -->
     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
     <!-- 允许收到通知时设置振动 -->
     <uses-permission android:name="android.permission.VIBRATE" />
    
     <!-- 点击消息时打开应用 -->
     <uses-permission android:name="android.permission.GET_TASKS" />
    
     <!-- 用于记录日志 -->
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
     <!-- 可选,建议配置,推送宝会跟踪用户的地理位置,开发者则可以进行基于区域的推送 -->
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
  4. 加入广播接收声明,用来接收从 Android 后台发出的消息:

     <receiver
         android:name="com.tuisongbao.push.PushBroadcastReceiver" >
         <intent-filter android:priority="1000">
             <action android:name="android.intent.action.BOOT_COMPLETED" />
             <action android:name="android.intent.action.USER_PRESENT" />
             <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
         </intent-filter>
    
         <intent-filter android:priority="1000" >
             <action android:name="com.tuisongbao.push.action.RECEIVE" />
             <action android:name="com.tuisongbao.push.action.GEOFENCE" />
         </intent-filter>
     </receiver>
    
  5. 声明用于处理推送消息的 Intent Service:

     <service android:name="com.tuisongbao.push.service.NotificationIntentService">
     </service>
    

    注意:如果你的应用程序仅需要通过 Android 的通知中心显示推送的消息正文,可以保留 NotificationIntentService的配置,否则,替换为自定义的 Service,该 Service 必须继承于 NotificationIntentService。同时,这里的 Service 须与 pushconfig.properties 中配置的 PUSH_MSG_PROCESSOR 相同:

  6. 声明推送宝后台服务:

     <service
         android:name="com.tuisongbao.push.tps.PushService"
         android:process=":tps" >
         <intent-filter>
             <action android:name="com.tuisongbao.push.tps.PushService" />
         </intent-filter>
     </service>
    
  7. 支持 RichMedia 的消息需要声明相应的 Activity,不需要支持时可以不声明:

     <activity
         android:name="com.tuisongbao.push.richmedia.RichMediaActivity"
         android:configChanges="keyboardHidden|orientation|screenLayout|uiMode|screenSize"
         android:theme="@android:style/Theme.NoTitleBar" >
     </activity>
    
  8. 加入 LocationService 的声明,用来监测地理围栏的进出,不需要支持时可以不声明:

     <service
         android:name="com.tuisongbao.push.location.PushLocationService"
         android:process=":location" >
     </service>
    

调用初始化代码

开发者需要在应用程序启动的时候,调用推送宝的初始化代码PushManager.init(Context)。我们推荐在 Application 的onCreate方法里调用推送宝 SDK 的初始化方法,具体实现可以参照 Demo 中的做法。

public class MyApplication extends Application
{
    @Override
    public void onCreate()
    {
        super.onCreate();
        //在你的 App 的 onCreate 方法里调用该方法,初始化推送宝的本地服务
        PushManager.init(this);
    }
}

之后在AndroidManifest.xml中配置 application 标签为你定义的名字,例如:

<application
    android:name="com.mypackage.app.MyApplication"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

自定义消息处理逻辑

当有推送消息到达时,SDK 会发送该消息给 IntentService 去处理(异步)。默认发送给 com.tuisongbao.push.service.NotificationIntentService, 并且会在通知栏显示最新的一条消息, 用户点击消息即可打开应用程序。 如果应用需要重新定义这个逻辑,需要做以下几件事:

  1. 自定义 IntentService, 并使其继承于推送宝的 NotificationIntentService
public class MyMsgIntentService extends NotificationIntentService
{
    @Override
    protected void onMessageDelivered(HashMap<String, String> msgMap) {
        // required
        super.onMessageDelivered(msgMap);

        String passthrough = msgMap.get(Constants.passthrough);
        if (StrUtils.isEqual(passthrough, String.valueOf(true))) {
            Notification myNotification = super.notification; // 这个 notification 具有高级设置的属性,即发送消息时推送宝网站上面对该消息设置的样式,点击行为等。你可以修改这个 notification 的内容以适应你的需要。
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(1, myNotification);
        }

        String alert = msgMap.get("body");
        String title = msgMap.get("title");
        String extraMsg = msgMap.get("my-extra"); // 获取自定义内容

        // 你的处理逻辑
    }

    @Override
    protected void onMessageClicked(HashMap<String, String> msgHashMap) {
        // 当小米和华为的通知栏消息被点击时回调,v3.1 新增
    }

    @Override
    protected void onGeoFenceTrigger(PushGeoFence geoFence, PushLocationManager.Event event, PushLocation location) {
        super.onGeoFenceTrigger(geoFence, event, location);
    }

    @Override
    protected void onLocationChanged(PushLocation currentLocation) {
        super.onLocationChanged(currentLocation);
    }

    @Override
    protected void onRegistered(String token, PushConfig.Service service)
    {
        super.onRegistered(token, service);
    }

    @Override
    protected boolean silentNotification() {
        // 对于透传消息,SDK 默认会在通知栏显示收到的通知,如果要去掉这个行为,return true 即可,默认为 false
        return false;
    }
}
  1. 修改 pushconfig.properties 中的 PUSH_MSG_PROCESSOR{MyMsgIntentService_class_package}.MyMsgIntentService
  2. 更新 AndroidManifest.xml 中与 PUSH_MSG_PROCESSOR 匹配的 IntentService

NotificationIntentService 接口说明

protected void onMessageDelivered(HashMap<String, String> msgMap)

当接收到 透传消息 时,推送宝 SDK 会回调 onMessageDelivered 方法,开发者可以在这里定义自己的消息处理逻辑。

参数说明:

  • HashMap msgMap:消息内容,其中,msgMap["title"] 为消息的标题,msgMap["body"] 为消息的正文,msgMap["{key}"] 为推送者自定义的附加信息。
protected void onMessageClicked(HashMap<String, String> msgMap) // v3.1 新增

当接收到 通知栏消息 时,消息会先显示在通知栏,用户点击之后 SDK 才会回调该方法。

参数说明:

  • HashMap msgMap:消息内容,其中,msgMap["title"] 为消息的标题,msgMap["body"] 为消息的正文,msgMap["{key}"] 为推送者自定义的附加信息。
protected void onRegistered(String token, PushConfig.Service service)

该事件用于开发者获取设备的 token。推送宝 SDK 默认会将 tokenservice提交到推送宝系统用于发送推送消息,如果开发者需要在自己的系统里保存一份,可以重写该方法,将 token 提交到自己的服务端。

参数说明:

  • String token:推送宝分配给设备的唯一识别码。
  • String service:所用的推送服务,PushConfig.Service.TPS或者PushConfig.Service.MIPUSH
protected void onGeoFenceTrigger(PushGeoFence geoFence, PushLocationManager.Event event, PushLocation location)

参数说明:

  • PushGeofence geofence:被触发的地理围栏。
  • PushLocationManager.Event event PushLocationManager.Event.LEAVEPushLocationManager.Event.ENTER
  • PushLocation location:被触发一刻所获得的地理位置信息。
protected boolean silentNotification()

SDK 默认会在通知栏中显示一条最新的通知消息,如果开发者需要改写此行为,可以重写该方法,并 return true,推送宝 SDK 将不会显示通知,由开发者自行决定如何处理接收到的消息。

所有 API

public static PushResponse registerTag(String tag);
public static PushResponse registerTags(List<String> tags);
public static void registerTagInBackground(String tag, PushCallback<PushResponse> callBack);
public static void registerTagsInBackground(List<String> tags, PushCallback<PushResponse> callBack);

API 说明

推送消息时,可以将特定的消息推送给特定的用户。为了对他们进行标识,可以给他们制定不同标签。请尽量使用英文字母,数字,下划线,中文等常用字符,以免因为字符格式导致注册标签失败。

public static PushResponse unregisterTag(String tag);
public static PushResponse unregisterTags(List<String> tags);
public static void unregisterTagInBackground(String tag, PushCallback<PushResponse> callBack);
public static void unregisterTagsInBackground(List<String> tags, PushCallback<PushResponse> callBack);

API 说明

解除指定的标签。该用户将不再收到发送给该标签的消息。

public static PushResponse registerUserVar(Map<String, String> dataMap);
public static void registerUserVarInBackground(Map<String, String> data, PushCallback<PushResponse> callBack);

API 说明

注册用户变量。使得同一个消息发给不同的设备可以产生不同的消息内容。

public static PushResponse setAlias(String alias); // v2.2.0新增
public static void setAliasInBackground(String alias, PushCallback<PushResponse> callBack);

API 说明

给设备设置别名。同一个设备只能绑定一个别名,新的别名会覆盖旧的。

    public static void feedbackMessage(String nid); // v3.0新增
    public static void feedbackMessageInBackground(String nid, PushCallback<PushResponse> callBack); // v3.0新增

API 说明

对收到的消息进行反馈,推送宝服务端会增加 nid 所对应的消息的 点击数nidcom_pushyun_nid 所对应的值。

集成 Geo Fence 消息推送

  1. 加入 LocationService 的声明,并在 pushconfig.properties 文件中开启 LOCATION_TRACK

     <service
         android:name="com.tuisongbao.push.location.PushLocationService"
         android:process=":location" >
     </service>
    
  2. 更新 PushBroadcastReceiver 的配置,注册 GEOFENCEbroadcast,用来接收地理围栏的触发事件。

     <receiver
         android:name="com.tuisongbao.push.PushBroadcastReceiver" >
         <intent-filter android:priority="1000">
             <action android:name="android.intent.action.BOOT_COMPLETED" />
             <action android:name="android.intent.action.USER_PRESENT" />
             <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
         </intent-filter>
    
         <intent-filter android:priority="1000" >
             <action android:name="com.tuisongbao.push.action.RECEIVE" />
             <action android:name="com.tuisongbao.push.action.GEOFENCE" />
         </intent-filter>
     </receiver>
    
  3. 我们在 NotificationIntentService 中定义了onGeofenceTrigger()方法用来处理地理围栏的触发事件,开发者可以通过重写该接口定义自己的处理流程。

     @Override
     protected void onGeoFenceTrigger(PushGeoFence geoFence, PushLocationManager.Event event, PushLocation location) {
         super.onGeoFenceTrigger(geoFence, event, location);
     }
    

在 EMUI 上使用华为推送

推送宝的 SDK 内集成了华为的推送服务( HMS-Push 服务),推送宝将其命名为 HuaweiPush, 在 EMUI 上可以提高送达率。 如果开发者决定使用 HuaweiPush (仅在 EMUI 上生效)请遵循以下步骤, 否则请不要配置相关参数, SDK 将根据当前 ROM 类型选择相应的 Push 服务,默认使用 TPS

  1. 申请华为推送服务,创建应用,获取 APP ID 和 APP SECRET。
  2. AndroidManifest.xml 文件中声明华为推送服务需要的 servicereceiver,在 application 节点下增加:

     <meta-data android:name="com.huawei.hms.client.appid" android:value="{APP ID}">
     </meta-data>
     <provider android:name="com.huawei.hms.update.provider.UpdateProvider"
               android:authorities="{my_app_package}.hms.update.provider"
               android:exported="false"
               android:grantUriPermissions="true" >
     </provider>
     <receiver android:name="com.huawei.hms.support.api.push.PushEventReceiver" >
         <intent-filter>
             <action android:name="com.huawei.intent.action.PUSH" />
         </intent-filter>
     </receiver>
    
     <receiver android:name="com.tuisongbao.push.huawei.HWPushReceiver">
         <intent-filter>
             <action android:name="com.huawei.android.push.intent.REGISTRATION" />
             <action android:name="com.huawei.android.push.intent.RECEIVE" />
             <action android:name="com.huawei.android.push.intent.CLICK" />
             <action android:name="com.huawei.intent.action.PUSH_STATE" />
         </intent-filter>
     </receiver>
    

    将第 1 步中获得的 APP ID 填入 {APP ID},并配置 {my_app_package}

  3. 在华为开发者联盟的应用管理页面填写 SHA256 证书的指纹,图中 SHA256证书指纹 输入框旁的 图标提供了获取指纹的方法。

    image

  4. 在推送宝官网上启用 HuaweiPush,点击 设置 -> 服务,展开 HuaweiPush

    image

在 MIUI 上使用小米推送

推送宝的 SDK 内集成了小米的推送服务( MiPush ), 在 MIUI 上可以提高送达率。 如果开发者决定使用 MiPush (仅在 MIUI 上生效)请遵循以下步骤, 否则请不要配置相关参数, SDK 将根据当前 ROM 类型选择相应的 Push 服务,默认使用 TPS

  1. 申请小米推送服务,获取 APP KEY, APP ID 和 APP SECRET 。
  2. 导入 MiPush_SDK_Client_3_1_2_sdk.jar
  3. 修改assets目录下的pushconfig.properties文件,添加小米推送所需的 App 信息:

     MIPUSH_APP_ID = mymipushappId
     MIPUSH_APP_KEY = mymipushappkey
    
  4. AndroidManifest.xml文件中添加接收小米推送消息的权限:

         <permission
             android:name="{my_app_package}.permission.MIPUSH_RECEIVE"
             android:protectionLevel="signature" />
    
         <uses-permission android:name="{my_app_package}.permission.MIPUSH_RECEIVE" />
    
  5. AndroidManifest.xml 文件中声明小米推送服务需要的 servicereceiver

         <receiver
             android:name="com.tuisongbao.push.xiaomi.MiMessageReceiver"
             android:exported="true" >
             <intent-filter>
                 <action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE" />
             </intent-filter>
             <intent-filter>
                 <action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED" />
             </intent-filter>
             <intent-filter>
                 <action android:name="com.xiaomi.mipush.ERROR" />
             </intent-filter>
         </receiver>
    
         <service
             android:enabled="true"
             android:process=":pushservice"
             android:name="com.xiaomi.push.service.XMPushService"/>
         <service
             android:name="com.xiaomi.push.service.XMJobService"
             android:enabled="true"
             android:exported="false"
             android:permission="android.permission.BIND_JOB_SERVICE"
             android:process=":pushservice" />
         <service
             android:enabled="true"
             android:exported="true"
             android:name="com.xiaomi.mipush.sdk.PushMessageHandler" />
         <service android:enabled="true"
                  android:name="com.xiaomi.mipush.sdk.MessageHandleService" />
         <receiver
             android:exported="true"
             android:name="com.xiaomi.push.service.receivers.NetworkStatusReceiver" >
             <intent-filter>
                 <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
         </receiver>
         <receiver
             android:exported="false"
             android:process=":pushservice"
             android:name="com.xiaomi.push.service.receivers.PingReceiver" >
             <intent-filter>
                 <action android:name="com.xiaomi.push.PING_TIMER" />
             </intent-filter>
         </receiver>
    
  6. 在推送宝官网上启用 MiPush,点击 设置 -> 服务,展开 MiPush

    image

常见问题

设备注册成功, 但是收不到消息

  1. 确认测试设备已经连入网络。

  2. PushService 是否启动。常见情况是第三方的管理软件阻止了非系统服务的自启动。检查 PushService 是否在运行,设备进入设置->应用->正在运行, 查看应用是否在列表中。

    • 在: 进入下一步
    • 不在: 这种情况就需要用户手动设置。在第三方管理软件里面找到有关自启动的选项,并开启该应用的自启动权限。开启之后重新打开应用,看是否收到消息,如果还没有,进入下一步。
  3. 仔细核对AndroidManifest.xml文件和pushconfig.properties文件,确保 appkey,appid,包名等都正确。

  4. 如果以上都不能排查出问题,可以尝试生成 log 日志发送给推送宝

    • Linux 开发者:

      • pushconfig.properties文件中配置

        DEBUG_SWITCH = true
        
      • 卸载应用

      • 在 terminal 中输入(需先安装adb)

        adb logcat -c && adb logcat > log
        
      • 重新安装应用,等待应用进入初始界面,之后发送几条消息给该设备。

      • 在 terminal 中停止(Ctrl+c)上个脚本,然后在当前的目录下运行

        cat log | grep "tuisongbao" > tuisongbao.log
        
      • 把最终的tuisongbao.log文件发送给我们。

    • Windows 开发者:

      • 卸载应用

      • 打开cmd.exe,输入如下命令(需先安装adb)

        adb logcat -c && adb logcat com.tuisongbao.push.push.pushmanager:V com.tuisongbao.push.push.pushservice:V com.tuisongbao.push.push.pushservice.net:V com.tuisongbao.push.push:V com.tuisongbao.push.http:V com.tuisongbao.push.notification:V *:S
        
      • 重新安装应用,等待应用进入初始界面,之后发送几条消息给该设备。

      • cmd中输出的 log 发送给推送宝。

升级步骤

如无特殊说明,直接替换 SDK 即可。

v2.* 至 v3.0

  • 根据集成文档做相应更改。

v2.0 至 v2.1

  • 因为添加了 MiPush 服务,onRegistered接口有变化。

v1.5 至 v2.0

  • 修改assets目录下的pushconfig.properties文件,添加和修改如下配置:
SDK_SECRET = 012345678901234567890123
PUSH_APP_ID = 123456
PUSH_APP_KEY = myappkey1234

注意

对于从老版本迁移过来的 APP,需要设置PUSH_APP_KEY为老版本 APP 的 APP Key。否则,请删除此参数。

  • 在你的工程中,修改所有不兼容的调用接口。 主要是 channel(v2.0中改为 tag)和 userdata(v2.0中改为 uservar)的更名问题

v1.1 至 v1.5

用新的 SDK 里的tuisongbao.jararmeabi/libpush-ndk.soarmeabi-v7a/libpush-ndk.so替换老的文件,然后检查你的应用程序的AndroidManifest.xml文件:

  • 检查是否配置接收推送消息的权限:

      <permission android:name="{my_app_package}.permission.PUSH"
          android:protectionLevel="signature" />
      <uses-permission android:name="{my_app_package}.permission.PUSH" />
    
  • 修改assets目录下的pushconfig.properties文件,检查是否开启了 Location 跟踪:

      LOCATION_TRACK = true
    
  • 检查你的AndroidManifest.xml文件,是否加入了对 Location 权限的声明:

      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
  • 检查你的AndroidManifest.xml文件,是否针对PushBroadcastReceiver的配置新增加了新的intent-filter

      <intent-filter> <!--Required-->
          <action android:name="android.intent.action.PACKAGE_REMOVED" />
          <data android:scheme="package"/>
      </intent-filter>
    
  • 加入支持富媒体的Activity的声明:

      <activity
          android:name="com.tuisongbao.push.richmedia.RichMediaActivity"
          android:configChanges="keyboardHidden|orientation|screenLayout|uiMode|screenSize"
          android:theme="@android:style/Theme.NoTitleBar" >
      </activity>
    
  Back To Top