广播(Broadcast)的简单用法

来源:互联网 发布:淘宝卖家体检中心链接 编辑:程序博客网 时间:2024/06/05 02:13

发送一条广播

发送广播的方法和启动Activity的方法是非常类似的。首先新建一个Intent对象,然后使用sendBroadcast()sendOrderedBroadcast()或者sendStickyBroadcast()发送广播:

  • sendBroadcast():发送一条普通广播。这种广播接收不分先后,而且不能截断,不能被修改。
  • sendOrderedBroadcast():发送一条有序广播。这种广播按照一定的顺序被接收,接收顺序可以通过在<intent-filter>标签下设定android:priority来改变。可以使用abortBroadcast()方法终止广播的传播。
  • sendStickyBroadcast():发送一条粘滞广播。这种广播在没有被接收的时候会一直存在。所以即使在广播发送后注册的接收器也能接受到这种广播。这种广播使用的使用要添加相应的权限。由于这种广播带来了很多安全性的问题,所以在API 21 以后已经被废弃了。

接收广播

  • 首先创建一个类继承BroadcastReceiver,并重写其中的onReceive()方法;
  • 注册Receiver。可以使用静态注册或者动态注册:
    • 静态注册:在Manifest文件中的<application>标签下添加<receiver>标签。在<receiver>标签下可以添加多个<intent-filter>来指定接收广播的类型;
    • 动态注册:如果想要让BroadcastReceiver只在一段时间内有效,可以调用registerReceiver()unRegisterReceiver()方法动态注册。

一个简单的例子

程序是这样子的:通过点击三个不同的按钮,可以发送三种不同的广播:

布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.broadcastreceiverdemo.MainActivity" >    <Button        android:id="@+id/button_1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="发送普通广播" />    <Button        android:id="@+id/button_2"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="发送有序广播" />    <Button        android:id="@+id/button_3"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="发送粘滞广播" /></LinearLayout>

在主程序中发送广播:

public class MainActivity extends Activity implements OnClickListener{    Button button1;    Button button2;    Button button3;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button1 = (Button) findViewById(R.id.button_1);        button2 = (Button) findViewById(R.id.button_2);        button3 = (Button) findViewById(R.id.button_3);        button1.setOnClickListener(this);        button2.setOnClickListener(this);        button3.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch(v.getId()){        case R.id.button_1:            Intent intent1 = new Intent();            intent1.setAction("BC_One");            intent1.putExtra(Intent.EXTRA_TEXT, "这是一条普通广播");            //如果明确知道广播的唯一接收者,也可以使用显式的intent            //intent.setClass(MainActivity.this, MyReceiver1.class);            sendBroadcast(intent1);            break;        case R.id.button_2:            Intent intent2 = new Intent();            intent2.setAction("BC_Two");            intent2.putExtra(Intent.EXTRA_TEXT, "这是一条有序广播");            sendOrderedBroadcast(intent2, null);            break;        case R.id.button_3:            Intent intent3 = new Intent();            intent3.setAction("BC_Three");            intent3.putExtra(Intent.EXTRA_TEXT, "这是一条粘滞广播");            sendStickyBroadcast(intent3);            //动态注册第三个广播接收器,注意这个接收器注册在广播发送之后            IntentFilter filter = new IntentFilter();            filter.addAction("BC_One");            filter.addAction("BC_Two");            filter.addAction("BC_Three");            MyReceiver3 receiver = new MyReceiver3();            registerReceiver(receiver, filter);            break;        default:            break;          }    }}

三个广播接收器:

public class MyReceiver1 extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        String s = intent.getStringExtra(Intent.EXTRA_TEXT);        Log.d("MyReceiver1", "收到一条广播:" + s);        Bundle bundle = getResultExtras(true);        String extraString = bundle.getString(Intent.EXTRA_TEXT);        if(extraString != null){            Log.d("MyReceiver1", "收到一条广播:" + extraString);        }    }}
public class MyReceiver2 extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        String s = intent.getStringExtra(Intent.EXTRA_TEXT);        Log.d("MyReceiver2", "收到一条广播:" + s);        Bundle bundle = new Bundle();        bundle.putString(Intent.EXTRA_TEXT, "这是第2条广播");        setResultExtras(bundle);    }}
public class MyReceiver3 extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        String s = intent.getStringExtra(Intent.EXTRA_TEXT);        Log.d("MyReceiver3", "收到一条广播:" + s);        Bundle bundle = getResultExtras(true);        String extraString = bundle.getString(Intent.EXTRA_TEXT);        if(extraString != null){            Log.d("MyReceiver3", "收到一条广播:" + extraString);        }    }}

setResultExtras()可以用来更改广播中的内容;getResultExtras()可以用来得到广播中的内容。这两个方法都只对有序广播有用。

前两个广播在Manifest文件中注册,第三个广播使用动态注册的方法,在广播发送以后被注册。

        <receiver android:name="com.example.broadcastreceiverdemo.MyReceiver1" >            <intent-filter>                <action android:name="BC_One" />            </intent-filter>            <intent-filter android:priority="-100" >                <action android:name="BC_Two" />            </intent-filter>            <intent-filter>                <action android:name="BC_Three" />            </intent-filter>        </receiver>        <receiver android:name="com.example.broadcastreceiverdemo.MyReceiver2" >            <intent-filter>                <action android:name="BC_One" />            </intent-filter>            <intent-filter android:priority="100" >                <action android:name="BC_Two" />            </intent-filter>            <intent-filter>                <action android:name="BC_Three" />            </intent-filter>        </receiver>

android:priority属性可以指定广播接收的顺序,但只对有序广播有用。

最后要在Manifest文件中添加需要的权限:

    <uses-permission android:name="android.permission.BROADCAST_STICKY" />

运行结果如下:

  • 点击发送普通广播时:
    普通广播
    发现静态注册的两个接收器都接收到了广播,且这两条广播没有先后顺序。报错的原因是在接收器中修改了广播的内容。

  • 点击发送有序广播时:
    有序广播
    发现两个静态注册的接收器都接收到了广播,且第二个接收器先于第一个接收器接收到了广播。且第一个接收器接收到了第二个接收器修改过的广播内容。说明有序广播发送顺序有先后,且内容可以被修改。

  • 点击发送粘滞广播
    粘滞广播
    可以发现三个接收器都接收到了广播,且顺序没有先后。出现错误还是因为试图在接收器中修改广播的内容。

0 0