常规 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
特点
- 广播数据在本应用范围内传播。
- 不用担心别的应用伪造广播。
- 比发送全局广播更高效。
用法
- 加入 Android v4 的兼容包
android.support.v4.content.LocalBroadcastManager
- 写一个 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);
}
}
};
- 注册 Receiver
IntentFilter filter = new IntentFilter(MyIntentService.ACTION);
filter.addAction("test");
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
- 发送 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);
}
});
- 注销 Receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
网友评论