作为四大组件,Broadcast Receiver 使用起来比较简单。有两种注册方式:1. 在AndroidManifest中注册。2. 在代码中直接注册,这种注册需要注意的一点是:当注册此Receiver的Activity退出的时候,一定要调用unregisterReceiver 方法,这个有点像Service的Bind。
第二种方式的示例代码如下:
?[Copy to clipboard]Download zuiniuwang.java
- * BroadCasterActivity.java
- * com.androidtest.broadcaster
- *
- * Function: TODO
- *
- * ver date author
- * ──────────────────────────────────
- * 2011-6-8 Leon
- *
- * Copyright (c) 2011, TNT All Rights Reserved.
- */
- package com.androidtest.broadcaster;
- import com.androidtest.R;
- import android.app.Activity;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- /**
- * ClassName:BroadCasterActivity
- * Function: TODO ADD FUNCTION
- * Reason: TODO ADD REASON
- *
- * @author Leon
- * @version
- * @since Ver 1.1
- * @Date 2011-6-8
- */
- public class BroadCasterActivity extends Activity{
- private Broadcaster myBroadcaster;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- this.setContentView(R.layout.activity_broadcaster);
- myBroadcaster = new Broadcaster();
- IntentFilter filter=new IntentFilter();
- filter.addAction("test");
- this.registerReceiver(myBroadcaster, filter);
- Button button=(Button)this.findViewById(R.id.button1);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Intent intent = new Intent("test");
- BroadCasterActivity.this.sendBroadcast(intent);
- }
- });
- }
- @Override
- public void finish() {
- // TODO Auto-generated method stub
- super.finish();
- this.unregisterReceiver(myBroadcaster);
- }
- }
- class Broadcaster extends BroadcastReceiver{
- private static final String TAG = "Broadcaster";
- @Override
- public void onReceive(Context context, Intent intent) {
- // TODO Auto-generated method stub
- String string = intent.getAction();
- Log.v(TAG , "The action is "+ string);
- }
- }
- 当然我们也可以使用第一种方式,在Android Manifest.xml定义,这样就定义了一个全局的receiver()和Activity
- <receiver android:name=".broadcaster.Broadcaster">
- <intent-filter>
- <action android:name="test" />
- </intent-filter>
- </receiver>
本文转自 最牛傻蛋 51CTO博客,原文链接:http://blog.51cto.com/zuiniuwang/718307,如需转载请自行联系原作者