android 多个activity 共用一套广播时,写个父类封装广播接收

public abstract class ParentActivity extends Activity {
	public static final String ACTION_1 = "com.example.action1";
	public static final String ACTION_2 = "com.example.action2";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ACTION_1);
		intentFilter.addAction(ACTION_2);
		registerReceiver(receiver, intentFilter);
	}

	protected abstract void doAction1();

	protected abstract void doAction2(String arg);

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(ACTION_1)) {
				doAction1();
			} else if (action.equals(ACTION_2)) {
				String arg = intent.getStringExtra("arg");
				doAction2(arg);
			}
		}
	};

	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	};
}

你可能感兴趣的:(android)