Preface
In development, we often use interface callback.
Interface callback means that after registration, it will not be executed immediately, but will be triggered at a certain time.
for instance:
A has a problem that he won't. He asks B. B can't solve it for the time being. B says, wait until I (b) solve it, and then tell you (a) at this time, a can continue to do other things first.
Then only when B solves the problem and tells A that it has been solved can A solve the problem.
In the code, for example, the most commonly used:
In an Activity, an interface callback method is given to a button. Only when the user clicks this button and tells that the button has been clicked can the interface callback method be executed
Button btn = new Button(this); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } });
Then we can understand the interface callback through a Demo:
The main thread starts an asynchronous task. When the asynchronous task receives data, it displays the data with TextView
1. First, we need to define an interface and a method. The parameter is a string:
package com.xqx.InterfaceDemo; public interface ChangeTitle { void onChangeTitle(String title); }
2. Write an asynchronous task, take the interface as the construction method parameter, and judge if there is data in the doInBackground() method, the interface callback
package com.xqx.InterfaceDemo; import android.content.Context; import android.os.AsyncTask; public class MyTask extends AsyncTask<String,Void,String>{ private ChangeTitle changeTitle; public MyTask(ChangeTitle changeTitle) { this.changeTitle = changeTitle; } @Override protected String doInBackground(String... strings) { if (strings[0]!=null){ changeTitle.onChangeTitle(strings[0]); } return null; } }
3. The primary Activity, which transfers this to the asynchronous task parameter, that is, the interface callback method is executed in this class, then the ChangeTitle interface needs to be implemented and the onChangeTitle method in the interface needs to be rewritten
package com.xqx.InterfaceDemo; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity implements ChangeTitle { private TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.textView); new MyTask(this).execute("I am the title."); } // Rewrite interface methods and perform corresponding operations @Override public void onChangeTitle(String title) { textView.setText(title); } }
appendix
Android advanced technology outline, as well as system advanced video;
Acquisition method;