android集成推送和消息响应

来源:互联网 发布:福建广电网络书记 编辑:程序博客网 时间:2024/06/05 08:14

Android所使用的各种第三方推送原理大致类似,首先集成各种第三方推送库文件,从程序的入口处启动推送,并同时注册监听器从推送服务器中进行消息接收和进行处理,以比较常见的百度推送为例。

首先打开网址http://app.baidu.com/apps,注册百度云平台开发者账户,之后打开上方的管理控制台中的开发者服务管理(ps:吐槽下百度的这个推送服务控制台真心难找)。


点击创建工程,填入自己的工程的名字后并创建



记下生成的应用ID,API KEY和SCREAT KEY。


从http://bs.baidu.com/push-sdk-release/Baidu-Push-SDK-Android-L2-4.4.0.zip下载对应的Android版SDK开发包

将对应的libs文件夹下的文件考入到对应的工程目录下。


新建MyApplication类并在onCreate中启动推送服务

package com.example.pushdemo;import com.baidu.frontia.FrontiaApplication;public class MyApplication extends FrontiaApplication {@Overridepublic void onCreate() {super.onCreate();FrontiaApplication.initFrontiaApplication(this);}}


在AndroidManifest.xml中添加百度推送所需要的权限和注册对应的接收receiver

    <!-- Push service 运行需要的权限 -->    <uses-permission android:name="android.permission.INTERNET"/>    <uses-permission android:name="android.permission.READ_PHONE_STATE" />    <uses-permission android:name="android.permission.ACCESS_NETWORK_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.WRITE_EXTERNAL_STORAGE" />    <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" />

  <!-- push富媒体,不使用富媒体推送不需要 -->        <activity            android:name="com.baidu.android.pushservice.richmedia.MediaViewActivity"            android:configChanges="orientation|keyboardHidden"            android:label="MediaViewActivity" >        </activity>        <activity            android:name="com.baidu.android.pushservice.richmedia.MediaListActivity"            android:configChanges="orientation|keyboardHidden"            android:label="MediaListActivity"            android:launchMode="singleTask" >        </activity>        <!-- push富媒体结束 -->                <!-- push应用定义消息receiver声明 -->        <receiver android:name="com.example.pushdemo.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>        <!-- 4.4版本新增的CommandService声明,提升小米和魅族手机上的实际推送到达率 -->        <service            android:name="com.baidu.android.pushservice.CommandService"            android:exported="true" />        <!-- push结束 -->                <!-- 在百度开发者中心查询应用的API Key -->        <meta-data android:name="api_key" android:value="INSERT YOUR OWN API_KEY HERE" />

新建MyPushMessageReceiver,用于接收推送过来的消息并进行相应的处理,onMessage用于接收透传消息,onNotificationClicked只有在处理通知栏的点击事件触发时才能接收到对应的推送消息,所以在使用百度推送需要通知栏消息的时候尽量在后台同时发送透传和通知信息。

package com.baidu.push.example;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import org.json.JSONException;import org.json.JSONObject;import android.content.Context;import android.content.Intent;import android.text.TextUtils;import android.util.Log;import com.baidu.frontia.api.FrontiaPushMessageReceiver;/** * Push消息处理receiver。请编写您需要的回调函数, 一般来说: onBind是必须的,用来处理startWork返回值; * onMessage用来接收透传消息; onSetTags、onDelTags、onListTags是tag相关操作的回调; * onNotificationClicked在通知被点击时回调; onUnbind是stopWork接口的返回值回调 *  * 返回值中的errorCode,解释如下:  *  0 - Success *  10001 - Network Problem *  30600 - Internal Server Error *  30601 - Method Not Allowed  *  30602 - Request Params Not Valid *  30603 - Authentication Failed  *  30604 - Quota Use Up Payment Required  *  30605 - Data Required Not Found  *  30606 - Request Time Expires Timeout  *  30607 - Channel Token Timeout  *  30608 - Bind Relation Not Found  *  30609 - Bind Number Too Many *  * 当您遇到以上返回错误时,如果解释不了您的问题,请用同一请求的返回值requestId和errorCode联系我们追查问题。 *  */public class MyPushMessageReceiver extends FrontiaPushMessageReceiver {    /** TAG to Log */    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);        // 绑定成功,设置已绑定flag,可以有效的减少不必要的绑定请求        if (errorCode == 0) {            Utils.setBind(context, true);        }        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑        updateContent(context, responseString);    }    /**     * 接收透传消息的函数。     *      * @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);        // 自定义内容获取方式,mykey和myvalue对应透传消息推送时自定义内容中设置的键和值        if (!TextUtils.isEmpty(customContentString)) {            JSONObject customJson = null;            try {                customJson = new JSONObject(customContentString);                String myvalue = null;                if (!customJson.isNull("mykey")) {                    myvalue = customJson.getString("mykey");                }            } catch (JSONException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑        updateContent(context, messageString);    }    /**     * 接收通知点击的函数。注:推送通知被用户点击前,应用无法通过接口获取通知的内容。     *      * @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);        // 自定义内容获取方式,mykey和myvalue对应通知推送时自定义内容中设置的键和值        if (!TextUtils.isEmpty(customContentString)) {            JSONObject customJson = null;            try {                customJson = new JSONObject(customContentString);                String myvalue = null;                if (!customJson.isNull("mykey")) {                    myvalue = customJson.getString("mykey");                }            } catch (JSONException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑        updateContent(context, notifyString);    }    /**     * 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> sucessTags, List<String> failTags, String requestId) {        String responseString = "onSetTags errorCode=" + errorCode                + " sucessTags=" + sucessTags + " failTags=" + failTags                + " requestId=" + requestId;        Log.d(TAG, responseString);        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑        updateContent(context, 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> sucessTags, List<String> failTags, String requestId) {        String responseString = "onDelTags errorCode=" + errorCode                + " sucessTags=" + sucessTags + " failTags=" + failTags                + " requestId=" + requestId;        Log.d(TAG, responseString);        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑        updateContent(context, 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);        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑        updateContent(context, 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);        // 解绑定成功,设置未绑定flag,        if (errorCode == 0) {            Utils.setBind(context, false);        }        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑        updateContent(context, responseString);    }    private void updateContent(Context context, String content) {        Log.d(TAG, "updateContent");        String logText = "" + Utils.logStringCache;        if (!logText.equals("")) {            logText += "\n";        }        SimpleDateFormat sDateFormat = new SimpleDateFormat("HH-mm-ss");        logText += sDateFormat.format(new Date()) + ": ";        logText += content;        Utils.logStringCache = logText;        Intent intent = new Intent();        intent.setClass(context.getApplicationContext(), PushDemoActivity.class);        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        context.getApplicationContext().startActivity(intent);    }}

在MainActivity中的onCreate中添加推送启动和对应的消息处理监听器

        // Push: 以apikey的方式登录,一般放在主Activity的onCreate中。        // 这里把apikey存放于manifest文件中,只是一种存放方式,        // 您可以用自定义常量等其它方式实现,来替换参数中的Utils.getMetaValue(this,"api_key")        !! 请将AndroidManifest.xml 104行处 api_key 字段值修改为自己的 api_key 方可使用 !!        !! ATTENTION:You need to modify the value of api_key to your own at row 104 in AndroidManifest.xml to use this Demo !!        PushManager.startWork(getApplicationContext(),PushConstants.LOGIN_TYPE_API_KEY,Utils.getMetaValue(this, "api_key"));        // Push: 如果想基于地理位置推送,可以打开支持地理位置的推送的开关        // PushManager.enableLbs(getApplicationContext());        // Push: 设置自定义的通知样式,具体API介绍见用户手册,如果想使用系统默认的可以不加这段代码        // 请在通知推送界面中,高级设置->通知栏样式->自定义样式,选中并且填写值:1,        // 与下方代码中 PushManager.setNotificationBuilder(this, 1, cBuilder)中的第二个参数对应        CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(                getApplicationContext(), resource.getIdentifier(                        "notification_custom_builder", "layout", pkgName),                resource.getIdentifier("notification_icon", "id", pkgName),                resource.getIdentifier("notification_title", "id", pkgName),                resource.getIdentifier("notification_text", "id", pkgName));        cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);        cBuilder.setNotificationDefaults(Notification.DEFAULT_SOUND                | Notification.DEFAULT_VIBRATE);        cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);        cBuilder.setLayoutDrawable(resource.getIdentifier(                "simple_notification_icon", "drawable", pkgName));        PushManager.setNotificationBuilder(this, 1, cBuilder);

    @Override    protected void onNewIntent(Intent intent) {        //消息处理部分        updateDisplay();    }

打包运行,在百度云推送平台的开发者管理服务中发送消息给客户端,客户端即可收到推送消息并作出相应的响应。

0 0