Basic setup of simple callback mechanism and establishment of simple callback mechanism
The establishment of a simple callback mechanism consists of the following steps:
1. Write a callback class and write the required Constructor
2. Define an interface and write an abstract method in it. The method body (String data) is the data to be called back.
3. Define a method for setting the interface to obtain the interface object.
4. Define a method for sending data. When this method is called, the data is automatically sent and accepted.
As follows:
Package com. zzw. huidiao; public class SendData {private OnSendDataListener mOnSendDataListener = null; // 1. write out the required constructor public SendData () {}// 2. define an interface and write an abstract method in it. The method body (String data) is the public interface OnSendDataListener {public void onAcceptData (String data) obtained by the callback.} // 3. define a method for setting the interface. Obtain the interface object public void setOnSendDataListener (OnSendDataListener mOnSendDataListener) {this. mOnSendDataListener = mOnSendDataListener;} // 4. defines a method for sending data. When this method is called, the data is automatically sent and the public void send (String data) {mOnSendDataListener is accepted. onAcceptData (data );}}
When using this method, you only need to new the object of this method, and then use the setOnSendDataListener () method to obtain the listener. Then, call the send () method to trigger the listener to obtain the callback data.
The following code:
Package com. zzw. huidiao; import com. zzw. huidiao. sendData. onSendDataListener; import android. app. activity; import android. OS. bundle; import android. util. log; public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); SendData mSendData = new SendData (); mSendData. setOnSendDataListener (new OnSendDataListener () {@ Override public void onAcceptData (String data) {Log. d ("data received through callback", data) ;}}); mSendData. send ("data sent by calling the send method through a callback object ");}}
The result is as follows: