监听器实现者:
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); //注销掉监听 }