Azure 下通知(百度推送)

1. 从 Bintray 上 Notification-Hubs-Android-SDK 的“文件”选项卡下载 notification-hubs-0.4.jar 文件。 libs 文件夹,然后刷新 libs 文件夹。


2. 下载并解压缩百度推送 Android SDK,打开 libs 文件夹,然后将 pushservice-x.y.z jar 文件以及 armeabi & mips 文件夹复制到 Android 应用程序的 jniLibs 文件夹。


3. 打开 Android 项目的 AndroidManifest.xml 文件,并添加百度 SDK 所需的权限。

<!-- Push service 运行需要的权限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<!-- 富媒体需要声明的权限 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


<!-- 适配Android N系统必需的ContentProvider写权限声明,写权限包含应用包名-->
<uses-permission android:name="baidu.push.permission.WRITE_PUSHINFOPROVIDER.包名" />
<permission
    android:name="baidu.push.permission.WRITE_PUSHINFOPROVIDER.包名"
    android:protectionLevel="normal"></permission>

向 AndroidManifest.xml 中的 application 元素添加 android:name 属性,并替换 yourprojectname(例如 com.skypine.skypine)。 确保此项目名称与你在百度控制台中配置的项目名称匹配。

 <application android:name="yourprojectname.DemoApplication"

4. 在 .MainActivity 活动元素后的 application 元素内添加以下配置,并替换 yourprojectname(例如 com.example.BaiduTest):

<!--自定义的receiver-->
<receiver android:name=".receiver.MyPushMessageReceiver">
    <intent-filter>

        <!-- 接收push消息 -->
        <action android:name="com.baidu.android.pushservice.action.MESSAGE" />
        <!-- 接收bind,unbind,fetch,delete等反馈消息 -->
        <action android:name="com.baidu.android.pushservice.action.RECEIVE" />
        <action android:name="com.baidu.android.pushservice.action.notification.CLICK" />
    </intent-filter>
</receiver>

<!-- push必须的receviver和service声明 -->
<receiver
    android:name="com.baidu.android.pushservice.PushServiceReceiver"
    android:process=":bdservice_v1">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        <action android:name="com.baidu.android.pushservice.action.notification.SHOW" />
        <action android:name="com.baidu.android.pushservice.action.media.CLICK" />
        <!-- 以下四项为可选的action声明,可大大提高service存活率和消息到达速度 -->
        <action android:name="android.intent.action.MEDIA_MOUNTED" />
        <action android:name="android.intent.action.USER_PRESENT" />
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
    </intent-filter>
</receiver>
<receiver
    android:name="com.baidu.android.pushservice.RegistrationReceiver"
    android:process=":bdservice_v1">
    <intent-filter>
        <action android:name="com.baidu.android.pushservice.action.METHOD" />
        <action android:name="com.baidu.android.pushservice.action.BIND_SYNC" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_REMOVED" />

        <data android:scheme="package" />
    </intent-filter>
</receiver>

<service
    android:name="com.baidu.android.pushservice.PushService"
    android:exported="true"
    android:process=":bdservice_v1">
    <intent-filter>
        <action android:name="com.baidu.android.pushservice.action.PUSH_SERVICE" />
    </intent-filter>
</service>
<service
    android:name="com.baidu.android.pushservice.CommandService"
    android:exported="true" />

<!-- 适配Android N系统必需的ContentProvider声明,写权限包含应用包名-->
<provider
    android:name="com.baidu.android.pushservice.PushInfoProvider"
    android:authorities="com.skypine.skypine.bdpush"
    android:exported="true"
    android:protectionLevel="signature"
    android:writePermission="baidu.push.permission.WRITE_PUSHINFOPROVIDER.com.skypine.skypine" />


<!--推送-->

5. 将一个名为 ConfigurationSettings.java 的新类添加到项目中。

    /**
 * 百度推送
 * Created by syhuang on 2017/7/14.
 */

public class ConfigurationSettings {
    public static String API_KEY = "zrHB4m1yzwHDNFxI8uBAHxhi";
    public static String NotificationHubName = "daisy-notification";
    public static String NotificationHubConnectionString = "Endpoint=sb://daisy-ns.servicebus.chinacloudapi.cn/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=wJTvYJB4wG1GJOvEtdKwxEPT6rGOdLbcmBb+lEtzt7k=";
}

6. 将以下代码添加到该类中:

public class ConfigurationSettings {
        public static String API_KEY = "...";
        public static String NotificationHubName = "...";
        public static String NotificationHubConnectionString = "...";
    }

使用前面从百度云项目中检索到的内容设置 API_KEY 的值,使用 Azure 经典门户中的通知中心名称设置 NotificationHubName,并使用 Azure 经典门户中的 DefaultListenSharedAccessSignature 设置 NotificationHubConnectionString。


7. 添加另一个名为 MyPushMessageReceiver.java的新类,并向此类中添加以下代码。 此类用于处理从百度推送服务器收到的推送通知。

/**
 * Created by syhuang on 2017/7/14.
 */

public class MyPushMessageReceiver extends PushMessageReceiver {
    /**
     * TAG to Log
     */
    public static NotificationHub hub = null;
    public static String mChannelId, mUserId;
    public static final String TAG = MyPushMessageReceiver.class
            .getSimpleName();

    /**
     * 调用PushManager.startWork后,sdk将对push
     * server发起绑定请求,这个过程是异步的。绑定请求的结果通过onBind返回。 如果您需要用单播推送,需要把这里获取的channel
     * id和user id上传到应用server中,再调用server接口用channel id和user id给单个手机或者用户推送。
     *
     * @param context   BroadcastReceiver的执行Context
     * @param errorCode 绑定接口返回值,0 - 成功
     * @param appid     应用id。errorCode非0时为null
     * @param userId    应用user id。errorCode非0时为null
     * @param channelId 应用channel id。errorCode非0时为null
     * @param requestId 向服务端发起的请求id。在追查问题时有用;
     * @return none
     */
    @Override
    public void onBind(Context context, int errorCode, String appid,
                       String userId, String channelId, String requestId) {
        String responseString = "onBind errorCode=" + errorCode + " appid="
                + appid + " userId=" + userId + " channelId=" + channelId
                + " requestId=" + requestId;
        Log.d(TAG, responseString);
        mChannelId = channelId;
        mUserId = userId;

        try {
            if (hub == null) {
                hub = new NotificationHub(
                        ConfigurationSettings.NotificationHubName,
                        ConfigurationSettings.NotificationHubConnectionString,
                        context);
                Log.i(TAG, "Notification hub initialized");
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        registerWithNotificationHubs();
    }

    private void registerWithNotificationHubs() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    hub.registerBaidu(mUserId, mChannelId);
                    Log.i(TAG, "Registered with Notification Hub - '"
                            + ConfigurationSettings.NotificationHubName + "'"
                            + " with UserId - '"
                            + mUserId + "' and Channel Id - '"
                            + mChannelId + "'");
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
                return null;
            }
        }.execute(null, null, null);
    }

    /**
     * setTags() 的回调函数。
     *
     * @param context     上下文
     * @param errorCode   错误码。0表示某些tag已经设置成功;非0表示所有tag的设置均失败。
     * @param successTags 设置成功的tag
     * @param failTags    设置失败的tag
     * @param requestId   分配给对云推送的请求的id
     */
    @Override
    public void onSetTags(Context context, int errorCode,
                          List<String> successTags, List<String> failTags, String requestId) {
        String responseString = "onSetTags errorCode=" + errorCode
                + " sucessTags=" + successTags + " failTags=" + failTags
                + " requestId=" + requestId;
        Log.d(TAG, responseString);
    }

    /**
     * delTags() 的回调函数。
     *
     * @param context     上下文
     * @param errorCode   错误码。0表示某些tag已经删除成功;非0表示所有tag均删除失败。
     * @param successTags 成功删除的tag
     * @param failTags    删除失败的tag
     * @param requestId   分配给对云推送的请求的id
     */
    @Override
    public void onDelTags(Context context, int errorCode,
                          List<String> successTags, List<String> failTags, String requestId) {
        String responseString = "onDelTags errorCode=" + errorCode
                + " sucessTags=" + successTags + " failTags=" + failTags
                + " requestId=" + requestId;
        Log.d(TAG, responseString);
    }

    /**
     * listTags() 的回调函数。
     *
     * @param context   上下文
     * @param errorCode 错误码。0表示列举tag成功;非0表示失败。
     * @param tags      当前应用设置的所有tag。
     * @param requestId 分配给对云推送的请求的id
     */
    @Override
    public void onListTags(Context context, int errorCode, List<String> tags,
                           String requestId) {
        String responseString = "onListTags errorCode=" + errorCode + " tags="
                + tags;
        Log.d(TAG, responseString);
    }

    /**
     * PushManager.stopWork() 的回调函数。
     *
     * @param context   上下文
     * @param errorCode 错误码。0表示从云推送解绑定成功;非0表示失败。
     * @param requestId 分配给对云推送的请求的id
     */
    @Override
    public void onUnbind(Context context, int errorCode, String requestId) {
        String responseString = "onUnbind errorCode=" + errorCode
                + " requestId = " + requestId;
        Log.d(TAG, responseString);
        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
    }

    /**
     * 接收通知点击的函数。
     *
     * @param context             上下文
     * @param title               推送的通知的标题
     * @param description         推送的通知的描述
     * @param customContentString 自定义内容,为空或者json字符串
     */
    @Override
    public void onNotificationClicked(Context context, String title,
                                      String description, String customContentString) {
        String notifyString = "title=\"" + title + "\" description=\""
                + description + "\" customContent=" + customContentString;
        Log.d(TAG, notifyString);
    }

    /**
     * 接收通知到达的函数。
     *
     * @param context             上下文
     * @param title               推送的通知的标题
     * @param description         推送的通知的描述
     * @param customContentString 自定义内容,为空或者json字符串
     */

    @Override
    public void onNotificationArrived(Context context, String title,
                                      String description, String customContentString) {
        String messageString = "title" + title + "message=\"" + description + "\" customContentString=" + customContentString;
        Log.d(TAG, messageString);
    }

    /**
     * 接收透传消息的函数。
     *
     * @param context             上下文
     * @param message             推送的消息
     * @param customContentString 自定义内容,为空或者json字符串
     */

    @Override
    public void onMessage(Context context, String message,
                          String customContentString) {
        String messageString = "message=\"" + message + "\" customContentString=" + customContentString;
        Log.d(TAG, messageString);
    }
}

8. 打开 MainActivity.java,并将以下内容添加到 onCreate 方法中:

    PushManager.startWork(getApplicationContext(),
            PushConstants.LOGIN_TYPE_API_KEY, ConfigurationSettings.API_KEY);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,116评论 25 707
  • 创造被动收入的法则,我们看第一条勇敢的把握机会,赢得你真正想要的生活。很多的人觉得自己就是缺少机会,事实是什么呢?...
    听雨廖哥阅读 812评论 0 0
  • 又到深夜,整个县城还没有陷入混沌一片的黑暗,耿耿的星星疏落在墨染的天空,月亮浅浅的,楼下单元门口因为结婚刚刚挂起的...
    双生夕阅读 250评论 0 0
  • HTML、XML、XHTML 有什么区别? HTML:超文本标记语言,是语法较为松散的、不严格的Web语言,主要用...
    饥人谷_NewClass阅读 302评论 0 0