Research on the filter in Android

Source: Internet
Author: User

First, overview:The filter constrains the data by filtering the mode by calling filter (Charsequence) or filter (Charsequence, Android.widget.Filter.FilterListener) These asynchronous methods to complete.     Once the above method is called, the filter request is submitted to the request queue for processing, and the operation cancels those requests that were previously submitted but not yet processed. The work process can be simply understood as having a task force listed in the processing task, but only one task at a time. Each time a task is submitted, the task is executed immediately if there are no tasks being performed in the work queue. If there is a task to perform, the task waits. If there are tasks being performed in the queue, and there are waiting tasks, all the waiting tasks are canceled and the task is put into the waiting process. So at any time, there can be at most one task in execution and one task waiting.
second, the Main method:   public void final filter (charsequence constraint, Filterlistener listener); Performs an asynchronous filtering operation request.
Protected abstract Filterresultsperformfiltering(charsequence constraint); Invoking a worker thread to filter the data according to constraints, the subclass must implement the method to perform the filtering operation. The filter results are returned as Filter.filterresults and then published in the UI thread through the Publishresults (Charsequence, Android.widget.Filter.FilterResults) method.

protected abstract voidPublishresults(charsequence constraint, filterresults results);   Publish filtering results in the user interface by calling the UI thread.
three, the realization principle:
The filtered operation is performed on a newly opened worker thread, and the filtered results are thread publish the UI line.
1.2 handler are used in the filter class:RequestHandleris used to handle the filtering operation,Resulthandleris used to publish the filter results.             private Handler mthreadhandler;            Private Handler Mresulthandler;                            public Filter () {&NB Sp                mresulthandler = new Resulthandler ();        &N Bsp  }            is visible, Resulthandler is created in the construction method, which is generally bound to the UI thread, and finally filters out the results, Publishresults is the distribution of messages through Resulthandler, so the final callback process is performed on the UI thread, and the implementation is ingenious and can be learned.             Questions: If the filter class was created on a thread, then it was not executed in the UI thread when Publishresults? The actual result is that if the thread new filter object is in the child line, the error is directly because the thread has not yet constructed the Looper object and needs to call the Looper.prepare () method before new Handler ().           2.filter request process.           Public final void filter (charsequence constraint, Filterlistener listener) {  &nbs P            synChronized (mLock) {    
if (Mthreadhandler = = null) {Handlerthread thread = new Handlerthread (Thread_name, Android.os.Pr Ocess.                     Thread_priority_background);                     Thread.Start ();                Mthreadhandler = new RequestHandler (Thread.getlooper ()); }
                 final long delay = (Mdelayer = = null)? 0:mdelayer.getpostingdelay (constraint);                    &NBSP ;        message Message = Mthreadhandler.obtainmessage (filter_token);                     requestarguments args = new requestarguments ();                 //Make sure we use a immutable copy of the constraint, so that    &N Bsp            //it doesn ' t change while the filter operation are in progress    &NBSP ;            args.constraint = constraint! = null? Constraint.tostring (): null;                 args.listener = listener;                 message.obj = args;                     mthreadhandler.removemessages (Filter_token);                  mthreadhandler.removemessages (finish_token);                 mthreadhandler.sendmessagedelayed (message, delay);      & nbsp      }         }               You can see it here Creates a Handlerthread object, which is a child thread, and then creates a requesthandler that handler binds to the child thread. All subsequent filtering requests are distributed through RequestHandler, and all filtering operations are performed in the child threads.           All messages that have not been executed are canceled by RequestHandler before this request is initiated.                Take a look at RequestHandler's internal implementation,          &N Bsp              case Filter_token:          //processing the filtering request hererequestarguments args = (requestarguments) msg.obj; try {args.results =performfiltering(Args.constraint);                        } catch (Exception e) {args.results = new filterresults ();                    LOG.W (Log_tag, "an exception occured during performfiltering ()!", e); } finally {message =Mresulthandler.obtainmessage(what);                        Message.obj = args;                    Message.sendtotarget (); } //You can see here that the Performfiltering () method is called to filter, and then the results are published through Resulthandler.
                    synchronized (mLock) {        &N Bsp               if (mthreadhandler! = null) {            &N Bsp               Message finishmessage = Mthreadhandler.obtainmessage (Finish_token); nbsp                           Mthreadhandler.sendmessagedelay Ed (finishmessage,; )                      }                   }                  & nbsp / /After all operations have been performed, a 3-second delay is sent to send an end message that terminates the message loop thread the Handlerthread line. This place is ingenious: 1. If a continuous filter request is initiated, the Handlerthread thread created earlier will be used to process the filtering operation, do not create threads frequently, excessive loss performance, 2. If there is no filtering request for a long time, such as more than 3s, the thread is terminated because the thread is actually an idle thread. Can be terminated, the same reduction in performance loss. Note that the lock operation is to be added.
Break Case Finish_token: //Handle terminating the operation of the thread hereSynchronized (MLock) {if (Mthreadhandler! = null) {Mthreadhandler.getlooper (). Quit ();mthreadhandler = null;}} break;
Iv. Summary:
1. Cleverly used the Handlerthread to create a thread with Looper.     2. Implement asynchronous filtering query operations with handler that are bound to different threads.     3. Implementations similar to Autocompletetextview are implemented through filter. 4. The reference filter is implemented in such a way that the same design method can be used where frequent asynchronous queries are required.     For example, the input box in the network automatic prompt function. The 5.AsyncQueryHandler implementation principle is similar to that of using Handlerthread, which uses a worker thread to handle things.

Research on the filter 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.