Make your own push

Source: Internet
Author: User

The last one months have been thinking about implementing a push library that allows Android developers to do it alone. Because of the existing push capabilities, all require server-side mates, constantly testing, even if the use of third-party libraries will take a long time to test. Here is a small piece of my recent research: Http://git.oschina.net/kymjs/KJPush

The push function is already very common in Android application development, this article is to discuss the underlying principle of push in Android and some solutions to implement push function.

1. What is push?

When we develop applications that need to interact with servers, we basically need to get server-side data, such as the open source Chinese client, which the client needs to know and handle when someone reviews or responds to you. There are two ways to get the information on the server: 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.

Push is the server to actively send messages to the client, there are now a lot of third-party push framework: such as Baidu push, Aurora push, push, etc., are based on the second way of saying that servers use push way. because the first time to know that the data changes are the server itself, so the advantage of push is high-real-time. However, server proactive push requires the development of a separate set of service-side programs that allow clients to connect permanently. However, in some cases it is not necessary to actively push the server, but at a certain time interval the client initiates the query, this time should use pull to obtain. Many people think that push mode does not have any consumption, but the use of push mode requires a long time to maintain a client and server-side communication socket long connection, is still very expensive traffic and power. If the polling policy is configured well, the amount of electricity and data consumed is no more than the one used to maintain a socket connection. for example, there is such an app, the real-time requirements are not high, as long as 10 times a day to get the latest data to meet the requirements, this situation obviously polling more suitable, push seems too wasteful, and more power consumption.

2. How to implement polling request

The first is to create a timer in a service, and the following code is a similar implementation (excerpt) found on the web

/** * SMS Push service class, in the background for a long run, each time to send a request to the server * @author Jerry */public class Pushsmsservice extends Service {@Override        public void OnCreate () {this.client = new asynchttpclient ();        This.mythread = new MyThread ();        This.myThread.start ();    Super.oncreate (); } private class MyThread extends Thread {@Override public void run () {String URL = "You requested the            Network Address ";                while (flag) {//each 10 second sends a request to the server Thread.Sleep (10000);                    Send request Client.get (URL, new Asynchttpresponsehandler () {@Override to server using get mode                        public void onsuccess (int statusCode, header[] headers, byte[] responsebody) {                                    try {jsonobject result = new Jsonobject (New String (                            Responsebody, "Utf-8"));        int state = Result.getint ("state");                    If the even is an unread message if (state% 2 = = 0) {String Co                                Ntent = result.getstring ("content");                                String date = result.getstring ("date");                                String number = result.getstring ("number");                            Notification (content, number, date);                        }} catch (Exception e) {e.printstacktrace (); }                    }}

However, with Sleep,timertask, it is possible to increase the service being recovered by the system, and a more appropriate method is to use the timer of the Alarmmanager system to manage it.

Here's how you can see the complete implementation here

private void Startrequestalarm () {cancelrequestalarm (); From 1 seconds onwards, every 2 minutes to execute getoperationintent ()//Note that this 2 minute is just 2 minutes under normal circumstances, the actual situation may be extended by different system processing strategies, such as the pit Father's coarse grain system may be extended to 5 minutes MALARMM                Gr.setrepeating (Alarmmanager.rtc_wakeup, System.currenttimemillis () + +, Kjpushconfig.palpitate_time,    Getoperationintent ());     /** * Even if the original process of starting pendingintent is finished, pendingintent itself still exists and can continue to be used in other processes (* Pendingintent other programs submitted to). * If I am extracting a pendingintent from the system, and there is a pendingintent equivalent pendinginent in the system that you describe, * Then the system will return directly and the pendingintent is actually the same token as the pendingintent, * instead of a new token and pendingintent.     However, when you extract pendingintent from the flag_cancel_current parameter, * Let the old pendingintent cancel (), so that the pendinginten and their tokens are new.    */private void Cancelrequestalarm () {Malarmmgr.cancel (getoperationintent ()); }/** * Using polling for message push <br> * Every call to execute {@link #PushReceiver}onreceive () method * * @return */P Rivate pendingintent getoperationintent () {        Intent Intent = new Intent (this, pushreceiver.class);        Intent.setaction (Kjpushconfig.action_pull_alarm);        Pendingintent operation = Pendingintent.getbroadcast (this, 0, intent, pendingintent.flag_update_current);    return operation; }

This can be done to the greatest extent possible due to the timing of their own implementation of the timer is not accurate or the timer is System recovery problems.

But just so there is no way to achieve a perfect and stable polling push library, do push the biggest problem has three: power consumption, data consumption, service persistence.

3, power consumption optimization and data flow consumption optimization:

These two problems can actually be combined into one problem, because the request server is actually a power-consuming thing. Similar to maintaining a long connection, the push function, whether it is to maintain a long connection or a timed Request server requires network data traffic, but the long connection is a continuous drain, and polling is a big break in the cost of data. This requires a workable strategy to configure, so that polling executes the way we want it to. At present, I adopt the idea is that when the phone is in GPRS mode to reduce the frequency of polling, every 5 minutes to request the server, when the phone in WiFi mode every 2 minutes to request the server, while setting off the screen will stop the push request, when the screen goes off 20 seconds to kill the push process, This not only does not need to consider maintaining the consumption of a process, but also saves the use of data traffic.

4. Service Persistence

I believe this is a lot of people have encountered problems, there are many similar problems on the Internet, such as the application of QQ is very good, regardless of the use of third-party mobile phone assistant or use the system to stop an application (not the kind of stop inside the set, is long press the home button the kind), background service will not be recycled. Unfortunately, I can only guarantee that a service is not recycled by a third-party phone helper, can prevent some phone long press the home button to stop, but for example, coarse grain of the MIUI system, will still kill my service and can not be restored. So far I have not found an open and perfect solution, if you know how to solve it, please feel free. I'll briefly talk about how to maintain a service to the maximum extent possible.

In the past when the music player, I believe many people have encountered, in the application of too many times, the background play music service independent process will be killed by the system.

The

has an internal class runningappprocessinfo in Android Activitymanager to record the status of processes in the current system. Here are some of these values:

       /** * Constant for {@link #importance}: The is a persistent process.         * Only used when reporting to process observers.        * @hide */public static final int importance_persistent = 50;         /** * Constant for {@link #importance}: This process is running the * foreground UI.                */public static final int importance_foreground = 100; /** * Constant for {@link #importance}: The This process was running something * that's actively visible to th         E user, though not in the immediate * foreground.                */public static final int importance_visible = 200; /** * Constant for {@link #importance}: The This process was running something * that's considered to be Activ  Ely perceptible to the user.         An * example would is an application performing background music playback.         */public static final int importance_perceptible = 130;       /** * Constant for {@link #importance}: This process is running a * application that can not save         Its state, and thus can ' t is killed * while in the background.                * @hide */public static final int importance_cant_save_state = 170;         /** * Constant for {@link #importance}: The This process was contains services * that should remain running.                */public static final int importance_service = 300; /** * Constant for {@link #importance}: This process process contains * Background code it is expendable         .                */public static final int importance_background = 400;         /** * Constant for {@link #importance}: This process is the empty of any * actively running code. */public static final int importance_empty = 500;

A process with a general value greater than Runningappprocessinfo.importance_service is useless for a long time or an empty process.

A process with a general value greater than runningappprocessinfo.importance_visible is a non-visible process, that is, running in the background

Third-party cleanup software cleanup is generally greater than the value of importance_visible, so if you want to not be killed, you need to reduce your own process to importance_visible below, that is, the extent of the visible process. In each service there is a method called Startforeground, that is, the mode of the visible process start, here is the SDK source code implementation and comments, you can see that it will continue to display a notification in the notification bar, but only need to pass the ID 0 to avoid the display of notifications. Of course, to cancel this visible process level setting only needs to call Stopforgeround.

/**     * Make this service run in the foreground, supplying the ongoing     * notification to being shown to the user while In the state.     * By default services is background, meaning if the system needs to     * kill them to reclaim more memory (such as To display a large page with a     * Web browser), they can be killed without too much harm.  can set this     * flag if killing your service would being disruptive to the user, such as     * If your service is perf Orming background music playback, so the user     * would notice if their music stopped playing.     *    /public final void Startforeground (int id, Notification Notification) {        try {            Mactivitymanager.setserviceforeground (                    new ComponentName (this, mclassname), Mtoken, ID,                    notification, true);        } catch (RemoteException ex) {        }    }

This is because of the limited space, so much, want to learn more about the process of priority promotion can be seen in the definition of Activitymanager source code and Kjpush in the implementation of the way.

Make your own push

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.