當前位置:編程學習大全網 - 源碼下載 - View編程(8): 自定義 View 如何註冊廣播

View編程(8): 自定義 View 如何註冊廣播

在 android opensource: Settings 研究_android 組件如何響應語言變化 博客中,說過我會跟大家交流壹下如何在自己定義的 View 中註冊以及接收廣播。在貼代碼之前,先看看 View 的兩個回調方法 onAttachedToWindow、onDetachedFromWindow.從api 不難看出,onAttachedToWindow、onDetachedFromWindow 分別在 view 依附到 window、脫離 window 時回調。源碼如下: /** * This is called when the view is attached to a window. At this point it * has a Surface and will start drawing. Note that this function is * guaranteed to be called before {@link #onDraw}, however it may be called * any time before the first onDraw -- including before or after * {@link #onMeasure}. * * @see #onDetachedFromWindow() */ protected void onAttachedToWindow() { if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { mParent.requestTransparentRegion(this); } } /** * This is called when the view is detached from a window. At this point it * no longer has a surface for drawing. * * @see #onAttachedToWindow() */ protected void onDetachedFromWindow() { if (mPendingCheckForLongPress != null) { removeCallbacks(mPendingCheckForLongPress); } destroyDrawingCache(); } 還需要搞明白壹個問題,onDraw 方法與這兩個回調方法的調用順序。D/mark- ( 316): onAttachedToWindow() D/mark- ( 316): onDraw() D/mark- ( 316): onDetachedFromWindow() 當我們運行 App,然後退出 App(點擊Back,或者kill,不是點擊Home),調用順序如上所示。看壹個 android 源碼的例子:@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (!mAttached) { mAttached = true; IntentFilter filter = new IntentFilter(); filter.addAction(Telephony.Intents.SPN_STRINGS_UPDATED_ACTION); getContext().registerReceiver(mIntentReceiver, filter, null, getHandler()); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mAttached) { getContext().unregisterReceiver(mIntentReceiver); mAttached = false; } } 可以看出,註冊和取消註冊廣播的操作是在兩個回調方法中完成的。其中,mAttached 是定義的壹個 boolean 值。這個地方值得借鑒學習!private boolean mAttached; 接收並處理廣播的邏輯在這裏:private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Telephony.Intents.SPN_STRINGS_UPDATED_ACTION.equals(action)) { updateNetworkName(intent.getBooleanExtra(Telephony.Intents.EXTRA_SHOW_SPN, false), intent.getStringExtra(Telephony.Intents.EXTRA_SPN), intent.getBooleanExtra(Telephony.Intents.EXTRA_SHOW_PLMN, false), intent.getStringExtra(Telephony.Intents.EXTRA_PLMN)); } } }; 完整的源碼,可以自行看/frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/CarrierLabel.java其中,CarrierLabel.java 是壹個自定義的 TextView.

再延伸壹步考慮,我們可以在這兩個回調方法裏面還可以發送廣播、啟動壹個 android 組件等,希望對妳有用!

  • 上一篇:湖南衛視主持人何炅簡介?
  • 下一篇:關於s40文件管理器,詳細說下有哪幾款,及各自的優缺點
  • copyright 2024編程學習大全網