Android apps typically use the background to poll the server for information, while iOS apps stop running after being switched to the background for a while, and if you want to get access to the information you can only rely on APNs (Apple Push Notification Service), Push is initiated by the server. APNs principle and Token acquisition method on-line search a lot of, here is mainly about Java APNs Class library Notnoop.
The core class in Notnoop is that Apnsservice and Payloadbuilder,apnsservice can send requests to the server, and a common server host is available in Apnsservicebuilder. The creation of a apnsservice can be accomplished by following a few simple lines of code:
P12 file path string keypath = "E:/PUSHTEST.P12";//p12 file key string password = "111111";//Create a APNs serviceapnsservice service = Apns.newservice (). Withcert (keypath, password)//Use the specified P12 file and key. Withsandboxdestination ()//Use Apple's test server. Build ();
Payloadbuilder can help developers easily create a JSON that conforms to the APNS specification, for example:
Create a message string payload = Apns.newpayload (). Alertbody ("Hello world!") The text that is displayed by the push notification. Sound ("Default")//voice prompts that are included with the push. Badge (1)//The number that appears in the upper-right corner of the application icon. build ();
Finally, just call the service's push method to push the message to the iOS device:
Token is fetched by the client string token = "45124a4cf9f5e272d395f6392456e5ab7185d2ae6e98ba2f8426fe09f60e785b";// Send message to iOS device Service.push (token, payload);
Localized strings can be used because APNs supports up to 256 bytes of message body, and a large amount of duplicate content in a push message can also cause traffic costs. A localized string is a pair of key-value pairs defined in the Localizable.strings file in the client, and the server only needs to provide a key for the specified string and dynamically generated parameters to generate a complete push message, for example:
Localizable.strings defines "focus" = "%@ concerns You" list<string> args = new ArrayList (); Args.add ("Zhang San"); String payload = Apns.newpayload (). Localizedkey ("focus")//localized string of key.localizedarguments (args)//dynamically generated parameters. Build (); Service.push (token, payload);//Push results: Zhang San focus on you.
Finally, not every message will definitely be pushed successfully. For example, when the user unloads the app, the token is invalidated, and the service's Getinactivedevices method is used to obtain the token that is invalidated and handle it.
[Java Web] Java's APNs class library Notnoop