Callback Interface essence that simple!

First, why would the interface callback? What is the interface callback?

In fact, these two issues is a problem, know the principles of natural callback interface will know why there is such a thing. We know that java is not possible to create direct interfaces instance, then the question is, if I have an interface declared as a variable, then I execute the method of this interface, the interface instance it is not how to do it? Aha, here they change the natural characteristics of java in another appearance --- "polymorphic", then the java virtual machine will naturally find its subclasses, the method is called a subclass already overloaded, here is the interface callback nature! ! We just need to give the address of its subclasses variable points on the subclass can know when to call in the call. Then we can create the class A subclass instance of an interface, an interface to create a variable in class B, the class A address to the variable class B, A is called when the variable of the interface methods of class method override, which is the interface to perform the steps callback. We will use when network requests and other time-consuming operations to the mechanisms used to get the data back to the main thread.

Second, use case

Here we have to use an instance of a network request to demonstrate how to use this mechanism, in order to try to reduce the code to make the main code to highlight, which is unnecessary fault-tolerant code did not write, and we hope in a formal project good fault tolerance.

We use a button and a imageView to demonstrate, click the button when the time to download data, use a callback interface to download data after the completion of the data transfer is displayed in imageview back in. Results are as follows:


Layout file is simple not in the posted out, we have three categories, one is the callback interface, one is the main activity, as a download and execute the callback data back Callee class, interface class look at the following:


  
  
  1. import android.graphics.Bitmap;
  2. /**
  3. * Created by JimLv on 2016/5/31.
  4. */
  5. public interface CallBackInterface {
  6. void result(Bitmap bm);
  7. }

It defines a method for communicating data to look Callee categories:


  
  
  1. import java.io.IOException;
  2. import java.net.HttpURLConnection;
  3. import java.net.URL;
  4. /**
  5. * Created by JimLv on 2016/5/31.
  6. */
  7. public class Callee {
  8. private final String IMGURL = "http://f.hiphotos.baidu.com/zhidao/pic/item/b21bb051f8198618a323ac464bed2e738ad4e688.jpg";
  9. // variable to hold the interface
  10. CallBackInterface mInterface;
  11. Callee(CallBackInterface theInterface) {
  12. // Here is the key, the external interface instance a reference to the class, assign values ​​to variables
  13. mInterface = theInterface;
  14. // create an object of the download time
  15. executeDown();
  16. }
  17. public void executeDown() {
  18. new Thread( new Runnable() {
  19. @Override
  20. public void run() {
  21. try {
  22. HttpURLConnection conn = (HttpURLConnection) new URL(IMGURL).openConnection();
  23. conn.setConnectTimeout( 5 * 1000);
  24. conn.setRequestMethod( "GET");
  25. mInterface.result(BitmapFactory.decodeStream(conn.getInputStream()));
  26. } catch (IOException e) {
  27. e.printStackTrace ();
  28. }
  29. }
  30. }).start();
  31. }
  32. }
Here we declare an interface variable initialization method of a class in the subclass interface address is assigned to the variable and call data download method call interface variables which method the data to the data after the download is complete, the actual implementation of the method is to perform the method in a subclass, which is the interface to the callback really do.
Finally, we look MainActivity categories:


  
  
  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2. private ImageView imgv;
  3. private Button downImgBtn;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super .onCreate (savedInstanceState);
  7. setContentView(R.layout.activity_main);
  8. imgv = (ImageView) findViewById(R.id.imgv);
  9. downImgBtn = (Button) findViewById(R.id.downImgBtn);
  10. //点击按钮去下载
  11. downImgBtn.setOnClickListener( this);
  12. }
  13. @Override
  14. public void onClick(View v) {
  15. //从接口回调得到数据,因为下载是在子线程中,所以这里要变到主线程中设置图片
  16. new Callee( new CallBackInterface() {
  17. @Override
  18. public void result(final Bitmap bm) {
  19. runOnUiThread( new Runnable() {
  20. @Override
  21. public void run() {
  22. imgv.setImageBitmap(bm);
  23. }
  24. });
  25. }
  26. });
  27. }
  28. }

Here we create anonymous inner class instance of a subclass of the interface, overloaded methods in the subclass because it is run in a sub-thread, we can not operate UI, all calls runOnUiThread method to update the data to imageview, the entire it's that point of the demo is not very simple?

Scanning concerned about my micro-channel public number:


Third, the summary

Haha, the whole callback mechanism is not very simple? In fact, before this time we do not know is a headache, disarray inside logic, Baidu above article is a lot, but the contents inside La La weave the thread of father Ken really not shallow ah. "" Damn dog program "" ~~~~~~~~~~ Well, actually I also hate it when people say that, but it does not matter, we are motivated engineers, who are not the same and your home programs dog! Understand the essence of a technology after what use it will not not start, a problem will know how to solve. If you find this article written by good hope you point a praise, I want to see if I'll write articles please pay attention to me, I wish backgammon, happy every day!
Finally, attach the demo: Click on the link to open

Published 154 original articles · won praise 89 · Views 100,000 +

Guess you like

Origin blog.csdn.net/qq_41933149/article/details/104218603