Android 回调接口的写法

3,981 阅读11分钟
原文链接: www.cnblogs.com
方法一: 定义一个接口,里面写想要对外提供的方法,在逻辑层方法的参数里传递进去,让在需要的时候调接口里的方法。 实例一: ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 public class SmsUtils {     public interface BackUpCallBack{         /**          * 短信调用前调用的方法          */         public void beforeSmsBackup( int total);         /**          * 短信备份中调用的方法          * @param progress 当前备份的进度。          */         public void onSmsBackup( int progress);     }     /**      * 短信的备份      * @param context 上下文      * @param od 进度条对话框      * @throws Exception      */     public static void backupSms(Context context,BackUpCallBack backupCallback) throws Exception{ ...         //开始备份的时候,设置进度条的最大值         backupCallback.beforeSmsBackup(cursor.getCount());         int progress = 0 ;         while (cursor.moveToNext()) {             Thread.sleep(500 );     ....             //备份过程中,增加进度             progress++;             backupCallback.onSmsBackup(progress);         }         serializer.endTag(null, "smss");         serializer.endDocument();         fos.close();     }   。。。 SmsUtils.backupSms(getApplicationContext(),new BackUpCallBack() {                              @Override                              public void onSmsBackup(int progress) {                                  pd.setProgress(progress);                              }                              @Override                              public void beforeSmsBackup(int total) {                                  pd.setMax(total);                              }                         });

  实例二:定义接口也可以写在类外面

?
1 2 3 4 public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }

  

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class HttpUtil {     public static void sendHttpRequest(final String address,             final HttpCallbackListener listener) {         new Thread(new Runnable() {             @Override             public void run() {                 HttpURLConnection connection = null;                 try {                 ...                     while ((line = reader.readLine()) != null) {                         response.append(line);                     }                     if (listener != null) {                         // 回调onFinish()方法                         listener.onFinish(response.toString());                     }                 } catch (Exception e) {                     if (listener != null) {                         // 回调onError()方法                         listener.onError(e);                     }                 } finally {                     if (connection != null) {                         connection.disconnect();                     }                 }             }         }).start();     } }

  

方法二:
  • 定义个接口,里面写上想要对外提供的方法,然后接口写get、set方法(注意是接口,其实有set方法就行了),声明出来在逻辑层代码的方法里,在需要的时候调用接口的方法
  • 用的时候先把逻辑层new出来,然后调用逻辑层.set接口(new 逻辑层.接口){接口的方法},相当于内部类的用法
实例1: ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 public class MyQueryHandler extends AsyncQueryHandler{ ...     @Override     protected void onQueryComplete(int token, Object cookie, Cursor cursor) {         ...         if(cookie!=null && cookie instanceof CursorAdapter){             CursorAdapter adapter = (CursorAdapter) cookie;             // 给adapter 设置新的cursor             adapter.changeCursor(cursor);         }                   if(cursorChangedListener!=null ){             cursorChangedListener.onCursorChanged(token, cookie, cursor);         }               }                 public IOnCursorChangedListener getCursorChangedListener() {         return cursorChangedListener;     }     public void setOnCursorChangedListener(IOnCursorChangedListener cursorChangedListener) {         this.cursorChangedListener = cursorChangedListener;     }     private IOnCursorChangedListener cursorChangedListener;           /**      * 声明,cursor改变时的监听接口      * @author Administrator      *      */     public interface IOnCursorChangedListener{                   void onCursorChanged(int token, Object cookie, Cursor cursor);     }       }   。。。。 //回调接口写法:这样就把adapter有回传回来了         MyQueryHandler myQueryHandler = new MyQueryHandler(getContentResolver());         myQueryHandler.setOnCursorChangedListener(new MyQueryHandler.IOnCursorChangedListener() {                           @Override             /**              *  当adapter 获得 cursor 的时候,回调此方法              */             public void onCursorChanged(int token, Object cookie, Cursor cursor) {                 // 让listview 显示最后一行                 listView.setSelection(adapter.getCount()-1);             }         });

  实例2:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 private GestureDetector gestureDetector;      private OnDeleteListener listener;        public void setOnDeleteListener(OnDeleteListener l) {        listener = l;         @Override    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,            float velocityY) {              deleteButton.setOnClickListener(new OnClickListener() {                @Override                public void onClick(View v) {                    itemLayout.removeView(deleteButton);                    deleteButton = null                   isDeleteShown = false                   listener.onDelete(selectedItem);                           });    public interface OnDeleteListener {          void onDelete(int index);      

  下面的内容来自网络
来源: <blog.csdn.net/eclipsexys/…>

Java接口回调是个什么玩意儿

java的接口回调,在android下用的是越来越多了,到底该怎么理解他呢?

 

回调就是外部设置一个方法给一个对象, 这个对象可以执行外部设置的方法, 通常这个方法是定义在接口中的抽象方法, 外部设置的时候直接设置这个接口对象即可.

  如何定义一个回调

a. 定义接口 : 在类中定义一个Interface, 并在接口中定义一个抽象方法;
b. 接口对象 : 在类中定义一个该接口的成员变量;
c. 设置对象 : 在类中定义一个公共的方法, 可以设置这个接口的对象, 调用该方法给接口对象成员变量赋值;
d. 调用方法 : 在合适的位置调用接口对象中的方法;  

 

好比是一个领导和一个下属,还有一个下属间谍三个人之间不清不楚的关系

 

1、下属有一个吃饭的事情……

(定义接口)

2、领导发表申明,说对下属的吃饭这件事感兴趣,并说了如果下属吃饭,他就怎么样怎么样,但是老板就是老板,总不能一直盯着下属所以……

(实现接口,并实现处理监听事件的方法)

3、领导一说话,间谍就去了下属那,并且领导给了间谍特权,可以使用我的怎么样怎么样方法

(建立于接口的连接,实际上是一个向上转型的过程,把间谍upcase为一个领导,从而调用领导的方法)

4、,然后只要一吃饭,间谍就通知领导,并替领导完成什么样什么样的事情

(通过接口的实例,调用接口中的方法)

 

这样一说,大家应该对接口回调的机制有了点感性的理解了吧。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 interface People{          void peopleList();            class Student implements People{          public void peopleList(){           System.out.println("I’m a student.");                 class Teacher implements People{         public void peopleList(){           System.out.println("I’m a teacher.");                 public class Example{         public static void main(String args[]){           People a;             //声明接口变量       a=new Student();      //实例化,接口变量中存放对象的引用       a.peopleList();        //接口回调       a=new Teacher();     //实例化,接口变量中存放对象的引用       a.peopleList();       //接口回调           

  

 

通过接口,我们将大量共通但实现细节不同的方法抽象出来,再去实现它的接口类中具体处理,这样通过接口去调用方法的时候,就不用考虑具体调用哪个方法了。

这是一种用法,大致是多态的意思,还有一种用法就是组件中的通信:

例如Fragment间的通信

1、在Fragment中定义接口,申明接口的实例,在onAttach()方法中实现接口实例化为Activity对象

2、在Fragment中的某个方法内,使用接口的实例,调用Activity的方法,向Activity通信

3、Activity实现接口与结构内的方法,实现处理回调的逻辑