Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/27231237
Now the app basically has the push function, then looked under the Baidu cloud push sends, the official document and the demo are very in place, records the use process, the goal is uses the Baidu cloud pushes the most server to write a timely communication example ~ Of course, this is the first entry ~
1, the first step is to create a project in the Baidu Developer service Management, and then get the API key, Secret key, the process is not much to say, the officer net directly apply on the line, not complicated.
2, download the Cloud push client Sdk,sdk compressed file contains an example code, a user manual, and the required libs and resources, etc. (actually directly look at the user manual and demo basically no problem).
3, the preparation work is over, then we will directly start the new project test
A. Create a new project and copy the jar and so folders in the SDK Libs to the new 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 requires a custom application, please refer to the relevant configuration in the user manual.
C. Add 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 a service (note indicating the usefulness)
<!--push service start--<!--to receive system messages to ensure pushservice uptime--<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--&L t;! --Note: Registrationreceiver in 2.1.1 and previous version of the spelling error, for Registratonreceiver, with the new version of the SDK, please change to the following code--<receiver A Ndroid:name= "Com.baidu.android.pushservice.RegistrationReceiver" android:process= ": Bdservice_v1" > <intent-filter> <action android:name= "Com.baidu.android.pushservice.action.METHOD"/> <actio n android:name= "Com.baidu.android.pushservice.action.BIND_SYNC"/> </intent-filter> <int ent-filter> <action android:name= "Android.intent.action.PACKAGE_REMOVED"/> <dat A android:scheme= "package"/> </intent-filter> </receiver> <!--Push Service-- <!--Note: The Version after 4.0 (inclusive) should be added as shown below intent-filter action---<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> <!--push service end-
E, we need to implement a receiver 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 notifications custom 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 necessary to handle the Startwork return value; * OnMessage is used to receive the 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, explained as follows: * 0-success * 10001-network Pro Blem * 30600-internal Server Error * 30601-method not allowed * 30602-request Params not Valid * 30603-authen Tication Failed * 30604-quota use up Payment Required * 30605-data Required not Found * 30606-request time EXP Ires Timeout * 30607-channel Token timeout * 30608-bind Relation not Found* 30609-bind Number Too Many * * When you encounter the above return error, if you do not explain your problem, please use the return value of the same request RequestID and errorcode contact us 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. If 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 mobile phone or 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. useful 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=" + RequestID; 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 display code, application please add your own processing logic updatecontent (context, responsestring); }/** * A function that receives a pass-through message. * * @param context * @param message * Push messages * @param customcontentstring * Custom content, empty or JSON string */@Override public void onMessage (context context, string message, String customcontentstring) {string messagestring = "Pass message message=\" "+ Message +" \ "Customconte ntstring= "+ customcontentstring; LOG.E (TAG, messagestring); Custom content acquisition methods, MyKey and myvalue correspond to the keys and values set in the custom content when the pass-through message is pushed (! 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 updatecontent (context, messagestring); /** * The function that receives the notification click. Note: The app cannot get the content of the notification through the interface until the push notification is clicked by the user. * * @param context * Contextual * @param title * Push Notification Header * @param description * Description of the PUSH notification * @param customcontentstring * Custom content, empty or JSON string */@Override public void Onnotificationclicked (context context, string title, string description, String customcontentstring) { String notifystring = "Notification click title=\" "+ title +" \ "description=\" "+ description +" \ "customcontent= "+ customcontentstring; LOG.E (TAG, notifystring); Custom content acquisition methods, MyKey and myvalue correspond to the keys and values set in the custom content when the notification is pushed (!). 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 updatecontent (context, notifystring); }/** * Settags () callback function. * * @param context * @param errorCode * error code. 0 indicates that some tags have been set successfully, and not 0 indicates that all tag settings fail. * @param successtags * Set the successful tag * @param failtags * Set the failed tag * @param RequestID * Assigned to the cloud push request 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.E (TAG, responsestring); Demo Update interface display code, application please add your own processing logic updatecontent (context, responsestring); }/** * Deltags () callback function. * * @param context * @param errorCode * error code. 0 indicates that some tags have been deleted successfully, and not 0 indicates that all tags are deleted. * @param successtags * Successfully deleted tag * @param failtags * Delete failed tag * @param RequestID * ID assigned to 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=" + sucesstags + "failtags=" + failtags + "requestid=" + reques TId; LOG.E (TAG, responsestring); Demo Update interface display code, application please add your own processing logic updatecontent (context, responsestring); }/** * Listtags () callback function. * * @param context * @param errorCode * error code. 0 indicates that the tag is successful; not 0 indicates 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 display code, application please add your own processing logic updatecontent (context, responsestring); }/** * PUSHMThe callback function for Anager.stopwork (). * * @param context * @param errorCode * error code. 0 indicates success from cloud push, non-0 indicates 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 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, the comments are particularly detailed, make a little change, 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);} /** * If not bound to 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");}}}
The final test:
1, after the application installation, if the binding is successful, the main interface:
Then start sending notifications and messages separately in the admin console:
2. When sending notifications and clicking notifications:
3. When sending a message:
Well, all is the most basic function, no technical content is to need a bit of patience, the following paste the source code, use the source code please mainactivity inside the key set to their own application key.
SOURCE Click to download