Use Intentservice to run background tasks in Android

Source: Internet
Author: User

Intentservice provides a way to run tasks in a background thread that is suitable for working with long-running background tasks.

Strengths:

(1) The Intentservice executes in a separate thread. Does not clog the UI thread

(2) Intentservice not affected by life cycle

Disadvantages:

(1) cannot interact directly with the UI and can be used broadcast

(2) Run the request sequentially, the second request only has the ability to run after the first request has run

(3) The request cannot be interrupted


Steps to use Intentservice:

(1) Start service through StartService in activity and pass the number of references.

(2) The service receives the parameter, does the time-consuming processing. Process complete, send Broadcat, and pass the processing results

(3) activity in the register Broadcastreceiver, listen to the broadcast, update the UI.


Look at the 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 the number of references. 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 is 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>

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


Use Intentservice to run background tasks in Android

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.