美文网首页Android Utils
BroadcastReceiver和LocalBroadcast

BroadcastReceiver和LocalBroadcast

作者: 几千里也 | 来源:发表于2015-03-01 22:14 被阅读143次

    常规 BroadcastReceiver 的常规用法

    <receiver android:name=".MyReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SECRET_CODE" />
            <data
                android:scheme="android_secret_code"
                android:host="9527" />
        </intent-filter>
    </receiver>
    
    import android.content.BroadcastReceiver;
    import android.content.IntentFilter;
    import com.android.internal.telephony.IccCardConstants;
    
        private final BroadcastReceiver mSimStateReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String stateExtra = intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE);
    
                if (IccCardConstants.INTENT_VALUE_ICC_ABSENT.equals(stateExtra)) {
                    // do...
                }
            }
        };
    
        protected void onCreate(Bundle icicle) {
        // ...
            IntentFilter filter = new IntentFilter();
            filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
            registerReceiver(mSimStateReceiver, filter);
        // ...
        }
    
    

    LocalBroadcastManager

    特点

    1. 广播数据在本应用范围内传播。
    2. 不用担心别的应用伪造广播。
    3. 比发送全局广播更高效。

    用法

    1. 加入 Android v4 的兼容包
    android.support.v4.content.LocalBroadcastManager
    
    1. 写一个 Receiver
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override    
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("test")) {
                String message = intent.getStringExtra("message");
                Log.d("receiver", "Got message: " + message);
            }
        }
    };
    
    1. 注册 Receiver
    IntentFilter filter = new IntentFilter(MyIntentService.ACTION);
    filter.addAction("test");
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
    
    1. 发送 Broadcast
    findViewById(R.id.button_send).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent("test");
            intent.putExtra("message", "This is a test!");
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }
    });
    
    1. 注销 Receiver
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    

    相关文章

      网友评论

        本文标题:BroadcastReceiver和LocalBroadcast

        本文链接:https://www.haomeiwen.com/subject/joxmxttx.html