java 监听器实现原理
監(jiān)聽器實(shí)現(xiàn)者:
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();
}
}
?
?
自定義類,監(jiān)聽器作為內(nèi)部屬性(包含方法),
類中存在調(diào)用監(jiān)聽器內(nèi)部方法的地方,
set不同的監(jiān)聽器實(shí)現(xiàn)者,處理的方式便不一樣,
監(jiān)聽器相當(dāng)于一個鉤子,做回調(diào)使用。
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);
}
}
?
實(shí)例二: @Overridepublic void onStart(Intent intent, int startid) {
super.onStart(intent, startid); locationService = ((LocationApplication) getApplication()).locationService;
//獲取locationservice實(shí)例,建議應(yīng)用中只初始化1個location實(shí)例,然后使用,可以參考其他示例的activity,都是通過此種方式獲取locationservice實(shí)例的
locationService.registerListener(mListener); //注冊監(jiān)聽 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(); //停止定位服務(wù)
locationService.unregisterListener(mListener); //注銷掉監(jiān)聽
}
?
超強(qiáng)干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的java 监听器实现原理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Volley框架使用及源码解析
- 下一篇: js中的 arguments ,实参的集