首先,参考一下众多文章中,把接口回调讲得比较浅显易懂的两篇文章:
举个例子
网友提供的一些例子,虽然接地气,但是,不够专业,还是欣叔的例子好一些,把代码取出来,原理讲解移步<码农翻身>公众号。
public class XiaoZhang implements IFileIoCallback { public void saveStr(){ String fileName = "callback.txt"; String str = "this is a callback demo."; FileIO fileIO = new FileIO(); fileIO.saveStrToFile(fileName,str,this); } @Override public void onResult(boolean isSave) { System.out.println(isSave ? "success" : "fail" ); }}
public class FileIO { public void saveStrToFile(String fileName, String content, final IFileIoCallback callback){ new Thread(new Runnable() { @Override public void run() { try { //write str to file... callback.onResult(true); }catch (Exception e){ e.printStackTrace(); callback.onResult(false); } } }).start(); }}
public interface IFileIoCallback { void onResult(boolean isSave);}