1. Let's analyze one of the tips in the service today: Front desk (forground service)
--------------------------------------------------------------------------------------------------------------- -------------------------
"Problem": we all know that the service is running in the background, if the system is out of memory, then, the system may be able to reclaim the services of future generations, then how do we ensure that the service can be run all the time?
"Resolution": in the service, there is a concept of a foreground service that calls the Startforground () method.
We look at the official website for the Front desk service and startforeground () Description:
After reading the official explanation, let's look at how to use the code:
Public classMyService extends service{...
@Override
Public voidOnCreate () {
Super.oncreate ();
IntentIntent = newIntent(Getbasecontext (), mainactivity.class);
pendingintentPI =pendingintent. Getactivity (Getbasecontext (), 0, intent, pendingintent.flag_cancel_current);
NotificationNo = newNotification. Builder (Getbasecontext ())//After starting the service, add a notification in the foreground
. Setwhen (System.currenttimemillis ())
. Setsmallicon (R.mipmap.ic_launcher)
. Setticker ("Create a front desk service!")
. Setcontenttitle ("This is a front desk service")
. Setcontenttext ("A service skill!!!")
. Setcontentintent (PI)
. Setautocancel (True)
. SetDefaults (Notification.default_all)
. build ();
Startforeground (1, no);
LOG.D (TAG, "OnCreate executed");
}
}
Let's look at the official documentation:
The above code is added in the service creation of a Notification, call startforground () can guarantee: As long as the service has been present, then the foreground will always show this Notification .
If we call the Stopforground () method in OnDestroy (), the Notificationis destroyed, but the service is still alive, At this point the service is at risk of being killed by the system .
If the stop service is direct, then both notification and service are destroyed.
--------------------------------------------------------------------------------------------------------------- -------------------------
2. Next, let's look at another service tip: Intentservice
"Problem": we know that the code logic for the service is executed in the main thread, and if we need to perform some time-consuming operations in the main thread, there is a good chance that the ANR (program is not responding) condition will occur.
This time, we can use the Android Multi-threaded programming (small series in the previous asynctask paste to explain too many threads, can review) way, we look at a code:
Public classMyService extends service{@Nullable @Override Publicibinder onbind (Intent Intent) {return NULL; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {
New Thread (New Runnable () {
@Override
public void Run () {
Handling specific logic//opening a thread-handling time-consuming operation
}
}). Start (); returnSuper.onstartcommand (Intent, flags, Startid); }
}
Now the service can start up, but if you don't call the StopService () or stopself () method, the service runs all the time, so let's change the code:
Public classMyService extends service{@Nullable @Override Publicibinder onbind (Intent Intent) {return NULL; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {NewThread (NewRunnable () {@Override Public voidrun () {//dealing with specific logic//open a thread-handling time-consuming operation
stopself (); //Let the service stop itself after the logic is finished executing}}). Start (); returnSuper.onstartcommand (Intent, flags, Startid); }}
The above code is a standard service written form, consisting mainly of two knowledge points: thecreation of thread child threads and the invocation of the Stopself () method .
In fact, in the general use of the process, a part of the programmer can easily forget the above two points, there is forgotten, then there is no better way to achieve the above two requirements?
"Resolution" : In Android, a Intentservice class (Android.app.IntentService) is specifically provided, and this class is well-adapted to our needs! We look directly through the code:
(1) Create a new Myintentservice class that inherits from Intentservice, code:
Public classMyintentservice extends intentservice{ PublicMyintentservice () {Super ("Myintentservice"); } @Overrideprotected voidonhandleintent (Intent Intent) {LOG.D ("Myintentservice","myintentservicethread ID is"+Thread.CurrentThread (). GetId ()); } @Override Public voidOnDestroy () {Super.ondestroy (); LOG.D ("Myintentservice","OnDestroy executed"); }}
The above code does a few things:
1, provides a non-parametric construction method, and called the parent class has the parameter constructor (this does not need me to say why?);
2, the subclass implements the Onhandleintent () abstract method of the parent class, this method is good, it is a method that has already run in the child thread. That is, the service invokes it, so the logic executes like a thread child thread.
Onhandleintent = Thread (). Start () + stopself ()
3, Onhandleintent () after the execution of the service will be destroyed? Will Selfstop ()? Then look down at the code.
--------------------------------------------------------------------------------------------------------------- -------------------------
(2) in the XML file, create a Myintentservice service button:
<button android:id = " android:layout_width = " match_parent " android:layout_height = " wrap_content android:text = " @string/intent_service "/>
(3) Next, modify the code in the mainactivity:
Public classMainactivity extends Activity {
@Overrideprotected voidonCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button Startintentservice=(Button) Super.findviewbyid (R.id.start_intent_service); Startintentservice.setonclicklistener (NewView.onclicklistener () {
@Override Public voidOnClick (View v) { log.d ( "Myintentservice", "Mainactivity Thread ID is" + thread.currentthread (). GetId ()); //View the ID of the main thread Intent intentservice = new Intent (Getbasecontext (), Myintentservice.class); StartService (intentservice); } }); }}
(4) Finally, register the service in Androidmainfest:
<service android:name=". Myintentservice" />
results: look directly at the effect of the code execution.
From the log you can see:
(1) The ID of the process where Myintentservice and mainactivity are located is not the same ;
(2) The Onhandleintent () method does destroy the service after executing the logic, and the effect is equivalent to Stopself ().
From the above analysis, we can see that the Onhandleintent () method is indeed quite useful!
Android_ Practical Technology (3)--service analysis (Ⅲ)