Android Background information push research

Source: Internet
Author: User
Tags readfile android push notification

Android Background information push research

Objective

We have developed an application, called a application, similar to the weather weather. Now the task is if these a application has a new version, or the weather is worse, to timely push the message on the phone, suggesting that new applications can be updated, and the weather will be changed, to remind users to pay attention to the situation. And the need to implement a message push mechanism.

Push Mode Basics

There are generally two ways to get information about updates on the server that are not timed: the first is the way the client uses pull, which is to get information from the server at a time and see if there is any updated information. The second is the way the server uses push (push), when new information is available on the server side, push the latest information to the client. This allows the client to automatically receive the message.

While pull and push two ways to get server-side update information, it is obvious that push is more advantageous than pulling mode. Because the pull way more than the client's network traffic, the main is the charge, but also need our program constantly to monitor the changes in the server.

When developing Android and iphone applications, we often need to instantly push various notification messages from the server to the mobile client. We only need to pull down at the notification bar of Android or iphone to expand the notification Panel to focus on a variety of notification messages. There are now simple and perfect push notification solutions on the iOS platform, but the Android platform is relatively cumbersome to implement.

Current programme Rollup 1. Scenario One: C2DM Cloud push function--google official

On the Android phone platform, Google provides C2DM (cloudto Device Messaging) services, and at first I was ready to use the service to implement the push feature on my phone and bring it into my project.

Android Cloud to Device Messaging (C2DM) is a service that helps developers send data from a server to an Android application. The service provides a simple, lightweight mechanism that allows the server to notify the mobile application to communicate directly with the server to obtain application updates and user data from the server. The C2DM service is responsible for processing transactions such as Message Queuing and distributing these messages to applications running on the target device.

The following is an example diagram of the C2DM operation process:


Figure 1 C2DM Operation Process Example diagram

After some research, this service has a lot of problems:

1) The C2DM is built into Android's 2.2 system and cannot be compatible with the old 1.6 to 2.1 system;

2) C2DM need to rely on Google's official C2DM server, due to the domestic network environment, this service is often not available, if you want to use it well, our appserver must also be abroad, this is not every developer can be achieved;

3) Unlike on the iphone, they integrate the hardware system into one piece. So for our developers, if we want to use C2DM push in our application, because of the different hardware vendors platform, such as Motorola, Huawei, ZTE do a mobile phone, they may be Google's services to remove, especially as in the domestic many such, Get rid of this native service from Google. Buying something like a cottage or a Huawei-made machine, Google's services may not be available. And things like those out there might be built in.

2. Scenario two: Using the MQTT protocol, broker is acting as a proxy server

MQTT is a lightweight message publishing/subscription protocol that is the ideal solution for implementing a messaging push server based on a mobile client. However, as the number of users increases this scheme will be problematic, because the broker has an upper limit of connections, to a certain extent, can not connect, which makes the message difficult to send out.

In short, the number of connections is limited.


Figure 2 Mqtt Protocol architecture diagram

3. Scenario Three: XMPP protocol for Android push function

Based on the XMPP protocol, many people recommend this, Google's official C2DM is also based on the development of XMPP, using this program will not rely on the Android system, and do not rely on Google server.

In fact, Google's official C2DM server is also packaged using the XMPP protocol. XMPP (Extensible Communication and Presentation Protocol) is an Extensible Markup Language (XML)-based protocol that is used for instant messaging (IM) and online probing. The agreement may eventually allow Internet users to send instant messages to anyone else on the Internet. ANDROIDPN is a Java open source Android push notification implementation based on the XMPP protocol. It contains the full client and server side.

The ANDROIDPN implementation intent is as follows:


Figure 3 ANDROIDPN Implementation Intent

The ANDROIDPN client needs a Java-based open source XMPP protocol package Asmack, which is also based on another open source project smack under OpenFire, but we don't need to compile it ourselves, The ANDROIDPN client can be used directly inside the Asmack.jar. The client uses the Xmppconnection class provided in Asmack to establish a persistent connection with the server, and the user registers and authenticates through the connection, as well as the notification sent by the server via this connection.

The ANDROIDPN server is also implemented in the Java language, based on the OpenFire Open source project, but its Web Part uses the spring framework, which is different from OpenFire. The ANDROIDPN server contains two parts, one is the XMPP service that listens on 5222 ports, is responsible for communicating with the client's Xmppconnection class, the role is user registration and authentication, and sends a push notification message. The other part is the Web server, which uses a lightweight HTTP server that is responsible for receiving Web requests from users. The server architecture is as follows:


Figure 4 Androidpn pushnotification Service

The top layer contains four components, namely Sessionmanager,auth Manager,presencemanager and notification Manager. SessionManager is responsible for managing the client-server session, Auth Manager is responsible for client user authentication management, and Presence Manager is responsible for managing the client user's login status. The Notificationmanager is responsible for implementing the server push message function to the client.

The biggest advantage of this solution is simplicity, and we don't have to rely on OS versions like C2DM, or worry about a day when Google servers aren't available. With the XMPP protocol, we can further extend the protocol to achieve a more complete function. With this scheme, we can only send text messages at this time, but generally enough for push, because we can not expect to push to get all the data, in general, the use of push just tell the phone server has some changes, when the client receives the notification, should actively to the server to obtain the latest data, This is the complete implementation of the push service. The XMPP protocol is relatively simple and deserves further study.

But after a period of testing, I found that there are some deficiencies in ANDROIDPN:

1. For example, when the time is too long, you can no longer receive push messages.

2. The performance is not stable enough.

3. If the message is pushed out of the server, it is no longer managed, regardless of whether the message successfully arrives on the client phone.

4. Scenario IV: Use of third-party push services

By embedding the SDK using the push service provided by the third party, the current mainstream Baidu Cloud push, Aurora push, Push, PUBNUB, gather to push and so on.

Advantages: Stable, mature, save development and exploration time, relative to their own low cost of development, push management interface and statistical procedures to improve.

Cons: There are procedural embedding concerns.

The push principle of the Aurora push is as follows: Annex I.

5. Programme five: Build a push platform yourself

This is not an easy job, of course, according to their own needs to adopt the appropriate plan.

Reference code (client, server side): Annex II .

Annex I:

Aurora Push Technology principle: Mobile wireless network long connection

Mobile Internet Application Status

because of the mobile platform itself, the power, network traffic restrictions, mobile Internet applications in the design with the traditional PC on the application is very different, need to according to the characteristics of the phone itself, as far as possible to save power and traffic, but also as far as possible to ensure that the data can reach the client in time.

in order to solve the problem of data synchronization, on the mobile phone platform, the commonly used methods are 2 species. One is to periodically go to the server to query data, also known as Polling, there is a phone andserver to maintain a TCP Long Connection, when the server has data, real-time push to the client, That's what we call Push.

In terms of the amount of energy consumed, the amount of traffic and the timeliness of data delivery, Push will have a clear advantage, but Push relatively high cost of implementation and maintenance. Maintaining long connections under mobile wireless networks has some technical difficulties. This article attempts to introduce how our Aurora push is maintained on the Android platform for long connections.

features of mobile wireless networks

because IP v4 of the IP operators are assigned to mobile terminals IP is the operator intranet IP , phone to connect Internet , you need to do a network address translation through the operator's Gateway ( networkaddress Translation , NAT ). Simply said that the operator's gateway needs to maintain an external network IP, port to the network IP, port correspondence, to ensure that the intranet phone can be Server communication on the Internet.


NAT The function is shown in the GGSN module implementation.

most mobile wireless network operators will retire when there is no data communication on the link for some time. AA; the corresponding item in the table, causing the link to break.

Androidimplementation of long connection on platform

in order not to let NAT table fails, we need a timed heartbeat to refresh NAT to avoid being eliminated.

Android The usual methods for running tasks on a regular basis are 2 species, a method used Timer , the other is Alarmmanager .

Timer

Android of the Timer class can be used to schedule tasks that need to be executed in a loop, Timer the problem is that it needs to be used WakeLock Let CPU stay awake, which consumes a lot of phone power, greatly reducing the phone's standby time. This is not a way to meet our needs.

Alarmmanager

Alarmmanager is a Android system encapsulated for management RTC the module, RTC (Real time Clock) is a standalone hardware clock that can be CPU normal operation during hibernation, wakeup by interrupt at preset time CPU .

This means that if we use Alarmmanager to perform tasks on a regular basis, CPU you can sleep normally and wake up for a short time only when you need to run a task. the Android SDK for the Aurora push is based on this technology.

Server Design

When a large number of mobile terminals need to maintain a long connection with the server, the design of the server will be a big challenge.

Suppose a server maintains Ten Thousands of long connections, when there was + users, you need to have as much - server to maintain the long connections of these users, this is not a server for backup, which would be a huge cost issue. That will require us to maximize the number of single-server access to users, that is, the industry has been discussing for a long time c10k problem.

c2000k

To address this issue, we have set up a project specifically named c2000k As the name implies, our goal is to maintain a single machine $ thousands of long connections. In the end, we used a multi-message loop, asynchronous non-blocking model to maintain apeak of over a long connection on a dual-core,24G - memory server .

PostScript

Stable Maintenance Long connection is a foundation of push platform, Aurora Push Team will be in this regard long-term investment, to ensure that users can effectively save power, traffic, and data can be delivered in real time.

Annex II:AndroidCode:

Import Org.apache.http.protocol.HTTP;

Import Org.json.JSONObject;

Import com.taocaiku.gaea.common.TckApp;

Import Com.taocaiku.gaea.domain.context.Container;

Importcom.taocaiku.gaea.service.SettingService;

Import Com.taocaiku.gaea.util.FileUtil;

Import Android.annotation.SuppressLint;

Import Android.os.Bundle;

Import Android.os.Message;

Import Android.util.Log;

/**

* Threads running Socket communication

* @author TCK-001

* @version 1.0

*/

@SuppressLint ("Handlerleak")

Public final class Socketthread Extendsthread {

public void Run () {

try {

while (true) {

if (! Socketmanager.get (). Isstart ()) {

Return

}

ServerSocket Sever =socketmanager.get (). Getsocket ();

if (null = = Sever | | Sever.isclosed ()) {

Return

}

New Readsocket (Sever.accept ()). Start ();

}

} catch (Exception e) {

LOG.E ("abstractactivity", "socket has been recycled");

}

}

/**

* Read socket and parse

* @author TCK-001

* @version 1.0

*/

public class Readsocket extends Thread {

private socket socket;

Public readsocket (socket socket) {

This.socket = socket;

}

public void Run () {

try {

String jsonstr =fileutil.get (). ReadFile (Socket.getinputstream (), HTTP. Utf_8, 1, false);

Socket.close ();

Jsonobject json = Newjsonobject (JSONSTR);

if (Json.getlong ("MemberID") = = Container.member.getId () &&container.socketkey.equals (Json.getstring (" Socketkey "))

&&settingservice.get (). GetSetting (settingservice.receive_msg)) {

Bundle bundle = Newbundle ();

Bundle.putint ("type", Json.getint ("type"));

Bundle.putstring ("Data", Json.getjsonobject ("Data"). ToString ());

Message message = Newmessage ();

Message.setdata (bundle);

Tckapp.get (). Getlastact (null). Sockethandler.sendmessage (message);

}

} catch (Exception e) {

LOG.E ("Abstractactivity", "Receive socket message, parse JSON", e);

}

}

}

}

Service-Side code:

/**

* Send a Socket communication message

* @param vo

* @return

*/

public static Boolean sendsocket (Socketvo vo) {

try {

if (!pingserver () (Vo.getip ())) {return false;}

Socket socket = new Socket (Vo.getip (), Vo.getport ());//Create socket object, specify server-side address and port number

OutputStream output = Socket.getoutputstream ();

Writer writer = new OutputStreamWriter (output, charencoding.utf_8);

PrintWriter out = new PrintWriter (writer, true);//get the output stream from client side

Vo.setip (null); Vo.setport (0);

Out.print (Gsonutils.tojson (VO));//Fill information

Writer.flush (); Writer.close ();

Out.flush (); Out.close ();

Output.flush (); Output.close ();

Socket.close ();

return true;

} catch (Exception e) {

Log.error ("Send socket failed:" + e.getmessage ());

return false;

}

}

/**

* Can ping IP address

* @param server IP Address

* @param time-out timeout

* @return Boolean

*/

public static Boolean pingserver (String server, int timeout) {

try {

Process Process =runtime.getruntime (). EXEC ("ping" + server + "-n 1-w" +timeout);

if (null = = Process) {return false;}

String info = fileutil.readfile (Process.getinputstream (), encoding_gbk,1, false);

return Toolutil.getstrcharnum (info, "MS") >= 3;

} catch (Exception e) {

return false;

}

}

Android Background information push research

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.