Android development: simple implementation of loading data through the interface callback mechanism, in actual development, the call back method is much more frequently used to obtain network-loaded data than to load data by directly enabling threads or asynchronous tasks, the code in this article will simply implement this smart call and understand the essence of callback.
MainActivity code
Package com. example. f07_callback01; import com. example. f07_callback01.A.Callback; import android. OS. bundle; import android. app. activity; import android. util. log; import android. view. menu; import android. view. view; import android. widget. button; public class MainActivity extends Activity {private Button button; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button = (Button) this. findViewById (R. id. button1); button. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View arg0) {// TODO Auto-generated method stubA getString = new A (); // call the interface to obtain the data getString. loadString ("", new Callback () {@ Overridepublic void get (String result) {// TODO Auto-generated method stubLog. I ("TAG", "-------->" + result) ;}}) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}
Method of the callback Interface Class
Package com. example. f07_callback01; public class A {// simulate obtaining the public void loadString (String path, final Callback callback) {new Thread (new Runnable () {@ Overridepublic void run () from the server () {// TODO Auto-generated method stubString msg = "call data through interfaces"; callback. get (msg );}}). start () ;}public interface Callback {public void get (String result );}}