Android Basics Getting Started tutorial--4.2.2 service advanced

Source: Internet
Author: User

Android Basics Getting Started tutorial--4.2.2 service advanced

tags (space delimited): Android Basics Getting Started Tutorial

Introduction to this section

We learned about the service lifecycle and two ways to start the service in the previous section,
This section continues with an in-depth understanding of the use instances of Intentservice,service in the service:
Front desk service and polling implementation!

Use of 1.IntentService

We already know how to define and start the service after the previous section, but if we directly
The time-consuming thread is placed in the service's OnStart () method, although it is possible to do so, but it is easy to
can cause a ANR exception (application not responding), while Android's official introduction
The service has the following passage:

Direct translation:

1.Service is not a separate process, it is in the same process as its application
2.Service is not a thread, which means that we should avoid time-consuming operations in the service

Thus, Android provides us with a solution to the above problems of the alternative, is the following Intentserviceto say;
Intentservice is a class that inherits and service and processes asynchronous requests, and in Intentservice there are
A worker thread to handle the time-consuming operation, and the requested intent record is added to the queue

Work Flow:

The client initiates the Intentservice by StartService (Intent);
We do not need manual area control Intentservice, when the task is finished, Intentservice will automatically stop;
You can start intentservice multiple times, and each time-consuming operation is done in the form of a work queue in Intentservice
The Onhandleintent callback method executes, and executes only one worker thread at a time, executes one, and then to two!

And then the code demo, most of the online code is compared to service and Intentservice,
Define a long enough sleep time to demonstrate the service's ANR exception, and then elicit the Intentservice how good!
The service is not shown here, the Web is custom service, and then the OnStart () method
Thread.Sleep (20000) then raises the ANR exception, interested can write their own code to try,
The words here only demonstrate the use of Intentservice!

Testservice3.java

 Public  class TestService3 extends intentservice {      Private FinalString TAG ="hehe";//must implement the parent class construction method     Public TestService3()      {Super("TestService3"); }//The core method that must be overridden    @Override      protected void onhandleintent(Intent Intent) {//intent is sent from the activity, carry the identification parameters, according to different parameters to perform different tasksString action = Intent.getextras (). GetString ("param");if(Action.equals ("S1")) log.i (TAG,"Start Service1");Else if(Action.equals ("S2")) log.i (TAG,"Start Service2");Else if(Action.equals ("S3")) log.i (TAG,"Start Service3");//Let service hibernate for 2 seconds        Try{Thread.Sleep ( -); }Catch(Interruptedexception e)              {E.printstacktrace ();} }//Override other methods for viewing the call order of a method    @Override       PublicIBinderOnbind(Intent Intent) {LOG.I (TAG,"Onbind");return Super. Onbind (Intent); }@Override       Public void onCreate() {log.i (TAG,"OnCreate");Super. OnCreate (); }@Override       Public int Onstartcommand(Intent Intent,intFlagsintStartid) {log.i (TAG,"Onstartcommand");return Super. Onstartcommand (Intent, flags, Startid); }@Override       Public void Setintentredelivery(BooleanEnabled) {Super. setintentredelivery (enabled); LOG.I (TAG,"Setintentredelivery"); }@Override       Public void OnDestroy() {log.i (TAG,"OnDestroy");Super. OnDestroy (); }  }

Androidmanifest.xml Registration under Service

<service android:name=".TestService3" android:exported="false">      <intent-filter >          <action android:name="com.test.intentservice"/>      </intent-filter>  </service>  

Start three services at mainactivity:

 Public  class mainactivity extends Activity {      @Override      protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);          Setcontentview (R.layout.activity_main); Intent it1 =NewIntent ("Com.test.intentservice"); Bundle B1 =NewBundle (); B1.putstring ("param","S1");          It1.putextras (B1); Intent it2 =NewIntent ("Com.test.intentservice"); Bundle B2 =NewBundle (); B2.putstring ("param","S2");          It2.putextras (B2); Intent it3 =NewIntent ("Com.test.intentservice"); Bundle B3 =NewBundle (); B3.putstring ("param","S3"); It3.putextras (B3);//Start multiple intentservice, create a new worker thread each time you start        //But there is always only one Intentservice instanceStartService (IT1);          StartService (IT2);      StartService (IT3); }  }

Run:

Summary:

When a background task needs to be divided into several subtasks and then executed in sequence, subtasks
(in short, asynchronous operations), if we define a normal service and then
In the OnStart method to open the thread, and then to control the thread, it seems very cumbersome;
At this point you should customize a intentservice and then Onhandleintent () method to complete the related tasks!

2.Activity Communication with Service

All of our previous operations started and stopped service through activity, if we started a download
Background service, and we would like to know the progress of the download task in the service! Then this must be a service.
Communicating with the activity, and the medium of communication between them is the Onbind () method in the service!
Return a Binder object of our own custom!

The basic flow is as follows:
1. Customize the service, customize a binder class, and then write the methods that need to be exposed to that class!
In the 2.Service class, instantiate this custom binder class, and then override the Onbind () method to return the Binder Object!
Instantiate a Serviceconnection object in the 3.Activity class, override the Onserviceconnected () method, and then
Get the Binder object and call the relevant method!

3. Implementation of a simple front-desk service

Learning now, we all know that service is generally run in the later, but the service's system priority
is still relatively low, when the system memory is insufficient, it is possible to recycle the service that is running in the background,
In this case we can use the front desk service, so that the service is slightly less easily killed by the system,
Of course it's possible to be killed ... The so-called front desk service is the status bar display notification!
Implementation is also very simple, recently done the project just use this front desk service, the core code out
Share the following:
In the custom service class, rewrite OnCreate (), and then customize the notification to suit your needs;
Once the customization is complete, call Startforeground (1,notification object)!
The core code is as follows:

public void OnCreate () {Super. OnCreate();Notification. BuilderLocalBuilder = new Notification. Builder(this);LocalBuilder. Setcontentintent(pendingintent. Getactivity(This,0, New Intent (This, mainactivity. Class),0));LocalBuilder. Setautocancel(false);LocalBuilder. Setsmallicon(R. Mipmap. IC_cow_icon);LocalBuilder. Setticker("Foreground Service Start");LocalBuilder. Setcontenttitle("socket Service Side");LocalBuilder. Setcontenttext("Running ...");Startforeground (1, LocalBuilder. GetNotification());}

Operating effect:

4. Implementation of a simple timed background thread

In addition to the above-mentioned front-desk services, the actual development of the service has a common use, is to perform scheduled tasks,
Polling, for example, is to request a server every time interval, confirm the status of the client, or update the information
such as There are two ways to use the timer class and the alarm mechanism in the timing mode that Android offers us!

The former is not suitable for scheduled tasks that need to run in the background for a long time, and when the CPU is dormant, the timer task
Alarm does not exist, he has the ability to wake up the CPU, and also to distinguish the CPU
Wake up with a screen wake up!

Use process:

  • Step 1: Get Service:
    Alarmmanager manager = (Alarmmanager) getsystemservice (Alarm_service);
  • Step 2: Set the timer task by the Set method
    int anhour = 2 * 1000;
    Long triggerattime = Systemclock.elapsedrealtime () + anhour;
    Manager.set (alarmmanager.rtc_wakeup,triggerattime,pendingintent);
  • Step 3: Define a service
    Open a transaction thread in Onstartcommand to handle some timing logic
  • Step 4: Define a broadcast (broadcast) to start the service
    Finally, don't forget to register this service with Boradcast in Androidmanifest.xml!

Detailed parameters:
Set (int type,long starttime,pendingintent pi)

①type:
There are five optional values:
Alarmmanager.elapsed_realtime:
The alarm clock is not available when the phone is asleep, and the alarm clock uses a relative time (relative to the start of the system boot) with a state value of 3.
Alarmmanager.elapsed_realtime_wakeup
The alarm will wake up the system and perform the prompt function, the alarm clock also uses the relative time, the status value is 2;
ALARMMANAGER.RTC
The alarm clock is not available in the sleep state, and the alarm clock uses the absolute time, that is, the current system time, the status value is 1;
Alarmmanager.rtc_wakeup
Indicates that the alarm will wake the system and perform the prompt function when the alarm is in a state of sleep, with an absolute time value of 0.
Alarmmanager.power_off_wakeup
Indicates that the alarm clock in the state of the hand machine can also be a normal function, so it is one of the most used states in 5 states,
In this state the alarm is also used absolute time, the status value is 4, but this state seems to be affected by the SDK version, some versions do not support;

PS: The first parameter determines the type of the second parameter, and if it is realtime, it is used:
The Systemclock.elapsedrealtime () method can get the number of milliseconds that the system has been booting to now
If RTC is used: System.currenttimemillis () can be obtained from 0 to 1970.1.1.
The number of milliseconds to do the experience now

②starttime:
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
The relative time (elapsed_realtime and elapsed_realtime_wakeup) is used, then the genus
The relative time (relative to the system boot time), such as the current time, is expressed in terms of:
Systemclock.elapsedrealtime (); If the alarm corresponding to the first parameter uses an absolute time (RTC, Rtc_wakeup, Power_off_wakeup), then this property will have to use absolute time,
For example, the current time is expressed as: System.currenttimemillis ().

③pendingintent:
An alarm is bound to perform actions such as sending a broadcast, giving hints, and so on. Pendingintent
is the encapsulation class for intent. It is important to note that if you implement an alarm prompt by starting the service,
The acquisition of Pendingintent objects should be based on Pending.getservice
(Context c,int i,intent intent,int j) method; If you are using a broadcast to implement an alarm alert,
The acquisition of Pendingintent objects should be based on Pendingintent.getbroadcast
(Context c,int i,intent intent,int j) method;
If the alarm is implemented in an activity-based way, the Pendingintent object gets
Should use Pendingintent.getactivity (Context c,int i,intent intent,int J)
Method. If these three methods are wrong, although not error, but do not see the alarm effect.

Other than that:

From the 4.4 release (API), the trigger time of the alarm task may become inaccurate, may delay, is the system
For power-hungry optimizations, you can call the Setextra () method if you need it correctly ~

Core code:
Longrunningservice.java

 Public  class longrunningservice extends Service {    @Override     PublicIBinderOnbind(Intent Intent) {return NULL; }@Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {//This opens a thread to perform the specific logic operation:        NewThread (NewRunnable () {@Override             Public void Run() {LOG.D ("Backservice",NewDate (). toString ());        }}). Start (); Alarmmanager manager = (Alarmmanager) getsystemservice (Alarm_service);//Here is timed, here is set every two seconds to print a time =-=, self-change        intAnhour =2* +;LongTriggerattime = Systemclock.elapsedrealtime () + anhour; Intent i =NewIntent ( This, Alarmreceiver.class); pendingintent pi = pendingintent.getbroadcast ( This,0I0); Manager.set (Alarmmanager.elapsed_realtime_wakeup, Triggerattime, pi);return Super. Onstartcommand (Intent, flags, Startid); }}

Alarmreceiver.java

publicclass AlarmReceiver extends BroadcastReceiver {    @Override    publicvoidonReceive(Context context, Intent intent) {        new Intent(context,LongRunningService.class);        context.startService(i);    }}
This section summarizes:

In this section we continue to learn more about service, Intentservice and service
Two common cases in real-world development: the implementation of the front-end service, and the service backend
The implementation of the service! In the next section we will continue to study the service Aidl, cross-process communication,
Please look forward to ~

Reference Documents:
"The first line of Android"-Guo Lin: A good android primer book!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Basics Getting Started tutorial--4.2.2 service advanced

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.