Broadcast Receiver是为了实现系统广播而提供的一种组件。例如,我们可以发一种广播来检测手机电量的变化,这时候就可以定义一个Broadcast Receiver来接收广播,当手机电量较低时提示用户。
Broadcast Receiver顾名思义是广播接收器的意思,它和事件处理机制类似,只不过事件处理机制是程序组件级别的,而广播事件处理机制是系统级别的。我们可以使用Intent来启动一个程序组件,通过使用sendBroadcast()方法来发起一个系统级别的事件广播来传递消息。然后可以在应用程序中实现Broadcast Receiver(覆盖onReceive()方法)来监听和响应这些广播的Intent。
下面看一个简单的例子:
package com.app;
import com.app.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
*
* 发出广播
*/
public class MainActivity extends Activity {
// 定义一个Action常量
private static final String MY_ACTION = "com.action.MY_ACTION";
// 定义一个Button对象
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置当前布局视图
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.Button01);
// 为按钮设置单击监听器
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 实例化Intent对象
Intent intent = new Intent();
// 设置Intent action属性
intent.setAction(MY_ACTION);
// 为Intent添加附加信息
intent.putExtra("msg", "地瓜地瓜,我是土豆,收到请回复,收到请回复!");
// 发出广播
sendBroadcast(intent);
}
});
}
}package com.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* 接收广播
*/
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context cxt, Intent intent) {
// 从Intent中获得信息
String msg = intent.getStringExtra("msg");
// 使用Toast显示
Toast.makeText(cxt, msg, Toast.LENGTH_LONG).show();
}
}在AndroidManifest.xml中要注册这个广播:
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.action.MY_ACTION"/>
</intent-filter>
</receiver>
结果:
本文介绍了Android中的BroadcastReceiver组件,展示了如何使用Intent发送广播,并通过一个简单示例解释了如何创建和注册BroadcastReceiver来监听和响应广播事件。
3965

被折叠的 条评论
为什么被折叠?



