java Callback simple use summary

  • 2020-06-23 00:16:02
  • OfStack

1. What is Callback and when do you need Callback

Callback callback mean, 1 we need two classes need to be out with each other, one kind of the dynamic data is passed to the other one class, you can use this way, such as the inside of the Android Launcher classes and class LauncherModel, the method to realize there is interface many LauncherModel, Launcher LauncherModel interface, implementation method, pass the data to LauncherModel class.

2. Simple code understanding

1) CallBack. java file contents are as follows


public class CallBack { 
 private Callback mCallback; 
 
 public CallBack(Callback callback) { 
 this.mCallback = callback; 
 } 
 public static interface Callback { 
 public void before(); 
 public void after(); 
 } 
 
 public void doThing() { 
 mCallback.before(); 
 System.out.println("hello chenyu"); 
 mCallback.after(); 
 } 
} 

2) TestCallBack. java file is as follows


 public class TestCallBack implements CallBack.Callback{ 
 
 public CallBack mCallback; 
 
 public TestCallBack() { 
 mCallback = new CallBack(this); 
 } 
 
 @Override 
 public void before() { 
 System.out.println("hello before"); 
 } 
 
 @Override 
 public void after() { 
 System.out.println("hello before"); 
 } 
 
 public void doThing() { 
 mCallback.doThing(); 
 } 
 
 public static void main(String[] args) { 
 new TestCallBack().doThing(); 
 } 
 
} 


3. Operation results


hello before 
hello chenyu 
hello before 

Above collate content, the friend that needs can refer below


Related articles: