Use IntentService in Android to execute background tasks

Source: Internet
Author: User

Use IntentService in Android to execute background tasks

IntentService provides a way to execute tasks in background threads and is suitable for processing background tasks with long execution time.

Advantages:

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

(2) IntentService is not affected by the lifecycle.

Disadvantages:

(1) You cannot directly interact with the UI. You can use Broadcast.

(2) requests are executed sequentially. The second request can be executed only after the first request is executed.

(3) requests cannot be interrupted

 

Steps for using IntentService:

(1) start the service through startService in the Activity and pass parameters.

(2) receive parameters in the Service, perform time-consuming processing, complete processing, send Broadcat, and pass the processing result

(3) Register BroadcastReceiver in the Activity, listen to broadcasts, and update the UI.

 

Let's look at 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 the service through 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 and listen to broadcast IntentFilter statusIntentFilter = new IntentFilter (Constants. BROADCAST_ACTION); // Sets the filter's category to DEFAULT statusIntentFilter. addCategory (Intent. CATEGORY_DEFAULT); DownloadStateReceiver mDownloadStateReceiver = new DownloadStateReceiver (); // Registers the DownloadStateReceiver and its intent filtersLocalBroadcastManager. getInstance (this ). registerReceiver (mDownloadStateReceiver, statusIntentFilter);} private class DownloadStateReceiver 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) {// receives parameters for time-consuming processing and processing, send BroadcatString localUrlString = workIntent. getDataString (); String data = download (localUrlString); Intent localIntent = new Intent (Constants. BROADCAST_ACTION); // Puts the status into the IntentlocalIntent. putExtra (Constant S. 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.android.threadsample.BROADCAST;// Defines the key for the status extra in an Intentpublic static final String EXTENDED_DATA_STATUS = com.example.android.threadsample.STATUS;public static final String EXTENDED_DATA = com.example.android.threadsample.DATA;}

AndroidManifest. xml:

 

 

 

 

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.