Android: Using Intentservice

Source: Internet
Author: User

9.5.2 using Intentservice

Again, at the beginning of this chapter, we already knew that the code in the service was running in the main thread by default, and that it would be easy to get the application not responding if you were dealing with some time-consuming logic directly in the service.
So this time we need to use the technology of Android multithreaded programming, we should open a sub-thread in each specific method of service, and then deal with the time-consuming logic here. As a result, a more standard service can be written in the following form:

public class MyService extends Service {


@Override
Public IBinder Onbind (Intent Intent) {
return null;
}


@Override
public int Onstartcommand (Intent Intent, int flags, int startid) {
New Thread (New Runnable () {
@Override
public void Run () {
Dealing with specific logic
}
}). Start ();
Return Super.onstartcommand (Intent, flags, Startid);
}

}
However, once this service is started, it is running and must call the StopService () or Stopself () method to stop the service. So, if you want to implement a feature that automatically stops a service after it finishes executing, you can write:

public class MyService extends Service {


@Override
Public IBinder Onbind (Intent Intent) {
return null;
}


@Override
public int Onstartcommand (Intent Intent, int flags, int startid) {
New Thread (New Runnable () {
@Override
public void Run () {
Dealing with specific logic
Stopself ();
}
}). Start ();
Return Super.onstartcommand (Intent, flags, Startid);
}

}
It's not complicated, but there are always programmers who forget to turn on the thread or forget to call the Stopself () method. In order to simply create an asynchronous, auto-stop service, Android specifically provides a Intentservice class that solves the two types of embarrassment mentioned earlier, so let's look at its usage.
Create a new Myintentservice class that inherits from Intentservice, as shown in the following code:

public class Myintentservice extends Intentservice {


Public Myintentservice () {
Super ("Myintentservice"); Call the parameter constructor of the parent class
}


@Override
protected void Onhandleintent (Intent Intent) {
Prints the ID of the current thread
LOG.D ("Myintentservice", "Thread ID is" + thread.currentthread (). GetId ());
}


@Override
public void OnDestroy () {
Super.ondestroy ();
LOG.D ("Myintentservice", "OnDestroy executed");
}

}


The first is to provide an argument-free constructor, and must call the parent class's parameter constructor inside.
Then to implement the abstract method of Onhandleintent () in the subclass, you can deal with some specific logic in this method, and do not worry about the ANR problem, because this method is already running in the sub-thread. To prove this, we have printed the ID of the current thread in the Onhandleintent () method. In addition, according to the characteristics of Intentservice, this service should be automatically stopped after the end of the run, so we have rewritten the OnDestroy () method, here also printed a line of logs to verify that the service is not stopped.
Next, modify the code in Activity_main.xml and add a button to start the Myintentservice service as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" android:layout_height= "Match_parent"
android:orientation= "Vertical" >
......
<button android:id= "@+id/start_intent_service" android:layout_width= "match_parent" android:layout_height= "wrap _content "android:text=" Start intentservice "/>
</LinearLayout>
Then modify the code in the mainactivity as follows:

public class Mainactivity extends Activity implements Onclicklistener {
......
Private Button Startintentservice;


@Override
protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);
......
Startintentservice = (Button) Findviewbyid (R.id.start_intent_service);
Startintentservice.setonclicklistener (this);
}


@Override
public void OnClick (View v) {
Switch (V.getid ()) {
......


Case R.id.start_intent_service:
Print the ID of the main thread
LOG.D ("Mainactivity", "Thread ID is" + thread.currentthread ().

GetId ());


Intent intentservice = new Intent (this, myintentservice.class);
StartService (Intentservice);
Break

Default
Break
}
}
}
As you can see, we start the Myintentservice service in the Click event of the Start Intentservice button and print the ID of the main thread here, which is later used for comparison with Intentservice. You will find that the usage of intentservice is no different from ordinary service.
Finally, do not forget that services are required to be registered in the Androidmanifest.xml, as follows:

<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Com.example.servicetest"
Android:versioncode= "1"
Android:versionname= "1.0" >
......
<application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@style/apptheme" >
......
<service android:name= ". Myintentservice "></service>
</application>
</manifest>
Now run the program again, as shown in interface 9.13.

Figure 9.13

After clicking the Start intentservice button, observe the print log in the LogCat, shown in 9.14.

Figure 9.14

As you can see, not only the Myintentservice and Mainactivity are located in the same thread ID, but the OnDestroy () method is also executed, indicating that the Myintentservice does stop automatically after it has finished running. Set open thread and auto stop in one, Intentservice still won a lot of programmers love.

Android: Using Intentservice

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.