Android 广播回调模式
接收广播状态改变回调所有监听者
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import com.android.internal.telephony.PhoneConstants; import com.android.internal.telephony.TelephonyIntents; import com.mediatek.contacts.ContactsApplicationEx; import java.util.ArrayList; import java.util.List; /** * this class used to handle the state change as phb, hotswap. */ public class PhbStateHandler { private static final String TAG = "PhbStateHandler"; public interface Listener { /** * the callback to handle the phb change. * * @param subId * The current sim contact refer to this sub id. */ public void onPhbStateChange(int subId); } private List<Listener> mListeners = new ArrayList<Listener>(); private Context mContext = (Context) ContactsApplicationEx.getContactsApplication(); private boolean mRegistered; private static PhbStateHandler sInstance; private BroadcastReceiver mPhbStateListener = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, ContactsConstants.ERROR_SUB_ID); Log.i(TAG, "[onReceive]action: " + action + ",subId:" + subId); // for phb state change if (TelephonyIntents.ACTION_PHB_STATE_CHANGED.equals(action)) { for (Listener listener : mListeners) { if (listener != null) { listener.onPhbStateChange(subId); } } } } }; private PhbStateHandler() { } /** * get the instance of the PhbStateHandler. */ public static synchronized PhbStateHandler getInstance() { if (sInstance == null) { sInstance = new PhbStateHandler(); } return sInstance; } /** * register the listener. * * @param target * the target register the listener. */ public synchronized void register(Listener target) { Log.i(TAG, "[register]target: " + target + ",mRegistered = " + mRegistered); // one target only register once if (target != null && !mListeners.contains(target)) { mListeners.add(target); } if (!mRegistered) { mContext.registerReceiver(mPhbStateListener, new IntentFilter( TelephonyIntents.ACTION_PHB_STATE_CHANGED)); Log.d(TAG, "register phb"); mRegistered = true; } } /** * unRegister the listener. * * @param target * the target unRegister the listener. */ public synchronized void unRegister(Listener target) { Log.i(TAG, "[unRegister]target: " + target + ",mRegistered = " + mRegistered); if (target != null && mListeners.contains(target)) { mListeners.remove(target); } if (mListeners.isEmpty() && mRegistered) { mContext.unregisterReceiver(mPhbStateListener); Log.d(TAG, "unRegister phb"); mRegistered = false; } } }
版权声明:如无特殊标注,文章均为本站原创,转载时请以链接形式注明文章出处。
评论