Use Intentservice to perform background tasks in Android

Source: Internet
Author: User

Intentservice provides a way to perform tasks in a background thread and is suitable for working with long-performing background tasks.

Advantages:

(1) Intentservice runs in a separate thread and does not block the UI thread

(2) Intentservice not affected by life cycle

Disadvantages:

(1) You cannot interact directly with the UI, you can use broadcast

(2) Sequential execution of a request, the second request can only be executed after the first request has been executed

(3) The request cannot be interrupted


Steps to use Intentservice:

(1) Start service through StartService in activity and pass parameters.

(2) Receive parameters in the service, do time-consuming processing, processing complete, send Broadcat, and transfer the results of processing

(3) The activity registers Broadcastreceiver, listens to the broadcast, updates the UI.


See an example:

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button btn = (button) This.findviewbyid (R.ID.BTN); Btn.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//Start service via StartService and pass parameters. Intent mserviceintent = new Intent (mainactivity.this,rsspullservice.class); Mserviceintent.setdata (Uri.parse ("http ://www.baidu.com/")); MainActivity.this.startService (mserviceintent);}});        /register Broadcastreceiver, monitor broadcast intentfilter statusintentfilter = new Intentfilter (constants.broadcast_action); Sets the filter ' s category to DEFAULT statusintentfilter.addcategory (intent.category_default);D ownloadstaterecei Ver mdownloadstatereceiver = new Downloadstatereceiver ();//registers the Downloadstatereceiver and its intent Filtersloc Albroadcastmanager.getinstance (This). Registerreceiver (Mdownloadstatereceiver, statusintentfilter);} Private CLDownloadstatereceiver extends Broadcastreceiver {@Overridepublic void OnReceive (context context, Intent Intent) { String data = Intent.getstringextra (Constants.extended_data); LOG.E ("Test", data); Toast.maketext (context, data, Toast.length_short). Show ();}}}

public class Rsspullservice extends Intentservice {public rsspullservice () {Super ("Rsspullservice");} @Overrideprotected void Onhandleintent (Intent workintent) {//Receive parameters, do time-consuming processing, processing complete, send broadcatstring localurlstring = Workintent.getdatastring ();    String data = Download (localurlstring), Intent localintent = new Intent (constants.broadcast_action);    Puts the status into the Intentlocalintent.putextra (Constants.extended_data, DATA);    Broadcasts the Intent to receivers in this app. Localbroadcastmanager.getinstance (This). Sendbroadcast (localintent);} private string Download (String localurlstring) {try{url url = new URL (localurlstring); HttpURLConnection conn = (httpurlconnection) url.openconnection (); InputStream in = Conn.getinputstream (); Bytearrayoutputstream out = new Bytearrayoutputstream (); byte[] buff = new Byte[1024];int len = 0;while (len = in.read (Buff ))! =-1) {out.write (Buff,0,len);} In.close (); return new String (Out.tobytearray ());} catch (Exception e) {e.printstacktrace (); return "";}}} 

public class Constants {//defines a custom Intent actionpublic static final String broadcast_action = "Com.example.androi D.threadsample.broadcast ";//defines the key for the status ' Extra ' in an intentpublic static final String extended_data_s Tatus = "Com.example.android.threadsample.STATUS";p ublic static final String extended_data = " Com.example.android.threadsample.DATA ";}

Androidmanifest.xml:

<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "        Com.example.android.intentservicedemo "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk  android:minsdkversion= "android:targetsdkversion="/> <!--Requires this permission to download RSS  Data from Picasa---<uses-permission android:name= "Android.permission.INTERNET"/> <!--defines    The application. --<application android:icon= "@drawable/icon" android:label= "@string/app_name" > <acti Vity android:name= "com.example.android.intentservicedemo.MainActivity" android:label= "@string/activi                Ty_title "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/>        <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter>        </activity> <!--    No Intent filters is specified, so android:exported defaults to "false".        The service is a available to this app. --<service android:name= "Com.example.android.intentservicedemo.RSSPullService" Androi D:exported= "false"/> </application></manifest>

Reference: http://developer.android.com/training/run-background-service/index.html


Use Intentservice to perform background tasks in Android

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.