Android interface callback mechanism details, android callback

Source: Internet
Author: User

Android interface callback mechanism details, android callback

When using the interface callback, I found a common error, that is, the implementation in the callback function may be done using multithreading or asynchronous tasks, this will cause us to expect the callback of the function to complete and return the result of a main function. The actual result is not feasible, because if the callback is multi-thread, you cannot synchronize with the main function, that is, the returned data is incorrect, which is a very hidden error. So is there any good way to implement linear data transfer? First, we will introduce the principle of the callback mechanism.


Callback Function


A callback function is a function called by a function pointer. If you pass the pointer (address) of a function as a parameter to another function, when this pointer is used to call the function to which it points, we will say this is a callback function. The callback function is called by another party when a specific event or condition occurs instead of by the implementer of the function. It is used to respond to the event or condition.

Explanation:
Client program C calls A function A in service program S, and then S calls A function B in C at some time. For C, this B is called A callback function. For example, the window procedure function under Win32 is a typical callback function. Generally, C does not call B by itself. C provides B for S to call it, and C has to provide it. Because S does not know who the B surname provided by C is, S will agree with the interface specification (function prototype) of B ), then C tells S to use the B function through a function R of S in advance. This process is called the registration of the callback function, and R is called the registration function. The callback mechanism is used by Web Service and Java RMI to access remote server programs.
The following is a common example:
One day, I called you to ask questions. Of course it was a difficult problem. You couldn't figure out a solution at the moment, and I couldn't wait there with a phone. So we agreed: after you have come up with a solution, you can call me to notify me. In this way, I will stop calling to handle other things. After XX minutes, my cell phone rang, and you said with high enthusiasm that the problem had been fixed, so you should handle it like this. The story ends here. This example illustrates the "Asynchronous + callback" programming mode. When you call a mobile phone to tell me that the result is a "Callback" process. My mobile phone number must be told before. This is the registration callback function; my mobile phone number should be valid and the mobile phone can receive your call. This is the callback function that must comply with the interface specifications.
JAVA does not allow direct pointer operations. How is its callback implemented?
Answer: It is implemented through interfaces or internal classes.
JAVA method callback is a means to define and share functions, and is a coupling design concept. As an architecture, you must have your own runtime environment and provide your implementation interfaces.
1. Define the interface Callback, including the callback method Callback ()
2. Declare a Callback interface object mCallback in a class Caller
3. Assign the Caller object interface member (mCallback) An internal class object in the program, such
New Callback (){
Callback (){
// Function implementation
}
}

In this way, the callback () method can be called by the mCallback interface member of the Caller object as needed to complete the callback.


Use of callback mechanism in Android framework


The Activity defines many methods to be called in different states of the life cycle. These methods are empty implementations. the system framework needs to be called and the user needs to call them.
Instance (simulate a Button click event listener on the Android Interface ):
A. Define the interface
Public interface OnClickListener {
Public void OnClick (Button B );
B. Define the Button
Public class Button {
OnClickListener listener;
Public void click (){
Listener. OnClick (this );
}
Public void setOnClickListener (OnClickListener listener ){
This. listener = listener;
}
}
C. Assign the OnClickListener interface object to the interface member of the Button.
Public class Activity {
Public Activity (){
}
Public static void main (String [] args ){
Button button = new Button ();
Button. setOnClickListener (new OnClickListener (){
@ Override
Public void OnClick (Button B ){
System. out. println ("clicked ");
}
});
Button. click (); // user click, System call button. click ();
}
}

The Mechanism is as follows. How does one transmit data through interfaces? Code:


/** @ Author sunglasses * @ category encapsulate the get method using the xUtils framework. IOAuthCallBack is the data interface callback, And the send method contains the asynchronous task method, * traditional data return methods may return incorrect data. */Public class xUtilsGet {public void getJson (String url, RequestParams params, final IOAuthCallBack iOAuthCallBack) {HttpUtils http = new HttpUtils (); http. configCurrentHttpCacheExpiry (1000*10); http. send (HttpMethod. GET, url, params, new RequestCallBack <String> () {@ Overridepublic void onFailure (HttpException arg0, String arg1) {// TODO Auto-generated method stub} @ Overridepublic void onSuccess (ResponseInfo <String> info) {// TODO Auto-generated method stubiOAuthCallBack. getIOAuthCallBack (info. result );}});}}

I used the xUtils development framework and used the interface callback when returning data. The interface definition is as follows:

  public interface IOAuthCallBack {public void getIOAuthCallBack(String result);}

Upper-layer functions are defined as follows:

public void getCataJson(int cityId,IOAuthCallBack iOAuthCallBack) {String url = "http://xxxxxxx";RequestParams params = new RequestParams();        params.addQueryStringParameter("currentCityId", cityId+"");getJson(url,params,iOAuthCallBack);}


Getcatajson is called in the class you want to get the data, and then input parameters and interface objects. The interface object must process the final data. The specific mechanism is as follows. In this way, the multi-thread data inconsistency in the interface callback can be avoided.

Reference: http://www.cnblogs.com/vtianyun/archive/2012/06/19/2555427.html

If you have any questions, please leave a message, reprinted with the source. http://blog.csdn.net/rain_butterfly/article/details/38274137


JAVA callback mechanism

Basically, this is a callback mechanism. The interface passed in the method is implemented as an interface of the Listener. when calling the method, the instance of the specific interface implementation can also be passed in advance (usually called registering the Listener ). This situation is common in the event mechanism in Java Swing programming.

There are always some interfaces between software modules. In terms of calling methods, they can be divided into three types: Synchronous call, callback and asynchronous call.

Synchronous call: a blocking call, which is a one-way call that the caller must wait for the execution of the other party to complete;

Callback: A two-way call mode, that is, the called party also calls the interface of the other party when the interface is called;

Asynchronous call: a mechanism similar to a message or event, but its call direction is the opposite. When an interface service receives a message or an event, the customer is notified (that is, the customer's interface is called ).

Asynchronous call implementation is a situation of callback. For example, a method can be returned in advance, and a specific logical execution can be called back and forth by another thread after the execution is completed, notifies the caller.

JAVA: The interface callback cannot be understood.

In the Example class, have you created two instance objects, new Student () and new Teacher. They only reference the interface (that is, the above interface references the subclass Instance Object) and reference it through the interface. the method in the interface actually follows the interface method rewritten by the subclass (to see who installed the object in the interface). This is the most commonly used method in future projects. I will understand it later.

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.