Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/27231237
Today, apps basically have push capabilities. So read the next Baidu Cloud push, the official documents and demo are very in place, recording the use of the process, the goal is to use Baidu cloud push the most server to write a timely communication sample ~ Of course. This is the first entry ~
1, the first step is to create a project in the Baidu Developer service Management. Then get the API key, Secret key, this process is not much to say, the officer net directly apply can, not complex.
2, download the cloud push clientsdk. The SDK's ZIP file includes a sample code, a user manual. And the required Libs and resources (in fact, directly look at the user manual and demo basic is no problem).
3, the preparation work is over, and then we will directly start the new project test
A, create a new project. Then copy the jar and so directories from the Libs in the SDK to the newly created project.
b, set the name of application in manifest to: com.baidu.frontia.FrontiaApplication
<application android:name= "com.baidu.frontia.FrontiaApplication" android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" >
If your project needs to define its own application, please refer to the relevant configuration in the user manual.
C. Increase permissions
<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.DISABLE_KEYGUARD "/> < Uses-permission android:name= "Android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android: Name= "Android.permission.ACCESS_WIFI_STATE"/>
D, add two receiver and one service (gaze marked for use)
<!--push service start--<!--to receive system messages to ensure pushservice normal execution--<receiver Android : Name= "Com.baidu.android.pushservice.PushServiceReceiver" android:process= ": Bdservice_v1" > <i ntent-filter> <action android:name= "Android.intent.action.BOOT_COMPLETED"/> <ac tion android:name= "Android.net.conn.CONNECTIVITY_CHANGE"/> <action android:name= "com.baidu.android.p Ushservice.action.notification.SHOW "/> <action android:name=" com.baidu.android.pushservice.action.me Dia. Click "/> </intent-filter> </receiver> <!--Push service receives various requests sent by the client-- <!--Note: Registrationreceiver in 2.1.1 and previous version number has a spelling error, for Registratonreceiver, use the new version number SDK when you change to such as the following code--<receiver Android:name= "Com.baidu.android.pushservice.RegistrationReceiver" android:process= ": Bdservice_v1" > <intent-filter> <action android:name= "Com.baidu.android.pushservice.action.METHOD"/> &L T;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> <!--Push Service -<!--Note: The version number after 4.0 (including) must be added to the Intent-filter action---<service android:name as seen below = "Com.baidu.android.pushservice.PushService" android:exported= "true" android:process= ": Bdservice_v1" > <intent-filter> <action android:name= "Com.baidu.android.pushservice.action.PUSH_S Ervice "/> </intent-filter> </service> <!--push service end--
E, we need to implement a receiver by ourselves. To receive push messages, interface call callbacks, and notification click events.
<receiver android:name= "Com.example.zhy_baiduyun_tuisong01.receiver.MyPushMessageReceiver" > < Intent-filter> <!--receive push messages-- <action android:name= " Com.baidu.android.pushservice.action.MESSAGE "/> <!--receive the return results of BIND, settags, etc.-- <action Android:name= "Com.baidu.android.pushservice.action.RECEIVE"/> <!--optional. Accept notification Click events, and notify yourself of definition Content- <action android:name= "Com.baidu.android.pushservice.action.notification.CLICK"/ > </intent-filter> </receiver>
Code:
Package Com.example.zhy_baiduyun_tuisong01.receiver;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;import Com.example.zhy_baiduyun_ Tuisong01. Mainactivity;import com.example.zhy_baiduyun_tuisong01.util.preutils;/** * Push message processing receiver. Please write the callback function you need. Generally speaking: Onbind is required to handle the startwork return value; * OnMessage is used to receive a pass-through message; Onsettags, Ondeltags, and onlisttags are callbacks for tag related operations. * Onnotificationclicked callback when the notification is clicked; Onunbind is the return value of the Stopwork interface callback * * ErrorCode in the return value. Explanations such as the following: * 0-success * 10001-network problem * 30600-internal Server Error * 30601-method not allowed * 3060 2-request Params not Valid * 30603-authentication Failed * 30604-quota use up Payment Required * 30605-data R equired not Found * 30606-request time Expires Timeout * 30607-channel Token Timeout * 30608-bind Relation not Found * 30609-bind Number Too Many * * When you encounter the above return error, assuming that your problem cannot be explained, please contact us with the return value of the same request RequestID and errorcode to track down the problem. * */public class Mypushmessagereceiver extends Frontiapushmessagereceiver {/** TAG to Log */public static final S Tring TAG = Mypushmessagereceiver.class. Getsimplename (); /** * After calling Pushmanager.startwork, the SDK will initiate a bind request to the push * server, which is asynchronous.The result of the binding request is returned by Onbind. Suppose you need to use unicast push. You need to upload the channel * ID and User ID obtained here to the application server, and then call the server interface to push with the channel ID and user ID to a single phone or to users. * * @param context * broadcastreceiver Execution context * @param errorCode * Binding interface return value, 0- * @param AppID * App ID. ErrorCode non 0 o'clock is null * @param userId * Applies the user ID.
ErrorCode non 0 o'clock is null * @param Channelid * applies channel ID.
ErrorCode non 0 o'clock is null * @param RequestID * Request ID initiated to the server.
Practical in tracing problems; * @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=" + requ Estid; LOG.E (TAG, responsestring); Bind successfully, set the bound flag, can effectively reduce the unnecessary binding request if (ErrorCode = = 0) {preutils.bind (context); }//Demo update interface to show the code. Application please add your own processing logic here updatecontent (context, responsestring); }/** * A function that receives a pass-through message. * * @param context * @param message * Push messages * @param customcontentstring * Self-defined content, empty or JSON string */@Override public void onMessage (context context, string message, String customcontentstring) {string messagestring = "Pass message message=\" "+ Message +" \ "customcontentstring= "+ customcontentstring; LOG.E (TAG, messagestring); Define your own content acquisition method, MyKey and myvalue the corresponding pass-through message pushes when you define the key and value set in the content 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.printstacktrac E (); }}//Demo update interface to show the code, application please add your own processing logic here updatecontent (context, messagestring); /** * The function that receives the notification click. Note: Push notifications are pre-clicked by the user. The app cannot get the content of the notification through the interface. * * @param context * Contextual * @param title * Push Notification Header * @param description * Descriptive narrative of push notifications * @param customcontentstring * Own definition content, empty or JSON string */@OVerride public void onnotificationclicked (context context, string title, string description, String Customco ntentstring) {String notifystring = "Notification click title=\" "+ title +" \ "description=\" "+ Descrip tion + "\" customcontent= "+ customcontentstring; LOG.E (TAG, notifystring); Define how you get your content. MyKey and myvalue the corresponding notifications when pushing the keys and values set in their own definition content 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.printstacktrac E (); }}//Demo update interface to show the code. Application please add your own processing logic here updatecontent (context, notifystring); }/** * Settags () callback function. ** @param context * @param errorCode * error code.
0 indicates that some of the tags have been set successfully; Not 0 indicates that all tags are set to fail. * @param successtags * Set the successful tag * @param failtags * Set the failed tag * @param RequestID * ID assigned to cloud PUSH request */@Override public void onsettags (context context, int errorCode, LIST< ; String> sucesstags, list<string> failtags, String requestid) {string responsestring = "Onsettags errorCod E= "+ ErrorCode +" sucesstags= "+ sucesstags +" failtags= "+ failtags +" requestid= "+ RE Questid; LOG.E (TAG, responsestring); Demo Update interface shows code. Application please add your own processing logic here updatecontent (context, responsestring); }/** * Deltags () callback function. * * @param context * @param errorCode * error code. 0 indicates that some tags have been deleted successfully, and not 0 means that all tags are deleted. * @param successtags * Successfully deleted tag * @param failtags * Delete failed tag * @param RequestID * ID assigned to the Cloud push request */@Override public voiD ondeltags (context context, int errorCode, list<string> sucesstags, list<string> failtags, String RequestID) {String responsestring = "Ondeltags errorcode=" + ErrorCode + "sucesstags=" + Sucesstag S + "failtags=" + failtags + "requestid=" + RequestID; LOG.E (TAG, responsestring); Demo Update interface shows code. Application please add your own processing logic here updatecontent (context, responsestring); }/** * Listtags () callback function.
* * @param context * @param errorCode * error code. 0 indicates that the tag was successfully listed. A non-0 indicates a failure. * @param tags * All tags of the current app settings.
* @param RequestID * ID assigned to the Cloud push request */@Override public void onlisttags (context context, int error Code, list<string> tags, string requestid) {string responsestring = "Onlisttags errorcode=" + Err Orcode + "tags=" + tags; LOG.E (TAG, responsestring); Demo Update interface shows code. Application please add your own processing logic here updatecontent (context, responsestring); }/** * Pushmanager.stopwork () callback function.
* * @param context * @param errorCode * error code.
0 indicates the success of the push-pull solution from the cloud. A non-0 indicates a failure. * @param RequestID * ID assigned to the Cloud push request */@Override public void Onunbind (context context, int Errorco DE, String RequestID) {string responsestring = "Onunbind errorcode=" + ErrorCode + "RequestID =" + RequestID; LOG.E (TAG, responsestring); Unbind successfully, set unbound flag, if (ErrorCode = = 0) {preutils.unbind (context); }//Demo update interface display code, application please add your own processing logic here updatecontent (context, responsestring); } private void Updatecontent (context context, String content) {LOG.E (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.putexTRA ("result", content); Intent.setclass (Context.getapplicationcontext (), mainactivity.class); Intent.addflags (Intent.flag_activity_new_task); Context.getapplicationcontext (). StartActivity (Intent); }}
The code is the official demo code, staring particularly specific. Made a little change to the result of each callback. I will let the display to the main interface.
Main actvity:
Package Com.example.zhy_baiduyun_tuisong01;import Android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.util.log;import Android.widget.textview;import Com.baidu.android.pushservice.pushconstants;import Com.baidu.android.pushservice.pushmanager;import Com.example.zhy_baiduyun_tuisong01.util.preutils;public class Mainactivity extends Activity{private TextView Mtextview; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initview (); Autobindbaiduyuntuisong ();} private void Initview () {Mtextview = (TextView) Findviewbyid (R.id.id_textview);} @Overrideprotected void Onnewintent (Intent Intent) {String result = Intent.getstringextra ("result"); if (result! = null) { Mtextview.settext (result);} Super.onnewintent (intent);} /** * Assumes that there is no bound Baidu cloud, then bind, and record in the properties file */private void Autobindbaiduyuntuisong () {if (! Preutils.isbind (Getapplicationcontext ())) {Pushmanager.startwork (Getapplicationcontext (), PuShconstants.login_type_api_key, "Tvkkgessssds5q7aamlgnncs");}}}
Finally the test:
1, after the application installation. Assuming the binding succeeds, the main interface:
Then, in the admin console, you start sending notifications and messages separately:
2. When sending notifications and clicking notifications:
3. When sending a message:
All right. is the main function, there is no technical content is the need to point patience. Paste the source code below. To use the source code, please set the key inside the mainactivity as your application key.
Source code click to download
Android push Baidu Cloud Push introduction