zoukankan      html  css  js  c++  java
  • java 监听器实现原理

    监听器实现者:


    public class MyActivity extends Activity implements InternetManager.Listener {

    private TextView mText;
    private InternetManager mInetMgr;

    /* called just like onCreate at some point in time */
    public void onStateChange(boolean state) {
    if (state) {
    mText.setText("on");
    } else {
    mText.setText("off");
    }
    }

    public void onCreate() {
    mInetMgr = new InternetManager();
    mInetMgr.registerListener(this);
    mInetMgr.doYourWork();
    }
    }

    自定义类,监听器作为内部属性(包含方法),

    类中存在调用监听器内部方法的地方,

    set不同的监听器实现者,处理的方式便不一样,

    监听器相当于一个钩子,做回调使用。


    public class InternetManager {
    // all the listener stuff below
    public interface Listener {
    public void onStateChange(boolean state);
    }

    private Listener mListener = null;
    public void registerListener (Listener listener) {
    mListener = listener;
    }

    // -----------------------------
    // the part that this class does

    private boolean isInternetOn = false;
    public void doYourWork() {
    // do things here
    // at some point
    isInternetOn = true;
    // now notify if someone is interested.
    if (mListener != null)
    mListener.onStateChange(isInternetOn);
    }
    }

            

     

     
    实例二:
     @Override
    public void onStart(Intent intent, int startid) {
    super.onStart(intent, startid);
     locationService = ((LocationApplication) getApplication()).locationService;
    //获取locationservice实例,建议应用中只初始化1个location实例,然后使用,可以参考其他示例的activity,都是通过此种方式获取locationservice实例的
    locationService.registerListener(mListener); //注册监听
      if (type == 0) {
    locationService.setLocationOption(locationService.getDefaultLocationClientOption());
    } else if (type == 1) {
    locationService.setLocationOption(locationService.getOption());
    }
       }
       @Override
    public void onDestroy() {
    Log.i("warn", "ondestroy");
    locationService.stop(); //停止定位服务
    locationService.unregisterListener(mListener); //注销掉监听
    }

     

  • 相关阅读:
    【Java】Junit快速入门
    【Redis】Redis Sentinel 哨兵模式搭建
    【Redis】Redis 主从模式搭建
    Android开发过程中的坑及解决方法收录(六)
    杂牌机搞机之旅(一)——获得root权限(刷入magisk)
    Java 学习笔记 泛型
    Java 学习笔记 反射与迭代器
    Java 学习笔记 正则表达式
    Java 学习笔记 执行外部命令 包装类 枚举类型
    IDEA设置显示中文文档API方法说明
  • 原文地址:https://www.cnblogs.com/to-creat/p/5684834.html
Copyright © 2011-2022 走看看