Android BroadcastReceiver

public class MainActivity extends Activity implements OnClickListener {
	private TextView txt;
	private Button btn_send;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		txt = (TextView) findViewById(R.id.txt);

		btn_send = (Button) findViewById(R.id.btn_send);
		btn_send.setOnClickListener(this);

	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver, new IntentFilter("com.bob.mybroadcast"));
	}

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

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_send:
			Intent intent = new Intent("com.bob.mybroadcast");
			intent.putExtra("hello", "hello from Bob");
			sendBroadcast(intent);
			break;
		}
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String str = intent.getStringExtra("hello");
			txt.setText(str);
		}
	};
}

静态注册:

<receiver android:name=".MyReceiver">  
    <intent-filter>  
        <action android:name="com.bob.mybroadcast"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>

动态注册:

MyReceiver receiver = new MyReceiver();

IntentFilter filter = new IntentFilter();
filter.addAction("com.bob.mybroadcast");


protected void onResume() {
	super.onResume();
	registerReceiver(receiver, filter);
}

protected void onPause() {
	super.onPause();
	unregisterReceiver(receiver);
}

 

http://blog.csdn.net/liuhe688/article/details/6955668

posted @ 2013-11-25 17:33  songsiyao  阅读(205)  评论(0编辑  收藏  举报