Android Asynchronous task

Source: Internet
Author: User
<span id="Label3"></p><p><p>This paper mainly discusses the various asynchronous loading mechanisms provided by Android platform, including their application scenarios, usage methods and so On.</p></p>1. asyntask<p><p>The asyntask is suitable for operations that can last for a few seconds, and it is recommended to use the multithreaded framework under the Java.util.concurrent package for long-duration Operations.</p></p><p><p>The actual type of the following three generic parameters needs to be provided when defining a asyntask:</p></p> <blockquote> <blockquote> <ol> <li>Params: the type of arguments that are passed to the background thread for execution</li> <li>Progress: the type used to indicate progress during a background thread execution</li> <li>Result: computed result type returned by the background thread</li> </ol> </blockquote> </blockquote><p><p>Asynctask an asynchronous task into four steps:</p></p> <blockquote> <blockquote> <ol> <li>OnPreExecute (): This method executes before the task is started and is called in the UI thread, which performs some task-setting actions, such as displaying the loaded progress bar in the interface</li> <li>Doinbackground (Params ...): This method is called in a background thread, which occurs after the OnPreExecute execution is complete, and the logic of the background operation is included in this method When defining asyntask, the type that the params parameter represents is the type of the Doinbackground parameter array, and the type of the method return value is the parameter type of the OnPostExecute method. During the execution of this method, you can call publishprogress (Progress ...). method to update the progress, the Publishprogress method triggers the Onprogressupdate method to be called in the UI thread</li> <li>Onprogressupdate (Progress ...): When a background thread calls the Publishprogress method, This method is triggered on the UI thread, which is primarily used to update the execution progress of the background thread, or to print the log in the interface</li> <li>OnPostExecute (result): when the background thread finishes executing, the method is called by the UI thread, and the return result of the background thread is passed in as a parameter to the METHOD.</li> </ol> </blockquote> </blockquote><p><p><strong>Attention:</strong></p></p> <blockquote> <blockquote> <ol> <li>The Asyntask class must be loaded into the UI thread</li> <li>The Asynctask instance must be created in the UI thread</li> <li>The Execute () method must be executed in the UI thread</li> <li>Do not explicitly invoke methods such as onpreexecute, onpostexecute, doinbackground, onprogressupdate, etc.</li> <li>Each task instance can only be executed once</li> </ol> </blockquote> </blockquote><p><p>The following example comes from the official Android Documentation:</p></p><pre><pre><code>private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); }}</code></pre></pre><p><p>Perform:</p></p><pre><pre><code>new DownloadFilesTask().execute(url1, url2, url3);</code></pre></pre>2. Loaders<p><p>The loaders is suitable for background operations where events are relatively long.</p></p><p><p><strong>Related classes</strong></p></p> <blockquote> <blockquote> <ul> <li>Loadermanager:loadermanager is bundled with activity or fragment to help activity/fragment manage loader, Each activity or fragment can bind up to one loadmanager, and one loadermanager can manage multiple loader</li> <li>Loadermanager.loadercallbacks: This interface is typically implemented by activity/fragment, and the interface contains declarations of several callback methods that are called by Loadermanager at the appropriate time</li> <li>Loader: a class that actually loads data asynchronously to update the interface data by detecting data changes in the data source</li> <li>Asynctaskloader: an abstraction that provides Asyntask functionality loader</li> <li>A cursorloader:asyntaskloader subclass that queries Contentresolver and returns a cursor Object.</li> </ul> </blockquote> </blockquote><p><p><strong>Attention</strong></p></p> <blockquote> <blockquote> <ol> <li>In the use of loader generally do not directly inherit the loader class, but inherit Asynctaskloader</li> <li>Subclasses generally must implement onstartloading, onstoploading, onforceload, onreset methods</li> </ol> </blockquote> </blockquote>2.1 Start Loader<p><p>In general, the loader is initialized in the OnCreate method of the activity or the Onactivitycreated method of the fragment, and the method of initializing loader is as Follows:</p></p><pre><pre><code>getLoaderManager().initLoader(0, null, this);</code></pre></pre><p><p>The Initloader method contains the following parameters:</p></p> <blockquote> <blockquote> <ul> <li>Unique ID used to identify the loader, in this case the ID is 0</li> <li>Loader constructs the required parameters, in this case the arguments are null</li> <li>An object that implements the Loadermanager.callbacks interface, and when an event occurs, Loadermanager calls the corresponding callback method</li> </ul> </blockquote> </blockquote><p><p>For activity/fragment, it is only necessary to interact with loadermanager, Loadermanager is responsible for managing the loader lifecycle, maintaining loader and the state of the data; so activity/ Fragment generally do not interact directly with Loader.</p></p>2.2 Restart Loader<p><p>For the Initloader method in loadermanager, when the loader of the corresponding ID number does not exist, Loadermanager calls the Oncreateloader method of the third argument to create a new loader, Otherwise Loadermanager will reuse the loader that already exists for the corresponding ID. however, in some scenarios, we do not need to have loader data, for example, for a query, the query condition changes, The corresponding result set will also Change. At this point, we can trigger a new query by restarting loader and get a new set of Data. Here's How to restart Loader:</p></p><pre><pre><code>getLoaderManager().restartLoader(0, null, this); //对应参数的意义和上面的initLoader相同</code></pre></pre>3.2 Using Loadermanager callbacks<p><p>The loadermanager.loadercallbacks consists of three methods as Follows:</p></p> <blockquote> <blockquote> <ul> <li>Oncreateloader (): instantiates a loader of a given ID</li> <li>onloadfinished (): Called when loader completes the data load, similar to OnPostExecute in Asyntask</li> <li>Onloaderreset (): resets an already existing loader so that its data is not available</li> </ul> </blockquote> </blockquote><p><p>Here are some examples from the official Android Documentation:</p></p><pre><code>public static class Cursorloaderlistfragment extends Listfragment implements onquerytextlistener, Loadermanager.loader Callbacks<cursor> {//this was the Adapter being used to display the list ' s Data. Simplecursoradapter madapter; If non-null, The current filter of the user has Provided. String mcurfilter; @Override public void onactivitycreated (Bundle Savedinstancestate) {super.onactivitycreated (savedinstancestate ); Give some text to display if there is no Data. In a real//application the would come from a resource. Setemptytext ("No Phone numbers"); We have a menu item to show in action bar. Sethasoptionsmenu (true); Create an empty adapter we'll use to display the loaded Data. Madapter = new Simplecursoradapter (getactivity (), android. r.layout.simple_list_item_2, null, new string[] {contacts.display_name, contacts.contact_status}, New int[] {andRoid. r.id.text1, Android. r.id.text2}, 0); Setlistadapter (madapter); Prepare the Loader. Either re-connect with an existing one,//or start a new one. Getloadermanager (). initloader (0, null, this); } @Override public void Oncreateoptionsmenu (menu menu, menuinflater inflater) {//place an action bar item For Searching. MenuItem item = Menu.add ("Search"); Item.seticon (android. r.drawable.ic_menu_search); Item.setshowasaction (menuitem.show_as_action_if_room); Searchview SV = new Searchview (getactivity ()); Sv.setonquerytextlistener (this); Item.setactionview (sv); } public boolean Onquerytextchange (String Newtext) {//called when the Action Bar search text has Changed. Update//the Search filter, and restart the loader to does a new query//with this filter. Mcurfilter =! Textutils.isempty (newtext)? newtext:null; Getloadermanager (). restartloader (0, null, this); Return true; } @Override public boolean onquerytextsubmit (String query) {//Don ' t care about This. Return true; } @Override public void Onlistitemclick (ListView l, View v, int position, long id) {//Insert desired Behav The IOR Here. LOG.I ("fragmentcomplexlist", "Item clicked:" + id); }//these is the Contacts rows that we'll Retrieve. Static final string[] contacts_summary_projection = new string[] {contacts._id, contacts.display_name, contacts.contact_status, contacts.contact_presence, contacts.photo_id, contacts.lookup_key,}; Public loader<cursor> oncreateloader (int. id, Bundle Args) {//this is called when a new Loader needs to B E Created. This//sample is only have one Loader, so we don ' t care about the ID. first, pick the base URI to use depending on whether we is//currently Filtering. Uri baseUri; If (mcurfilter! = Null) {baseUri = Uri.withappendedpath (contacts.content_filter_uri, uri.encode (mcurfilter )); } Else {baseUri = contacts.content_uri; }//now Create and return a cursorloader that would take care of//creating a Cursor for the data being dis Played. String select = "((" + Contacts.display_name + "notnull) and (" + Contacts.has_phone_number + "=1) and (" + contacts.display_name + "! =")) "; return new Cursorloader (getactivity (), baseUri, contacts_summary_projection, select, null, CONTACTS. Display_name + "COLLATE Localized ASC"); } public void onloadfinished (loader<cursor> Loader, Cursor data) {//swaps the new Cursor in. (the framework would take care of closing the//old cursor once we return.) Madapter.swapcursor (data); } public void Onloaderreset (loader<cursor> Loader) {//this was called when the LASt Cursor provided to onloadfinished ()//above are about to being closed. We need to make sure we is no//longer using it. Madapter.swapcursor (null); }</code></pre><p><p>}</p></p> <p><p>Android Asynchronous task</p></p></span>

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.