Original URL: http://rainbow702.iteye.com/blog/1143286
Regardless of the service, it runs by default in the main thread of the application (i.e., the UI thread). So, if your service is going to run very time-consuming or potentially blocked operations, your application will be suspended and even a ANR error will occur. To avoid this problem, you should restart a new thread in the service to do these things. There are two kinds of methods available for reference:
① restarts a thread directly in the service's Onstartcommand () method to execute, such as:
Java code
- @Override
- public int Onstartcommand (Intent Intent, int flags, int startid) {
- Myserviceactivity.updatelog (TAG + "----> Onstartcommand ()");
- New Thread (new Runnable () {
- @Override
- public Void Run () {
- //Here is a time-consuming operation, this is simply to let the thread sleep 1s
- try {
- Thread.Sleep (1000);
- } catch (Exception e) {
- E.printstacktrace ();
- }
- }
- }). Start ();
- return start_sticky;
- }
②android SDK provides us with an out-of-the-box service class to implement this function, it is intentservice, it is mainly responsible for the following aspects:
- Creates a default worker thread this executes all intents delivered to
onStartCommand() separate from your application ' s main thread.
Generates a default worker thread that is independent of the main thread to perform all intetnt that are passed to the Onstartcommand () method
- Creates a work queue this passes one intent at a time to your
onHandleIntent() implementation, so you never has to worry about multi -threading.
Generate a task queue to transfer the intent object to your Onhandleintent () method, sending only one intent object at a time, so you don't have to worry about multithreading.
- Stops the service after all start requests has been handled, so you never has to call
stopSelf() .
The service is automatically stopped after all requests (Intent) have been executed, so you do not need to call the Stopself () method to stop the service
- Provides default implementation of that
onBind() returns NULL.
Provides a default implementation of the Onbind () method, which returns null
- Provides a default implementation of that sends the intent to the work queue and then to
onStartCommand() your onHandleIntent() implementation
Provides a default implementation of the Onstartcommand () method, which transfers the intent to the work queue and then each time it takes out a transfer to the Onhandleintent () method from the work queue, in which the corresponding processing of the intent
Above, English from the official SDK, Chinese for my translation.
From the above, all you need to do is implement the Onhandleintent () method to implement what you want to do within the method. In addition, when inheriting intentservice, you must provide a parameterless constructor, and within that constructor you need to call the constructor of the parent class as follows:
Java code
- Public Hellointentservice () {
- Super ("Hellointentservice");
- }
Here is an example to explain:
Java code
- Activity's OnCreate ()
- @Override
- public void OnCreate (Bundle savedinstancestate) {
- super.oncreate (savedinstancestate);
- Setcontentview (R.layout.main);
- StartSer1 = (Button) Findviewbyid (r.id.startser1);
- StopSer1 = (Button) Findviewbyid (r.id.stopser1);
- StartSer2 = (Button) Findviewbyid (R.ID.STARTSER2);
- StopSer2 = (Button) Findviewbyid (R.ID.STOPSER2);
- Log = (TextView) Findviewbyid (R.id.log);
- LogView = (ScrollView) Findviewbyid (R.id.logview);
- Startser1.setonclicklistener (Btnlistener);
- Stopser1.setonclicklistener (Btnlistener);
- Startser2.setonclicklistener (Btnlistener);
- Stopser2.setonclicklistener (Btnlistener);
- Intent = New Intent (myserviceactivity. This, Intentservicedemo. class);
- //Print out the ID of the main thread
- Long id = thread.currentthread (). GetId ();
- Updatelog (TAG + "----> onCreate () in thread ID:" + ID);
- }
Java code
- Service Code
- Package Com.archer.rainbow;
- Import Java.text.SimpleDateFormat;
- Import Java.util.Date;
- Import Android.app.IntentService;
- Import android.content.Intent;
- Public class Intentservicedemo extends Intentservice {
- private static final String TAG = "Intentservicedemo";
- private static final SimpleDateFormat Sdf_date_format = new SimpleDateFormat ("Yyyy/mm/dd hh:mm:ss. SSS ");
- Public Intentservicedemo () {
- super (TAG);
- Myserviceactivity.updatelog (TAG + "----> constructor");
- }
- @Override
- public void OnCreate () {
- super.oncreate ();
- //Print out the ID of the service thread
- Long id = thread.currentthread (). GetId ();
- Myserviceactivity.updatelog (TAG + "----> onCreate () in thread ID:"
- + ID);
- }
- @Override
- public void OnDestroy () {
- Super.ondestroy ();
- Myserviceactivity.updatelog (TAG + "----> OnDestroy ()");
- }
- @Override
- public int Onstartcommand (Intent Intent, int flags, int startid) {
- Myserviceactivity.updatelog (TAG + "----> Onstartcommand ()");
- //Record the time when this request was sent
- Intent.putextra ("Time", System.currenttimemillis ());
- return Super.onstartcommand (intent, flags, Startid);
- }
- @Override
- public void Setintentredelivery (Boolean enabled) {
- Myserviceactivity.updatelog (TAG + "----> Setintentredelivery ()");
- super.setintentredelivery (enabled);
- }
- @Override
- protected void Onhandleintent (Intent Intent) {
- //Print out the ID of the thread used to process intent
- Long id = thread.currentthread (). GetId ();
- Myserviceactivity.updatelog (TAG
- + "----> onhandleintent () in thread ID:" + ID);
- Long time = Intent.getlongextra ("Time", 0);
- Date date = new Date (time);
- try {
- //Print out the corresponding trigger time for each request
- Myserviceactivity.updatelog (TAG
- + "----> Onhandleintent (): Download file ..." + Sdf_date_format.format (DATE));
- Thread.Sleep (3000);
- } catch (Interruptedexception e) {
- E.printstacktrace ();
- }
- }
- }
When the app starts, the interface looks like this:
As you can see from this diagram, the ID of the main thread (UI thread) is 1. Next, click the Start Service 1 button three times in a row to get the following screen:
As can be seen from this figure, Intentservicedemo's OnCreate () is still in the thread ID of 1, indicating that it was executed in the main thread and executed only once. Then, every time I click the button, it will trigger the Onstartcommand () method. Looking closely at the second and third OnCommand () method and the Onhandleintent () print out the statement, you will find that the second to third two-click button and the first click of the button time is not more than 3 seconds, they are continuously executed, which shows what? Note that when the first intent is processed (that is, onhandleintent () is running), the service can still accept the new request, but after accepting the new request it does not execute immediately, but instead puts them in the work queue and waits to be executed.
This is the simple use of intentservice. But if you want to have multiple threads in the service in parallel, you have to have another idea. For example, using the first method, multiple threads are used within the service, but in this case, you can handle the synchronization of the thread well.
"Turn" Android Service II (Intentservice)