Study on Android [6]-message mechanism, asynchronous and Multithreading

Source: Internet
Author: User
With the framework, we don't have to deal with naked OS APIs and do repetitive and complicated things. However, there is no free lunch in the world. We still need to learn how to use different frameworks efficiently and correctly. Many methods to deal with a specific problem are different in different frameworks.
In Android, the lower layer is the kernel of Linux, but the framework made by the upper layer of Java makes all the encapsulation airtight. Taking message processing as an example, in MFC, we can use pretranslatemessage and other Dongdong to freely process messages. in C #, the boss of Anders hejlsberg said, he opened a "life-saving window" for us to the bottom layer, but unfortunately, in Android, the window was closed (at least I didn't find it now ...).
In Android, if you want to process some messages (such as keydown...), you must find some overload functions provided by activity for you (such
Such as onkeydown...) or various listener (such as onkeydownlistner ...). The benefits of doing so are obvious,
The more freedom there will be more danger and more obscure, the more complicated it is to use it and save your mind. This is what a well-designed framework should provide. For my current jobs
Cheng said, I have no BT requirements that can't be achieved under the current API, and Google's design MS is still very nice.
However, the world is cruel. Sometimes we still need mechanisms to provide message distribution and processing, because some jobs cannot be processed synchronously by direct calls, at the same time, it cannot pass
Embedded message distribution and interface settings, such as scheduled touch of events, asynchronous processing of cyclic events, and high time-consuming work. In Android, it provides some interesting ways to do this.
(Sorry, I don't know much about it. I have never seen a similar gameplay &&
Hyperled_^) under the mouth. It has an android. OS. Handler class that accepts a logint parameter. As its name suggests, this class is encapsulated to characterize message loops.
Class. By default, Handler accepts the message loop instances in the current thread. That is to say, a message loop can be distributed by multiple objects in the current thread,
(In the UI thread, the system already has an activity to process, and you can start several handler to process it ...). Instantiate
After handlerinstance, you can use sendmessage and other message sending mechanisms to send messages, and use handlemessage and other functions to distribute and remove messages.
. But! The handlerinstance can receive only messages constructed by handlerinstance. obtainmessage (
You can also manually add a message and configure it to the handlerinstance for processing. I am not interested in analyzing its identification mechanism.
You can play it yourself ^_^ ). That is to say, A, B, C, and D can all process message distribution in the same thread, but each of them can only process its own message,
This obliterates the possibility that B wants to secretly enter the territory of A, and the greater the number of agents, the more possible it is to do some non-copy tasks (theoretically, B may pretend that the messages are the same as those of a's family, I didn't try to challenge Google's
IQ, self-research required by Bt ^_^ ). In this way, both flexibility and security are taken into account, and it will be simple to use. I am the master of my website, so I don't have to be hurt or innocent. It is a great deal to hold it left and right.
Happy things...
Obviously, message senders are not limited to their own threads. No one can only perform scheduled, delayed, and other things. When instantiating handler, logoff can be any thread
As long as there is a handler pointer, any thread can also sendmessage (this construction method is also very interesting, you can construct it by passing the Logoff of the B thread in thread.
Handler can also be constructed in the B thread, which brings a huge variable to the memory management method ...). However, a rule must not be broken, that is, a non-UI thread cannot touch the UI class.
There are many solutions on different platforms (if you have more than one interest, you can take a look at one I wrote a long time ago, no Sb, no money ). I specifically followed the asyncqueryhandler class in Android to learn about Google's official solutions.
Asyncqueryhandler is a sub-class of handler. As mentioned in the document, if you are dealing with contentprovider-related content, you do not need to define a set of things,
The async method can be used simply. I want to refer to the asyncqueryhandler class. This class is a typical template class, which is contentprovider
The addition, deletion, modification, and query of provides a good interface, provides a solution architecture, final some methods, and leave some methods empty. By deriving, instantiate some methods (not every pair
Contentprovider needs to add, delete, modify, and query all for processing. I think this is also the reason why this class is left empty by default rather than abstracting some methods. Internally, this class
It hides the details of multi-threaded processing. When used, you will feel very convenient. Take query as an example. You can use this method:

// Define a handler and use an anonymous class to process only query. Therefore, only the onquerycomplete function is rewritten:
Queryhandler = new asyncqueryhandler (this. getcontentresolver () {// The input is a contentresolver instance, so the handler class must be instantiated after oncreate
@ Override
Protected void onquerycomplete (INT token, object cookie, cursor ){
// Here you can get a cursor and the additional tokens and cookies you pass in.
// This method is in the current thread (if the default logoff is passed in), the UI information can be set freely.
}
};

// You only need to call startquery (INT token, object cookie, contenturi Uri,
String [] projection, string selection, string [] selectionargs, string
Sortorder) function:
Queryhandler. startquery (token, Cookie, Uri, projection, selection, selectionargs, sortby );

It can be seen how simple this class is to be used (its implementation is not very easy, because I tried to create a wheel * _ *), which is countless times simpler than using handler directly. But what makes me feel lonely is, no
I know that no one is doing asynchronous contentprovider access, or is it too mentally retarded to use this class (I have been exploring this method for a long time, but am I really so weak @ _ @)?
Or everyone has their own tips. From the SDK to the Internet, there is no usage instructions for this class. And I happened to sadly find that this class actually has a lot of problems. For example, if he eats an exception, it is simply a simple mistake.
Single return NULL pointer (this is not to blame him, you can look here ...); when you pass in a null contentresolver, there is no exception, but inexplicably discard all the messages, so that you are stuck in a hard wait and don't know why. What's more furious is that, there is a bug in token transfer (difficult
Or I am not using IT & _ &), from the token passed in startxx to onxxcomplete, it will be changed to 1, and the document clearly says that two are one
(My solution is to use cookie as the token, which won't be lost *_*). However, I have no plans to abandon it for the moment. Although no one cares about it, even though there are a bunch of problems
I made a new wheel, but in order to save some boring work, I decided to cheat myself...
It is still a habit to run the question. In fact, I want to talk about its multi-thread asynchronous processing solution strategy through countless debugger follow-up on this class. The basic policy is as follows:

1. when you instantiate an asyncqueryhandler class (including its subclass ...), it constructs a thread in one piece (detailed later ...), this thread will build a message loop.
2. Get the pointer to the message loop and use it as a parameter to instantiate another handler class, which is an internal class. So far, there are two threads, each having a handler to process messages.
3. When onxxx is called, the request is encapsulated into an internal parameter class in the xxx function, which serves as the parameter of the message and sends the message to another thread.
4. In the handler of the thread, accept the message, analyze the input parameters, perform the xxx operation with the contentresolver passed in during initialization, and return the cursor or other return values.
5. Construct a message, bind the returned values and other related content to the message, and send the message back to the main thread.
6. the handlemessage method of the default asyncqueryhandler class of the main thread (which can be customized, but because it is an internal class, it is basically meaningless ...) the message is analyzed and forwarded to the corresponding onxxxcomplete method.
7. The onxxxcomplete method rewritten by the user starts to work.

This is what it has done secretly. It is basically easy to understand. The only thing I'm curious about is its thread management method. I guess it is a single-piece mode.
The instantiation of the first asyncqueryhandler will lead to the creation of a thread. From then on, this thread will become an old virgin, and all the contentresolver-related work will be
This thread is used in a unified manner. I personally think this solution is awesome. The life cycle of this thread is hard to estimate, and when you have a contentprovider request, judge you
It is not excessive to perform more similar operations. Even if it is wrong, the cost is only an endless thread (same as the process to survive...), in exchange for simple lifecycle management and countless thread Life and Death overhead
Save. At the same time, another very important issue involves data synchronization in a single piece. Each class has its own handler class, which does not interfere with each other. distribution can be performed separately. When multiple data entries are displayed
When the request is obtained, it may be minimal on the same contentresolver, which avoids blocking. All in all, this solution and the overall Android design are heaven-made.
.
Therefore, it is recommended that you simulate a set of non-contentprovider operations that require asynchronous multi-thread execution. Of course, the specific situation is analyzed, it is hard to learn Marxism-Leninism...

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.