BroadcastReceiver和LocalBroadcastManager

常规 BroadcastReceiver 的常规用法


    
        
        
    

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和LocalBroadcastManager)