先上代码:
package com.example.listenermode;
public class InternetManager {
private Listener mListener = null;
private boolean isInternetOn = false;
public interface Listener {
public void onStateChange(boolean state);
}
public void registerListener(Listener listener) {
mListener = listener;
}
public void doYourWork() {// the part that this class does
isInternetOn = true;// catch new state at some point
if (mListener != null) {// now notify if someone is interested.
mListener.onStateChange(isInternetOn);
}
}
}上面自定义的监听器几大特点:
1.自定义类,监听器作为内部属性(包含方法)
2.类中存在调用监听器内部方法的地方
3.set不同的监听器实现者,处理的方式便不一样
4.监听器相当于一个钩子,做回调使用
package com.example.listenermode;
import com.example.interfacemode.InternetManager.Listener;
import com.example.interfacemode.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mText;
private InternetManager mInetMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView) findViewById(R.id.textView);
mInetMgr = new InternetManager();
mInetMgr.registerListener(new Listener() {
@Override
public void onStateChange(boolean state) {
if (state) {
mText.setText("on");
} else {
mText.setText("off");
}
}
});
mInetMgr.doYourWork();
}
}最后的输出结果如下图:
现在把整个监听过程梳理一遍:
A.在onCreate方法中初始化主页面视图并实例化TextView和InternetManager对象,并注册监听,此方法只执行一遍
B.这个监听完成对InternetManager中类型为Listener的成员变量赋值,这个监听器是在内存中一直存在的
C.通过InternetManager对象注册的监听是一个Listener对象,故而要实现这个Listener,即实现onStateChange方法
D.这个Listener对象实现的onStateChange方法有个boolean类型的参数state,根据state的值设置textView的文本内容
E.在MainActivity中调用InternetManager对象的doYourWork方法完成对上面state的传值
监听:一旦state状态(网络开/关)变化,Manager中的方法就可感知并捕获这个变化的状态,如果有谁监听(即注册了这个监听mListener!=null)就通过监听器中onStateChange方法把这个新状态传出去。而监听者注册了这个监听(此时肯定实现了onStateChange方法),当注册者通过IntenetManager对象调用doYourWork方法时,做了两件事:1.捕获更新的状态故可得到Manager传来的新状态state数据。2.调用onStateChange方法传参为state,由于doYourWork是在MainActivity中执行的,故调用的是MainActivity中注册的监听器方法,从而完成了整个监听的实现。
互联网状态监听机制解析
555

被折叠的 条评论
为什么被折叠?



