android--using Jobservice for process keepalive

Source: Internet
Author: User
Tags set time

Process KeepAlive has always been the hope of the vast majority of app developers, because the process is alive we can do a lot of things (push, data synchronization, etc.), but Google is not allowed to do so (optimization), so we have to find a way.

    1. Let's take a look at some of the processes in Android.
      • foreground process: Foreground process
        • user interacting activity (onresume ( )
        • When a service binding is interacting with the activity.
        • is actively invoked as a foreground service (Startforeground ())
        • component in the execution lifecycle of callbacks (OnCreate ()/onstart ()/ondestroy ())
        • Broadcastreceiver is executing onreceive ();

      • Visible Processes: Visible process
        • Our activity is in OnPause () (No entry to OnStop ())
        • bound to the foreground activ Ity's service.
      • Services Process: Service process
        • simple StartService () start.
      • Background process: Background process
        • Processes that have no direct impact on users----activity out of onstop ().
          android:process= ": xxx"

      • NULL processes: Empty process
        • Does not contain any active components. (Android-designed, for a second start faster, take a trade-off)

2, usually we start a service process, either directly startservice () or Bindservice (), we may need to do some things in these service processes, but these things do not say that we do now, may be to do in the future, Or at some point in time, we need our service to stay active.

3, Jobservice can be regarded as a Jobscheduler callback service. Jobscheduler is a system-level job scheduler, we throw certain tasks to the system, and when we reach the conditions we set, Jobscheduler will then suspend our Jobservice to execute our business logic.

      • Here is mainly to introduce how to use Jobscheduler to carry out our service KeepAlive, Jobscheduler not introduced, there is need to understand please move the official documents.
      • Https://developer.android.google.cn/reference/android/app/job/JobScheduler.html

4. Let's see how we can achieve this. (I'll just go straight to the code.)

    • @SuppressLint ("Newapi") Public classJobhandleserviceextendsJobservice {Private intKjobid = 0; @Override Public voidonCreate () {Super. OnCreate (); LOG.I ("INFO", "Jobservice create"); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {LOG.I ("INFO", "Jobservice start"); //when the service starts, it pushes the task directly to the Jobscheduler task queue, and then, when the set time condition arrives, it will lift our service directly and walk the Onstartjob () methodSchedulejob (Getjobinfo ()); returnStart_not_sticky; } @Override Public voidOnDestroy () {Super. OnDestroy (); } @Override Public Booleanonstartjob (jobparameters params) {//Params.getextras ()//Schedulejob (Getjobinfo ());        BooleanIslocalservicework = Isservicework ( This, "Com.xxx.XxxService"); BooleanIsremoteservicework = Isservicework ( This, "Com.xxx.XxxService"); if(!islocalservicework | |!isremoteservicework) {             This. StartService (NewIntent ( This, LocalService.class));  This. StartService (NewIntent ( This, Remoteservice.class)); Toast.maketext ( This, "Process Start", Toast.length_short). Show (); }        return true; } @Override Public Booleanonstopjob (jobparameters params) {log.i ("INFO", "Job Stop"); //when execution is complete, we add the task to the Jobscheduler. Schedulejob (Getjobinfo ()); return true; }    /*** Send job to the Jobscheduler. */     Public voidschedulejob (Jobinfo t) {log.i ("INFO", "Scheduling job"); Jobscheduler TM=(Jobscheduler) Getsystemservice (Context.job_scheduler_service); if(tm! =NULL) {tm.schedule (t); }    }     Publicjobinfo Getjobinfo () {Jobinfo.builder Builder=NewJobinfo.builder (kjobid++,NewComponentName ( This, Jobhandleservice.class));        Builder.setrequirednetworktype (Jobinfo.network_type_any); Builder.setpersisted (true); Builder.setrequirescharging (false); Builder.setrequiresdeviceidle (false); Builder.setperiodic (10);//interval Time--period        returnBuilder.build (); }    /*** How to determine if a service is running * *@paramMcontext *@paramServiceName is the class name of the package name + service (for example: net.loonggg.testbackstage.TestService) *@returntrue to indicate that the service is not running, false*/     Public Booleanisservicework (Context mcontext, String serviceName) {BooleanIswork =false; Activitymanager Myam=(Activitymanager) Mcontext.getsystemservice (Context.activity_service); List<RunningServiceInfo> myList =NULL; if(Myam! =NULL) {myList= Myam.getrunningservices (100); }        if(MyList! =NULL&& mylist.size () <= 0) {            return false; }        if(MyList! =NULL) {             for(inti = 0; I < mylist.size (); i++) {String mname=Mylist.get (i). Service.getclassname (); if(Mname.equals (serviceName)) {iswork=true;  Break; }            }        }        returniswork; }}

I here is a simple demonstration, the specific implementation of our project did not send to the above, you can figure it out.

android--using Jobservice for process keepalive

Related Article

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.