Android推送 百度云推送 入门篇

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/27231237

现在app基本都有推送的功能,于是看了下百度云的推送,官方文档和Demo都很到位,记录下使用过程,目标是利用百度云推送最为服务器写个及时通讯的例子~当然了,这是第一篇入门~

1、第一步就是在百度开发者服务管理中创建项目,然后拿到API key , Secret Key ;这个过程就不多说了,上官网直接申请就行,不复杂。

2、下载云推送的客户端SDK,SDK的压缩文件中包含一个例子代码,一个用户手册,和所需的libs和资源等(其实直接看用户手册和Demo基本就没问题了)。

3、准备工作结束,接下来,我们就直接开始新建项目测试

a、新建一个项目,然后把SDK中的libs中的jar和so文件夹拷贝到新建的项目中去

b、将manifest中的application的name设置为:com.baidu.frontia.FrontiaApplication

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <application  
  2.      android:name="com.baidu.frontia.FrontiaApplication"  
  3.      android:allowBackup="true"  
  4.      android:icon="@drawable/ic_launcher"  
  5.      android:label="@string/app_name"  
  6.      android:theme="@style/AppTheme" >  


如果你的项目需要自定义Application,请参考用户手册中的相关配置。

 

c、添加权限

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <uses-permission android:name="android.permission.INTERNET" />  
  2.    <uses-permission android:name="android.permission.READ_PHONE_STATE" />  
  3.    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  4.    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  
  5.    <uses-permission android:name="android.permission.WRITE_SETTINGS" />  
  6.    <uses-permission android:name="android.permission.VIBRATE" />  
  7.    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  8.    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />  
  9.    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
  10.    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  


d、添加两个receiver和一个Service(注释标明了用处)

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <!-- push service start -->  
  2.        <!-- 用于接收系统消息以保证PushService正常运行 -->  
  3.        <receiver  
  4.            android:name="com.baidu.android.pushservice.PushServiceReceiver"  
  5.            android:process=":bdservice_v1" >  
  6.            <intent-filter>  
  7.                <action android:name="android.intent.action.BOOT_COMPLETED" />  
  8.                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />  
  9.                <action android:name="com.baidu.android.pushservice.action.notification.SHOW" />  
  10.                <action android:name="com.baidu.android.pushservice.action.media.CLICK" />  
  11.            </intent-filter>  
  12.        </receiver>  
  13.        <!-- Push服务接收客户端发送的各种请求 -->  
  14.        <!-- 注意:RegistrationReceiver 在2.1.1及之前版本有拼写失误,为RegistratonReceiver ,用新版本SDK时请更改为如下代码 -->  
  15.        <receiver  
  16.            android:name="com.baidu.android.pushservice.RegistrationReceiver"  
  17.            android:process=":bdservice_v1" >  
  18.            <intent-filter>  
  19.                <action android:name="com.baidu.android.pushservice.action.METHOD" />  
  20.                <action android:name="com.baidu.android.pushservice.action.BIND_SYNC" />  
  21.            </intent-filter>  
  22.            <intent-filter>  
  23.                <action android:name="android.intent.action.PACKAGE_REMOVED" />  
  24.   
  25.                <data android:scheme="package" />  
  26.            </intent-filter>  
  27.        </receiver>  
  28.        <!-- Push 服务 -->  
  29.        <!-- 注意:在4.0 (包含)之后的版本需加上如下所示的intent-filter action -->  
  30.        <service  
  31.            android:name="com.baidu.android.pushservice.PushService"  
  32.            android:exported="true"  
  33.            android:process=":bdservice_v1" >  
  34.            <intent-filter>  
  35.                <action android:name="com.baidu.android.pushservice.action.PUSH_SERVICE" />  
  36.            </intent-filter>  
  37.        </service>  
  38.        <!-- push service end -->  


e、我们需要自己实现一个Receiver,来接收Push消息、接口调用回调以及通知点击事件。

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <receiver android:name="com.example.zhy_baiduyun_tuisong01.receiver.MyPushMessageReceiver" >  
  2.            <intent-filter>  
  3.                <!-- 接收push消息 -->  
  4.                <action android:name="com.baidu.android.pushservice.action.MESSAGE" />  
  5.                <!-- 接收bind、setTags等method的返回结果 -->  
  6.                <action android:name="com.baidu.android.pushservice.action.RECEIVE" />  
  7.                <!-- 可选。接受通知点击事件,和通知自定义内容 -->  
  8.                  <action android:name="com.baidu.android.pushservice.action.notification.CLICK" />  
  9.            </intent-filter>  
  10.        </receiver>  


代码:

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.example.zhy_baiduyun_tuisong01.receiver;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.json.JSONException;  
  6. import org.json.JSONObject;  
  7.   
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.text.TextUtils;  
  11. import android.util.Log;  
  12.   
  13. import com.baidu.frontia.api.FrontiaPushMessageReceiver;  
  14. import com.example.zhy_baiduyun_tuisong01.MainActivity;  
  15. import com.example.zhy_baiduyun_tuisong01.util.PreUtils;  
  16.   
  17. /** 
  18.  * Push消息处理receiver。请编写您需要的回调函数, 一般来说: onBind是必须的,用来处理startWork返回值; 
  19.  * onMessage用来接收透传消息; onSetTags、onDelTags、onListTags是tag相关操作的回调; 
  20.  * onNotificationClicked在通知被点击时回调; onUnbind是stopWork接口的返回值回调 
  21.  *  
  22.  * 返回值中的errorCode,解释如下:  
  23.  *  0 - Success 
  24.  *  10001 - Network Problem 
  25.  *  30600 - Internal Server Error 
  26.  *  30601 - Method Not Allowed  
  27.  *  30602 - Request Params Not Valid 
  28.  *  30603 - Authentication Failed  
  29.  *  30604 - Quota Use Up Payment Required  
  30.  *  30605 - Data Required Not Found  
  31.  *  30606 - Request Time Expires Timeout  
  32.  *  30607 - Channel Token Timeout  
  33.  *  30608 - Bind Relation Not Found  
  34.  *  30609 - Bind Number Too Many 
  35.  *  
  36.  * 当您遇到以上返回错误时,如果解释不了您的问题,请用同一请求的返回值requestId和errorCode联系我们追查问题。 
  37.  *  
  38.  */  
  39. public class MyPushMessageReceiver extends FrontiaPushMessageReceiver {  
  40.     /** TAG to Log */  
  41.     public static final String TAG = MyPushMessageReceiver.class  
  42.             .getSimpleName();  
  43.   
  44.     /** 
  45.      * 调用PushManager.startWork后,sdk将对push 
  46.      * server发起绑定请求,这个过程是异步的。绑定请求的结果通过onBind返回。 如果您需要用单播推送,需要把这里获取的channel 
  47.      * id和user id上传到应用server中,再调用server接口用channel id和user id给单个手机或者用户推送。 
  48.      *  
  49.      * @param context 
  50.      *            BroadcastReceiver的执行Context 
  51.      * @param errorCode 
  52.      *            绑定接口返回值,0 - 成功 
  53.      * @param appid 
  54.      *            应用id。errorCode非0时为null 
  55.      * @param userId 
  56.      *            应用user id。errorCode非0时为null 
  57.      * @param channelId 
  58.      *            应用channel id。errorCode非0时为null 
  59.      * @param requestId 
  60.      *            向服务端发起的请求id。在追查问题时有用; 
  61.      * @return none 
  62.      */  
  63.     @Override  
  64.     public void onBind(Context context, int errorCode, String appid,  
  65.             String userId, String channelId, String requestId) {  
  66.         String responseString = "onBind errorCode=" + errorCode + " appid="  
  67.                 + appid + " userId=" + userId + " channelId=" + channelId  
  68.                 + " requestId=" + requestId;  
  69.         Log.e(TAG, responseString);  
  70.   
  71.         // 绑定成功,设置已绑定flag,可以有效的减少不必要的绑定请求  
  72.         if (errorCode == 0) {  
  73.             PreUtils.bind(context);  
  74.         }  
  75.         // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑  
  76.         updateContent(context, responseString);  
  77.     }  
  78.   
  79.     /** 
  80.      * 接收透传消息的函数。 
  81.      *  
  82.      * @param context 
  83.      *            上下文 
  84.      * @param message 
  85.      *            推送的消息 
  86.      * @param customContentString 
  87.      *            自定义内容,为空或者json字符串 
  88.      */  
  89.     @Override  
  90.     public void onMessage(Context context, String message,  
  91.             String customContentString) {  
  92.         String messageString = "透传消息 message=\"" + message  
  93.                 + "\" customContentString=" + customContentString;  
  94.         Log.e(TAG, messageString);  
  95.   
  96.         // 自定义内容获取方式,mykey和myvalue对应透传消息推送时自定义内容中设置的键和值  
  97.         if (!TextUtils.isEmpty(customContentString)) {  
  98.             JSONObject customJson = null;  
  99.             try {  
  100.                 customJson = new JSONObject(customContentString);  
  101.                 String myvalue = null;  
  102.                 if (customJson.isNull("mykey")) {  
  103.                     myvalue = customJson.getString("mykey");  
  104.                 }  
  105.             } catch (JSONException e) {  
  106.                 // TODO Auto-generated catch block  
  107.                 e.printStackTrace();  
  108.             }  
  109.         }  
  110.   
  111.         // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑  
  112.         updateContent(context, messageString);  
  113.     }  
  114.   
  115.       
  116.       
  117.     /** 
  118.      * 接收通知点击的函数。注:推送通知被用户点击前,应用无法通过接口获取通知的内容。 
  119.      *  
  120.      * @param context 
  121.      *            上下文 
  122.      * @param title 
  123.      *            推送的通知的标题 
  124.      * @param description 
  125.      *            推送的通知的描述 
  126.      * @param customContentString 
  127.      *            自定义内容,为空或者json字符串 
  128.      */  
  129.     @Override  
  130.     public void onNotificationClicked(Context context, String title,  
  131.             String description, String customContentString) {  
  132.           
  133.           
  134.         String notifyString = "通知点击 title=\"" + title + "\" description=\""  
  135.                 + description + "\" customContent=" + customContentString;  
  136.         Log.e(TAG, notifyString);  
  137.   
  138.         // 自定义内容获取方式,mykey和myvalue对应通知推送时自定义内容中设置的键和值  
  139.         if (!TextUtils.isEmpty(customContentString)) {  
  140.             JSONObject customJson = null;  
  141.             try {  
  142.                 customJson = new JSONObject(customContentString);  
  143.                 String myvalue = null;  
  144.                 if (customJson.isNull("mykey")) {  
  145.                     myvalue = customJson.getString("mykey");  
  146.                 }  
  147.             } catch (JSONException e) {  
  148.                 // TODO Auto-generated catch block  
  149.                 e.printStackTrace();  
  150.             }  
  151.         }  
  152.   
  153.         // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑  
  154.         updateContent(context, notifyString);  
  155.     }  
  156.   
  157.     /** 
  158.      * setTags() 的回调函数。 
  159.      *  
  160.      * @param context 
  161.      *            上下文 
  162.      * @param errorCode 
  163.      *            错误码。0表示某些tag已经设置成功;非0表示所有tag的设置均失败。 
  164.      * @param successTags 
  165.      *            设置成功的tag 
  166.      * @param failTags 
  167.      *            设置失败的tag 
  168.      * @param requestId 
  169.      *            分配给对云推送的请求的id 
  170.      */  
  171.     @Override  
  172.     public void onSetTags(Context context, int errorCode,  
  173.             List<String> sucessTags, List<String> failTags, String requestId) {  
  174.         String responseString = "onSetTags errorCode=" + errorCode  
  175.                 + " sucessTags=" + sucessTags + " failTags=" + failTags  
  176.                 + " requestId=" + requestId;  
  177.         Log.e(TAG, responseString);  
  178.   
  179.         // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑  
  180.         updateContent(context, responseString);  
  181.     }  
  182.   
  183.     /** 
  184.      * delTags() 的回调函数。 
  185.      *  
  186.      * @param context 
  187.      *            上下文 
  188.      * @param errorCode 
  189.      *            错误码。0表示某些tag已经删除成功;非0表示所有tag均删除失败。 
  190.      * @param successTags 
  191.      *            成功删除的tag 
  192.      * @param failTags 
  193.      *            删除失败的tag 
  194.      * @param requestId 
  195.      *            分配给对云推送的请求的id 
  196.      */  
  197.     @Override  
  198.     public void onDelTags(Context context, int errorCode,  
  199.             List<String> sucessTags, List<String> failTags, String requestId) {  
  200.         String responseString = "onDelTags errorCode=" + errorCode  
  201.                 + " sucessTags=" + sucessTags + " failTags=" + failTags  
  202.                 + " requestId=" + requestId;  
  203.         Log.e(TAG, responseString);  
  204.   
  205.         // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑  
  206.         updateContent(context, responseString);  
  207.     }  
  208.   
  209.     /** 
  210.      * listTags() 的回调函数。 
  211.      *  
  212.      * @param context 
  213.      *            上下文 
  214.      * @param errorCode 
  215.      *            错误码。0表示列举tag成功;非0表示失败。 
  216.      * @param tags 
  217.      *            当前应用设置的所有tag。 
  218.      * @param requestId 
  219.      *            分配给对云推送的请求的id 
  220.      */  
  221.     @Override  
  222.     public void onListTags(Context context, int errorCode, List<String> tags,  
  223.             String requestId) {  
  224.         String responseString = "onListTags errorCode=" + errorCode + " tags="  
  225.                 + tags;  
  226.         Log.e(TAG, responseString);  
  227.   
  228.         // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑  
  229.         updateContent(context, responseString);  
  230.     }  
  231.   
  232.     /** 
  233.      * PushManager.stopWork() 的回调函数。 
  234.      *  
  235.      * @param context 
  236.      *            上下文 
  237.      * @param errorCode 
  238.      *            错误码。0表示从云推送解绑定成功;非0表示失败。 
  239.      * @param requestId 
  240.      *            分配给对云推送的请求的id 
  241.      */  
  242.     @Override  
  243.     public void onUnbind(Context context, int errorCode, String requestId) {  
  244.         String responseString = "onUnbind errorCode=" + errorCode  
  245.                 + " requestId = " + requestId;  
  246.         Log.e(TAG, responseString);  
  247.   
  248.         // 解绑定成功,设置未绑定flag,  
  249.         if (errorCode == 0) {  
  250.             PreUtils.unbind(context);  
  251.         }  
  252.         // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑  
  253.         updateContent(context, responseString);  
  254.     }  
  255.   
  256.     private void updateContent(Context context, String content) {  
  257.         Log.e(TAG, "updateContent");  
  258.         //String logText = "" + Utils.logStringCache;  
  259.   
  260. //        if (!logText.equals("")) {  
  261. //            logText += "\n";  
  262. //        }  
  263.   
  264. //        SimpleDateFormat sDateFormat = new SimpleDateFormat("HH-mm-ss");  
  265. //        logText += sDateFormat.format(new Date()) + ": ";  
  266. //        logText += content;  
  267.   
  268.         //Utils.logStringCache = logText;  
  269.   
  270.         Intent intent = new Intent();  
  271.         intent.putExtra("result", content);  
  272.         intent.setClass(context.getApplicationContext(), MainActivity.class);  
  273.         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  274.         context.getApplicationContext().startActivity(intent);  
  275.     }  
  276.   
  277. }  


代码是官方Demo的代码,注释特别详细,做了一点修改,每次回调的结果,我会让显示到主界面上。主Actvity:

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.example.zhy_baiduyun_tuisong01;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.widget.TextView;  
  8.   
  9. import com.baidu.android.pushservice.PushConstants;  
  10. import com.baidu.android.pushservice.PushManager;  
  11. import com.example.zhy_baiduyun_tuisong01.util.PreUtils;  
  12.   
  13. public class MainActivity extends Activity  
  14. {  
  15.     private TextView mTextView;  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState)  
  19.     {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.activity_main);  
  22.         initView();  
  23.   
  24.         autoBindBaiduYunTuiSong();  
  25.   
  26.     }  
  27.   
  28.     private void initView()  
  29.     {  
  30.         mTextView = (TextView) findViewById(R.id.id_textview);  
  31.     }  
  32.   
  33.     @Override  
  34.     protected void onNewIntent(Intent intent)  
  35.     {  
  36.         String result = intent.getStringExtra("result");  
  37.         if (result != null)  
  38.         {  
  39.             mTextView.setText(result);  
  40.   
  41.         }  
  42.         // super.onNewIntent(intent);  
  43.     }  
  44.   
  45.     /** 
  46.      * 如果没有绑定百度云,则绑定,并记录在属性文件中 
  47.      */  
  48.     private void autoBindBaiduYunTuiSong()  
  49.     {  
  50.         if (!PreUtils.isBind(getApplicationContext()))  
  51.         {  
  52.             PushManager.startWork(getApplicationContext(),  
  53.                     PushConstants.LOGIN_TYPE_API_KEY,  
  54.                     "TVkKGesssSDs5q7AamLGnNCs");  
  55.         }  
  56.     }  
  57.   
  58. }  


最终的测试:

 

1、应用安装后,如果绑定成功,主界面:

然后在管理控制台开始分别发送通知和消息:

2、当发送通知并点击通知:

3、当发送消息:

 

 

好了,都是最基本的功能,没什么技术含量就是需要点耐心,下面贴上源码,使用源码请把MainActivity里面的KEY设置成自己申请的KEY。

 

源码点击下载

posted @ 2016-11-29 15:59  天涯海角路  阅读(118)  评论(0编辑  收藏  举报