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);
}
}
?
實例二: @Overridepublic 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); //注銷掉監聽
}
?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的java 监听器实现原理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Volley框架使用及源码解析
- 下一篇: js中的 arguments ,实参的集