Android Development Note (104) Message Push SDK

Source: Internet
Author: User
Tags aliases getmessage time in milliseconds xml example

Push integration common concept push: from the server to send messages to the client app in real time, which is push, push can be used to send system notifications, send referral information, send chat messages and so on.
Aliases: Used to give mobile devices a good name to remember, such as the computer has a computer name, you can interpret the alias as a developer to the transfer device nickname. However, multiple mobile devices can have the same alias, and the devices will receive messages to that alias at the same time.
Tags: used to label mobile devices, can be understood as a classification, such as the supermarket in the Thai rice can be labeled "Food products", you can also hit the "Imported goods" label. The server can send messages uniformly to a certain kind of mobile device, and if the mobile device is tagged with the mobile phone number of the device, the server will be able to send messages separately for that number.
Custom message: The content of the push message is generally displayed directly in the system's notification bar by the SDK, but sometimes we want to control the timing of the presentation of notifications, such as pre-processing a transaction, or displaying Messages in a dialog box, and in these cases, custom messages come in handy. The app can receive a custom message from the server and then choose the next processing logic autonomously.


The integration Step Push SDK is divided into two blocks: client and server, the developer integrates the Client SDK on the client app, and integrates the service-side SDK on the servers ' programs. However, the push client does not communicate directly with the server SDK, which must be brokered by the push-to-vendor push servers. Here is the process of data flow when pushing SDK integration:
1, after the application of the Integrated Client SDK is started, the initialization (registration) operation is initiated, that is, the client SDK sends the initialization request (including Appkey, Master secret) to the push server (the push vendor), and the push server assigns a unique identity to the mobile device.
2, the Client SDK sends the alias and tag settings to the push server, and pushes the server to register the appropriate aliases and tags for the mobile device.
3. The Client SDK sends an open push request to the push server and pushes the server to indicate that you know it, and then I will tell you if there is a message.
4, the service-side SDK encapsulates the message push request, including Appkey, Master secret, alias, tag, push content and so on information.
5, the service-side SDK sends a message push request to the push server, the push server first verifies whether the Appkey and master secret are legal, and then selects the client device collection which needs to receive the notification according to the aliases and tags, and finally pushes the content onto the eligible client devices.


Aurora Push Aurora Push is a high-volume push SDK that supports iOS, Android, Winphone, and other platforms. The Client SDK package for the Aurora push is Jpush-android-2.1.5.jar, the service-side SDK package is Jpush-client-3.2.9.jar, and the server-side SDK also relies on jar packages such as Gson, SLF4J, log4j, and so on.


The push-call interface enables Aurora push on the app, with the Jpushinterface class, and here's a general description of how Jpushinterface:
Init: Initialize. Can be called in mainapplication or mainactivity.
Stoppush: Pause to receive notifications.
Resumepush: Resumes receiving notifications.
ispushstopped: Determine if push stops
Getregistrationid: Gets the registration ID.
Setaliasandtags: Sets the alias and tag for this device. If the server specifies to push a message to a mobile phone number, the app calls the method to set the phone number as an alias or tag.
Setalias: Sets the alias.
Settags: Sets the tag.
Clearallnotifications: Clears all notifications.
Setpushnotificationbuilder: Sets the notification bar style. A type of 1 means that a basic style is used, and a custom style is used for 2.
Setpushtime: Sets the time period to receive notifications. You can set the start time and end time of the day from Monday to Sunday.


Push events broadcast the events of the Aurora push are broadcast by radio and do not use listeners, so we want to customize the broadcast receivers in the app to handle events. Here are a few common event descriptions for Aurora push:
1, jpushinterface.action_registration_id
Represents the event that registered the SDK, the corresponding Intent-filter is <action android:name= "Cn.jpush.android.intent.REGISTRATION"/>
2, jpushinterface.action_message_received
Represents an event that receives a custom message, and the corresponding Intent-filter is <action android:name= "Cn.jpush.android.intent.MESSAGE_RECEIVED"/>
3, jpushinterface.action_notification_received
Represents the event that receives the notification, the corresponding Intent-filter is <action android:name= "Cn.jpush.android.intent.NOTIFICATION_RECEIVED"/>
4, jpushinterface.action_notification_opened
Indicates the event of clicking on the notification bar, the corresponding Intent-filter is <action android:name= "Cn.jpush.android.intent.NOTIFICATION_OPENED"/>
5, Jpushinterface.action_richpush_callback
Represents an event that receives a callback for rich text (such as Web pages, multimedia, and so on), and the corresponding Intent-filter is <action android:name= "cn.jpush.android.intent.ACTION_RICHPUSH_ CALLBACK "/>
6, Jpushinterface.action_connection_change
Represents the event of a network connection change (connect up, disconnect), the corresponding Intent-filter is <action android:name= "Cn.jpush.android.intent.CONNECTION"/>


The following is an example of an XML registered Aurora broadcast receiver in Androidmanifest.xml:
    <receiver        android:name= ". Jpushreceiver "        android:exported=" false "        android:enabled=" true ">        <intent-filter>            < Action android:name= "Cn.jpush.android.intent.REGISTRATION"/>            <action android:name= " Cn.jpush.android.intent.MESSAGE_RECEIVED "/>            <action android:name=" Cn.jpush.android.intent.NOTIFICATION_RECEIVED "/>            <action android:name=" Cn.jpush.android.intent.NOTIFICATION_OPENED "/>            <action android:name=" cn.jpush.android.intent.ACTION_ Richpush_callback "/>            <action android:name=" Cn.jpush.android.intent.CONNECTION "/>            < Category android:name= "Com.example.exmpushjpush"/>        </intent-filter>    </receiver>


The server sends the Notification app code realizes the client receives the push the function, next also has the server to cooperate, the server's program sends the push message, the client app receives the message.
Here's how the server sends the message:
1. Constructs a Jpushclient object that contains the following information: AppKey, Master Secret, retries, and time-out parameters.
2. Generate platform platform objects, audience audience objects, notification notification objects, message custom message objects, respectively, according to the parameters.
3, according to the object produced in the second step, constructs the Pushpayload object.
4. Call the Sendpush method of the Jpushclient object to send the Pushpayload object information.
5, the Sendpush method call fails to throw an exception, the call succeeds returns the Pushresult result object, which contains the message number of this send.


The Pushpayload object of step three above is the key to the whole sending process, the object is built using the builder mode, and the parameters are set by Pushpayload.builder, which are described as follows:
Setplatform: Sets the message receiving platform. There are three main types, namely: Platform.ios (), platform.android (), Platform.winphone ().
Setaudience: Sets the message acceptance group. There are three main audiences, Audience.all () represents all users, Audience.alias (alias) represents the user who specified the alias, and Audience.tag (tag) represents the user who specified the tag.
Setnotification: Sets the notification content. According to different platform there are three kinds of setup methods, respectively: Notification.ios, Notification.android, Notification.winphone.
Setmessage: Sets a custom message. Note that only Android and Winphone can set a custom message, and iOS can only set notifications.
Build: Builds the Pushpayload object based on the content of the setting.


The following is a sample code for sending notifications to the server:
Import Cn.jpush.api.jpushclient;import Cn.jpush.api.common.clientconfig;import Cn.jpush.api.common.resp.apiconnectionexception;import Cn.jpush.api.common.resp.apirequestexception;import Cn.jpush.api.push.pushresult;import Cn.jpush.api.push.model.message;import Cn.jpush.api.push.model.Platform; Import Cn.jpush.api.push.model.pushpayload;import Cn.jpush.api.push.model.audience.audience;import Cn.jpush.api.push.model.notification.notification;import Java.util.map;import Java.util.Set;public Class Messagepush {public static long IOS = 0l;public static Long Android = 1l;private string Mtitle;private string Mmessage;pri Vate long mplatformtype;private jpushclient mjpushclient;private Platform mplatform;private audience mAudience;private Notification mnotify;private Message mmsg;public long mmsgid;public string Mstatus;public string Merrcode;public string m Errmsg;public Messagepush (String AppKey, String Mastersecret, String message) {ClientConfig conf = Clientconfig.getinstance (); Conf.setmaxretRytimes (3); mjpushclient = new Jpushclient (Mastersecret, AppKey, NULL, conf); mmessage = Message;mtitle = ""; mplatform = Pla Tform.all (); mmsg = Message.content (Message); maudience = Audience.all (); setmsg ( -1l, 0, 0, "");} Public Messagepush (String AppKey, String Mastersecret, String message, string title) {This (AppKey, Mastersecret, message) ; mtitle = title;} Public Messagepush (String AppKey, String Mastersecret, String message,string title, Long platformtype, map<string, STR Ing> Extras) {This (AppKey, Mastersecret, message, title); Mplatformtype = Platformtype.longvalue (); System.out.println ("Messagepush platformtype=" + platformtype); if (platformtype.longvalue () = = IOS) {Mplatform = Platform.ios (); mnotify = Notification.ios (mmessage, extras);} else if (platformtype.longvalue () = = Android) {mplatform = Platform.android (); mnotify = Notification.android (Mmessage, Mtitle, extras);} else {mplatform = Platform.winphone (); mnotify = Notification.winphone (mmessage, Extras);}} public void Setalias (SEt<string> alias) {maudience = Audience.alias (alias);} public void Settag (string[] tag) {maudience = Audience.tag (tag);} public void Sendpush () {pushpayload payload = build (); try {pushresult result = Mjpushclient.sendpush (payload); Mmsgid = Res ult.msg_id; System.out.println ("Got result-" + result); catch (Apiconnectionexception e) {System.out.println ("Connection error. Should retry later. "+ e.getmessage ()); Setmsg ( -1l,-1,-1, E.getmessage ());} catch (Apirequestexception e) {System.out.println ("HTTP Status:" + e.getstatus ()); System.out.println ("Error Code:" + e.geterrorcode ()); System.out.println ("Error Message:" + e.geterrormessage ()); System.out.println ("MSG ID:" + e.getmsgid ()); Setmsg (E.getmsgid (), E.getstatus (), E.geterrorcode (), E.geterrormessage ());}} private void Setmsg (long msgId, int status, int errcode, String errmsg) {mmsgid = Msgid;mstatus = string.valueof (status); m Errcode = string.valueof (errcode); merrmsg = errmsg;} Private Pushpayload Build () {System.out.println ("BuilD platformtype= "+ Mplatformtype); Pushpayload push;if (Mplatformtype = = IOS) {push = Pushpayload.newbuilder (). Setplatform (Mplatform). Setaudience ( maudience). Setnotification (mnotify). build ();} else if (Mplatformtype = = Android) {push = Pushpayload.newbuilder (). Setplatform (Mplatform). Setaudience (maudience). Setmessage (mmsg). build ();//.setaudience (maudience). Setnotification (mnotify). build ();} else {push = Pushpayload.newbuilder (). Setplatform (Mplatform). Setaudience (maudience). Setmessage (mmsg). build ();} return push;}}


Push-Push is another push SDK that uses more, supports iOS and Android, but does not support Winphone, but the server, in addition to Java, supports PHP, Python, C + +, C #, and so on. Push the Client SDK package for Getuisdk2.8.1.0.jar and Getuiext-2.0.3.jar, the Server SDK package is Gexin-rp-sdk-base-4.0.0.7.jar, Gexin-rp-sdk-http-4.0.1.2.jar and Gexin-rp-sdk-template-4.0.0.4.jar, the SDK for the server also relies on jar packages such as Commons, Jackson, and Protobuf.


Push calls to the interface in the app to enable a push, using the Pushmanager class, the following is the common method of Pushmanager:
GetInstance: Get a single case of Pushmanager.
Initialize: Initialize.
Turnonpush: Turn on push.
Turnoffpush: Turn off push.
Ispushturnedon: Determines whether the push is on or off.
Getclientid: Gets the client ID.
Settag: Sets the label.
Bindalias: Bind alias.
Unbindalias: Unbind aliases.
Setsilenttime: Sets the quiet time period. That is, from a few points to the points do not receive notifications.


Broadcast tweets for push events also use broadcasts to send events, although many events are not broken down like Aurora, and custom broadcast receivers are required. Here are a few of the frequently used event introductions:
Event types are differentiated according to Bundle.getint (pushconsts.cmd_action)
1, Pushconsts.get_clientid: Obtain the client ID. is actually registered, equivalent to the Aurora jpushinterface.action_registration_id
2, Pushconsts.get_msg_data: Receive custom message. Equivalent to the Aurora jpushinterface.action_message_received


The following is an XML example of registering a promotional broadcast receiver in Androidmanifest.xml:
        <receiver            android:name= ". Gexinreceiver "            android:exported=" false ">            <intent-filter>                <action android:name=" Com.igexin.sdk.action. Apply the assigned AppID value "/>            </intent-filter>        </receiver>


Server send notification The following are the specific steps that the server sends a message:
1. Constructs a Igtpush object that contains the following information: Push server address, AppKey, Master Secret.
2, according to the parameters to generate Templates template object, Appconditions condition object, AppID queue and so on.
3, according to the object produced in the second step, constructs the Appmessage object.
4. Call the Pushmessagetoapp method of the Igtpush object to send the Appmessage object information.
5, the Pushmessagetoapp method call fails to throw an exception, the call succeeds returns the Ipushresult result object, which contains the result information of this send.


The Appmessage object above step three is the key to the entire sending process, and the common methods for that object are described below:
Setappidlist: Sets the AppID queue. That is, the user who binds to which AppID sends the message.
Setconditions: Sets the condition information. Includes phone type, area, label, etc.
SetData: Sets the template data. Template templates define the specific style of the message, and here are a few common templates that are packaged well:
--notificationtemplate: Notification template. Automatically display the message in the notification bar, click to jump to the app home page. The template corresponds to the notification of the aurora.
--transmissiontemplate: Pass-through template. The notification bar is not automatically displayed and is handled by the developer on its own in the Pushconsts.get_msg_data branch of the broadcast receiver. The template corresponds to the Aurora message.
--linktemplate: Link template. Automatically display the message in the notification bar, click to jump to the specified URL.
--notypoploadtemplate: Download the prompt template. Automatically display the message in the notification bar, click to download the specified installation package.


The following is a sample code for sending notifications to the server:
Import Java.util.arraylist;import Java.util.list;import Com.gexin.rp.sdk.base.ipushresult;import Com.gexin.rp.sdk.base.impl.appmessage;import Com.gexin.rp.sdk.base.uitls.appconditions;import    Com.gexin.rp.sdk.http.igtpush;import Com.gexin.rp.sdk.template.notificationtemplate;public class PushtoAppNotify {    With the Java SDK QuickStart, and the application configuration obtained in the second step of obtaining access credentials, the user can replace the private static String appId = "Fj9unm6wks8lais3c05w9";    private static String AppKey = "Cpv7grk6ilao26adzgmti1"; private static string Mastersecret = "qsvowgnx0e9jempixtqj39"; static string host = "http://sdk.open.api.igexin.com/    Apiex.htm ";        public static void Main (string[] args) throws Exception {Igtpush push = new Igtpush (host, AppKey, Mastersecret);        Notificationtemplate template = Notificationtemplatedemo ();        Appmessage message = new Appmessage ();        Message.setdata (template);        Message.setoffline (TRUE);        Offline active time in milliseconds, selectable message.setofflineexpiretime (24 * 1000 * 3600); PushThe conditions appconditions CDT = new Appconditions () are required for the target user to be satisfied with the app;        list<string> appidlist = new arraylist<string> ();        Appidlist.add (APPID);        Message.setappidlist (appidlist);        Phone type list<string> phonetypelist = new arraylist<string> ();        Province list<string> provincelist = new arraylist<string> ();        Custom tag list<string> tagList = new arraylist<string> ();        Cdt.addcondition (Appconditions.phone_type, phonetypelist);        Cdt.addcondition (Appconditions.region, provincelist);        Cdt.addcondition (appconditions.tag,taglist);         Message.setconditions (CDT);        Ipushresult ret = push.pushmessagetoapp (message, "task alias _toapp");    System.out.println (Ret.getresponse (). toString ());  } public static Notificationtemplate Notificationtemplatedemo () throws Exception {notificationtemplate template        = new Notificationtemplate ();        Template.setappid (APPID); TempLate.setappkey (AppKey);        Template.settitle ("pushtoappnotify title");        Template.settext ("pushtoappnotify content");        Template.setlogo ("Icon.png");        Template.setlogourl ("");        Template.setisring (TRUE);        Template.setisvibrate (TRUE);    Template.setisclearable (TRUE);    Pass-through message settings, 1 to force start the app, the client receives the message will start the application immediately, 2 to wait for the application to launch Template.settransmissiontype (1);        Template.settransmissioncontent ("Pushtoappnotify Please enter the content you want to pass through");    return template; } public static class Notificationtemplatedemo {public static notificationtemplate Notificationtemplatedemo (Str        ing appId, String appkey) {notificationtemplate template = new Notificationtemplate ();        Set AppId and Appkey template.setappid (appId);        Template.setappkey (Appkey);        Set the notification bar title and content Template.settitle ("Please enter the Notification bar title");        Template.settext ("Please enter the contents of the Notification Bar");        Configure the Notification bar icon Template.setlogo ("Icon.png");        Configure the Notification Bar Network icon Template.setlogourl (""); Set whether notifications are ringingBell, vibrate, or can be cleared template.setisring (true);        Template.setisvibrate (TRUE);        Template.setisclearable (TRUE);        Pass-through message settings, 1 to force start the app, the client receives the message will start the application immediately, 2 to wait for the application to launch Template.settransmissiontype (1);        Template.settransmissioncontent ("Please enter the content you want to pass through");        Set timing display Time//template.setduration ("2015-01-16 11:40:00", "2015-01-16 12:24:00");    return template; }        }}




Click here to view the full list of Android development notes

Android Development Note (104) Message Push SDK

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.