Android应用开发基础篇(7)-----BroadcastReceiver

一、概述

      BroadcastReceiver,意思就是广播信息接收者,是Android的四大组件之一。它既可以接收系统广播出来的信息,也可以接收自定义的广播信息,比如说接收系统开机完成的信息,然后让某个程序启动,这就可以实现程序开机启动,又或者,某个程序需要通过Service发出的信息来更新UI,这时也可以使用BroadcastReceiver。


二、要求

     编写一个程序,能够接收自定义的广播信息,程序在接收到这个信息后把收到的信息显示到屏幕上。


三、实现

     新建工程MyBroadcast,修改/res/layout/main.xml文件,在里面添加一个Button和一个TextView,完整的main.xml文件如下:

 1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="fill_parent"
5 android:orientation="vertical" >
6
7 <Button
8 android:id="@+id/mbutton"
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 android:text="发送广播"
12 />
13
14 <View
15 android:layout_width="fill_parent"
16 android:layout_height="70dp"
17 />
18
19 <TextView
20 android:id="@+id/mtextview"
21 android:layout_width="fill_parent"
22 android:layout_height="wrap_content"
23 android:textSize="30dp"
24 android:textColor="#FF0000FF"
25 android:gravity="center_horizontal"
26 />
27
28 </LinearLayout>

接着,修改MyBroadcastActivity.java文件,编写一个BroadcastReceiver的子类,实现它的onReceive()方法,注册一个接收者。完整的MyBroadcastActivity.java如下:

 

 1 package com.nan.receiver;
2
3 import android.app.Activity;
4 import android.content.BroadcastReceiver;
5 import android.content.Context;
6 import android.content.Intent;
7 import android.content.IntentFilter;
8 import android.os.Bundle;
9 import android.view.View;
10 import android.widget.Button;
11 import android.widget.TextView;
12
13
14 public class MyBroadcastActivity extends Activity
15 {
16 private Button mButton = null;
17 private TextView mTextView = null;
18
19 /** Called when the activity is first created. */
20 @Override
21 public void onCreate(Bundle savedInstanceState)
22 {
23 super.onCreate(savedInstanceState);
24 setContentView(R.layout.main);
25
26 mTextView = (TextView)findViewById(R.id.mtextview);
27
28 mButton = (Button)findViewById(R.id.mbutton);
29 //设置按钮监听
30 mButton.setOnClickListener(new View.OnClickListener()
31 {
32
33 public void onClick(View v)
34 {
35 // TODO Auto-generated method stub
36 Intent mIntent = new Intent();
37 //设置接收动作
38 mIntent.setAction("com.nan.action.MY_ACTION");
39 //设置发送的内容
40 mIntent.putExtra("MY", "您好!");
41 //发送广播
42 sendBroadcast(mIntent);
43 }
44 });
45 //注册接收
46 registerReceiver(mReceiver,new IntentFilter("com.nan.action.MY_ACTION"));
47
48 }
49
50 //自定义一个继承BroadcastReceiver的类
51 private BroadcastReceiver mReceiver = new BroadcastReceiver()
52 {
53
54 @Override
55 public void onReceive(Context context, Intent intent)
56 {
57 // TODO Auto-generated method stub
58 //显示接收到的信息
59 mTextView.setText(intent.getStringExtra("MY"));
60 }
61
62 };
63
64 }

好了,运行该程序,如下:

 

点击一下“发送广播”按钮,如下:

 

完成。


后记:

      还可以把BroadcastReceiver的子类写在一个单独的java文件里,这时就需要修改AndroidManifest.xml文件,在里面声明一个receiver。



posted @ 2012-02-22 18:58  lknlfy  阅读(805)  评论(0编辑  收藏  举报