Android Product Development (13)-->app rotation operation

Source: Internet
Author: User

Reprint please indicate the source: a column of Maple Leaf

In the previous article, we explained several ways in which the Android app can implement long connections, their pros and cons, and the specific implementations, which generally use third-party push services to meet basic business requirements. Of course, if the pursuit of technology can be through the NIO or Mina to achieve their long connection service, but the long-connected service of their own more complex time-consuming more, and there may be many pits to fill in the process, generally recommend the use of third-party push service, stable and simple, The modules for managing the Long Connection section are available for reference: Android Product Development (12) –>app long connection implementation.

This article will explain the application side of the rotation request service, in general we often use the rotation operation for the request server. For example, a certain page we have timed tasks need to always get updates from the server and display, such as when the long connection is broken we may need to start rotation request as a long connection supplement, so this time to use the rotation service.

What is a rotation request

In the description of our rotation request, here first explain what is called rotation request, my understanding is the app side every certain time to repeat the request operation is called rotation request, for example: The app end every time to report the location information, the app end every time to pull a user state, etc. These should all be rotation requests, then we talked about the long connection of the app side, why do we need rotation operation after long connection?

This is because our long connection is not stable and reliable, and we do rotation operation is generally to stabilize the network request, and rotation operation is generally a life cycle, that is, in a certain life cycle to perform rotation operations, and our long connection is generally the entire process life cycle, So it's not a good way to talk about it.

Rotation Request Practice

Rotation requests related to long connections

    1. When we were explaining the long connection, we said that long connections could be broken, and at this time we need to start a rotation service when the long connection is broken, which complements the long connection.
/** * Start Polling service * *     Public void Startloopservice() {//Start polling service        //Not consider the decision to join the network temporarily ...        if(! loopservice.isserviceruning) {//user is logged in, start polling service            if(Userconfig.ispasslogined ()) {//Determine the status of the current long connection, and if the long connection is connected, the polling service is no longer turned on                if(Minalongconnectmanager.session! =NULL&& MinaLongConnectManager.session.isConnected ()) {Loopservice.quitloopservice (context);return;            } loopservice.startloopservice (context); }Else{Loopservice.quitloopservice (context); }        }    }

Here is what we do with the rotation service, which is to start a rotation service (that is, rotation services) and then execute the specific rotation request in the rotation service, so we'll look at the code logic for this service in detail.

    • Rotation service requests related to long connections
/** * Start service when long connection is abnormal, close service when long connection is restored * / Public  class loopservice extends Service {     Public Static FinalString ACTION ="Com.youyou.uuelectric.renter.Service.LoopService";/** * The time interval at which the client performs polling, which is returned by the Startqueryinterface interface and is set to 30s by default * /     Public Static intLoop_interval_secs = -;/** * Polling interval (mloop_interval_secs this time interval variable has a server issued, the polling service scene and logic and definition changes, involving the iOS side, so with their own defined constants in the client write dead time interval) * /     Public Static intMloop_interval_secs = -;/** * Whether the current service is executing */     Public Static BooleanIsserviceruning =false;/** * Timer Task Tool class * /     Public StaticTimer timer =NewTimer ();Private StaticContext context; Public Loopservice() {isserviceruning =false; }//-------------------------------use the alarm to perform a polling service------------------------------------    /** * Start Polling service * *     Public Static void Startloopservice(Context context) {if(Context = =NULL)return;        Quitloopservice (context); L.i ("Turn on polling service, polling interval:"+ Mloop_interval_secs +"S");        Alarmmanager manager = (Alarmmanager) context.getapplicationcontext (). Getsystemservice (Context.alarm_service); Intent Intent =NewIntent (Context.getapplicationcontext (), loopservice.class);        Intent.setaction (loopservice.action); Pendingintent pendingintent = Pendingintent.getservice (Context.getapplicationcontext (),1, intent, pendingintent.flag_update_current);//Long triggerattime = Systemclock.elapsedrealtime () + +;        /** * The first time the alarm is executed, in milliseconds, the time can be customized, but the current time is generally used. It is important to note that this property is closely related to the first property (type), * if the alarm corresponding to the first parameter uses a relative time (Elapsed_realtime and Elapsed_realtime_wakeup), Then this property will have to use relative time (relative to the system startup time), * For example, the current time is expressed as: Systemclock.elapsedrealtime (); * If the alarm for the first parameter uses an absolute time (RTC, RT         C_wakeup, Power_off_wakeup), then this property will have to use absolute time, * For example, the current time is expressed as: System.currenttimemillis (). */Manager.setrepeating (Alarmmanager.rtc_wakeup, System.currenttimemillis (), Mloop_interval_secs * +, pendingintent); }/** * Stop Polling service * *     Public Static void Quitloopservice(Context context) {if(Context = =NULL)return; L.i ("Turn off polling alarm service ...");        Alarmmanager manager = (Alarmmanager) context.getapplicationcontext (). Getsystemservice (Context.alarm_service); Intent Intent =NewIntent (Context.getapplicationcontext (), loopservice.class);        Intent.setaction (loopservice.action); Pendingintent pendingintent = Pendingintent.getservice (Context.getapplicationcontext (),1, intent, pendingintent.flag_update_current); Manager.cancel (pendingintent);//Turn off polling serviceL.i ("Turn off polling service ...");    Context.stopservice (Intent); }@Override     Public void onCreate() {Super. OnCreate ();    context = Getapplicationcontext (); }@Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {l.i ("Start polling service ... \ n Determine if the current user is logged in ...");//If the current network is not normal or the user is not logged in, no longer jump        if(Userconfig.ispasslogined ()) {//Judge the current long connection state, if the long connection is OK, turn off polling serviceL.i ("The current user is logged in ... \ nthe long connection is already connected ...");if(Minalongconnectmanager.session! =NULL&& MinaLongConnectManager.session.isConnected ()) {l.i ("Long connection has resumed connection, exiting polling service ...");            Quitloopservice (context); }Else{if(isserviceruning) {returnStart_sticky; }//Start polling pull messageStartloop (); }        }Else{L.i ("User has exited login, turn off polling service ...");        Quitloopservice (context); }returnStart_sticky; }@Override     Public void OnDestroy() {Super. OnDestroy (); L.i ("Polling service exits, executes Ondestory () method, Inserviceruning assignment False"); Isserviceruning =false;        Timer.cancel (); Timer =NewTimer (); }@Override     PublicIBinderOnbind(Intent Intent) {Throw NewUnsupportedoperationexception ("not yet implemented"); }/** * Start polling Pull message */    Private void Startloop() {if(Timer = =NULL) {timer =NewTimer (); } timer.schedule (NewTimerTask () {@Override             Public void Run() {isserviceruning =true; L.i ("The long connection does not resume the connection, perform the polling operation ... \ n Poll the service Request GetInstance interface ...");            Looprequest.getinstance (context). Sendlooprequest (); }        },0, Mloop_interval_secs * +); }}

It can be found that the service rotation services here is still a lot of code, but the rotation service request code comments are very detailed, so do not do too much explanation, it should be noted that its core is through the timer object each time the network request execution. The specific Network request code:

L.i("长连接未恢复连接,执行轮询操作... \n 轮询服务中请求getInstance接口...");           LoopRequest.getInstance(context).sendLoopRequest();

Here's the rotation service request Core Logic: When the long connection exception occurs, the rotation service is started and the server state is pulled through the timer object every certain time, and when the long connection is resumed, the rotation service is turned off. This is the code execution logic for our rotation services related to long connections, and we'll look at the execution logic of the page-related rotation requests after we've finished this part.

Page-related rotation requests

    • Page-related rotation requests
      In our app, we may need to pull the user state periodically when the user stays on a certain page, then we need to use rotation request to pull the server state and close the rotation service request when the user leaves the page.

Here we take a look at our products current itinerary page rotation operation, used for rotation request the current user's vehicle mileage, cost, time and other information, specific can refer to:

In fact, in the current fragment page has a timed pull to order information rotation request, below we specifically look at this timing request execution logic:

/** * TimerTask object, mainly used to pull the server information periodically. Public  class Task extends timertask {        @Override         Public void Run() {l.i ("Start Execution timer timer task ..."); Handler.post (NewRunnable () {@Override                 Public void Run() {Isfirstgetdata =false; GetData (true);        }            }); }    }

And here the GetData method is to pull the server state method, here do not do too much explanation, when the user exits this page need to clear the rotation operation here. As a result, the purge timertask is performed in the fragment Ondesctoryview method.

@Override    public void onDestroyView() {        super.onDestroyView();        ...        if (timer != null) {            timer.cancel();            timer = null;        }        if (timerTask != null) {            timerTask.cancel();            timerTask = null;        }        ...    }

This way, when the user opens this page, initializes the TimerTask object, requests the server to pull the order information once every minute and updates the UI, and when the user leaves the page, clears the TimerTask object, which cancels the rotation request operation. It can be found that the rotation request service that we see above is related to long connections and pages is the rotation request service implemented through the timer object's timed task, let's look at how to implement rotation request service through handler object.

Implementing rotation requests through handler objects

    • Let's look at a rotation request service that is implemented by handler asynchronous messages.
/** * Default time interval: 1 minutes */    Private Static intDefault_interval = -* +;/** * Polling interval in exceptional cases: 5 seconds */    Private Static intError_interval =5* +;/** * Current Polling execution time interval * /    Private Static intInterval = Default_interval;/** * Poll handler message type * /    Private Static intLoop_what =Ten;/** * is the first time to pull data * /    Private BooleanIsfirstrequest =false;/** * The first request data is successful */    Private BooleanIsfirstrequestsuccess =false;/** * Start polling, normally, polling every 1 minutes to pull up the latest data * Turn on polling at OnStart * *    Private void Startloop() {l.i ("page OnStart, need to turn on polling");    Looprequesthandler.sendemptymessagedelayed (loop_what, interval); }/** * Turn polling off, stop polling when the interface is OnStop */    Private void Stoploop() {l.i ("page is onstop, need to stop polling");    Looprequesthandler.removemessages (Loop_what); }/** * Handle Polling handler */    PrivateHandler Looprequesthandler =NewHandler () {@Override         Public void Handlemessage(Message msg) {//If the first request fails,            if(!isfirstrequestsuccess) {L.i ("The first request failed and the polling time needs to be set to:"+ Error_interval);            Interval = Error_interval; }Else{interval = Default_interval; } l.i ("Polling-----The current polling interval:"+ interval); Looprequesthandler.removemessages (Loop_what);//When the first request succeeds, or the location is unsuccessful, the relocation is performed and the dot data is loaded            if(!isfirstrequestsuccess | |! Config.locationissuccess ()) {Isclicklocationbutton =false;            Dolocationoption (); }Else{LoadData ();            } System.GC ();        Looprequesthandler.sendemptymessagedelayed (loop_what, interval); }    };

Here is the rotation operation implemented through handler, the core principle is that in handler Handlermessage method, the message is sent again after receiving the delay message, where the delay time is our definition of rotation interval time, This allows us to send a delay message again the next time we receive the message, which causes us to send rotation messages at all times.

These are the two ways we implement rotation operations:

    • Timer Object Implementation rotation operation

    • Handler object Implementation rotation operation

We have analyzed the different usage scenarios, functions and implementations of rotation requests, and we can consider using rotation request when we need to pull the cancellation interest to the server in the specific development process.

Summarize:

    • Rotation operation is generally through the timing request Server pull information and update the UI;

    • Rotation operations generally have a certain life cycle, such as when a page is opened to start the rotation operation, when a page is closed to cancel the rotation operation;

    • The request interval of the rotation operation needs to be determined according to the specific requirement, the interval time should not be decisive, otherwise may cause the concurrency problem;

    • In the product development process, some need to try to update the server pull information and update the UI, you can consider using the rotation operation implementation;

    • The timer object and the handler object can be used to implement the rotation request operation in two ways.


In addition to product development technology, skills, practice interested students can refer to my:
Android Product Development (i) –> Practical development Code
Android product Development (ii) –> start Page optimization
Android Product Development (iii) –> base class activity
Android product Development (iv) –> reduce APK size
Android Product Development (v) –> multi-channel packaging
Android product Development (vi) –>APK confusion
Android Product Development (vii) –>APK hot fix
Android product Development (eight) –>app data statistics
Android product Development (ix) –>APP Network Transfer Protocol
Android Product Development (10) –> do not use static variables to save data

This article synchronizes to GitHub: Https://github.com/yipianfengye/androidProject, Welcome to star and follow

Android Product Development (13)-->app rotation operation

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.