在 Android 中使用 Activity, Service, Broadcast, BroadcastReceiver
- 活动(Activity) - 用于表现功能
- 服务(Service) - 相当于后台运行的 Activity
- 广播(Broadcast) - 用于发送广播
- 广播接收器(BroadcastReceiver) - 用于接收广播
- Intent - 用于连接以上各个组件,并在其间传递消息
------------------------------------------------------悲伤的分割线----------------------------------------------------------------------------
一、只是简单的接收这个很简单。
想要监听屏幕锁屏代码:
1)注册一个接收器(文中用程序注册)
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); registerReceiver(mBatInfoReceiver, filter);2)实现接收器程序
private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
.....
if(Intent.ACTION_SCREEN_ON.equals(action)){
System.out.println(1);...}
------------------------------------------------------悲伤的分割线----------------------------------------------------------------------------
二、广播自定义的行为。
1. 构造Intent,发送广播
static final String ACTION_1 = "com.eoeAndroid.action.NEW_BROADCAST_1"; //这个action是自己定义的Intent intent = new Intent(ACTION_1); sendBroadcast(intent);
2. 继承BroadcastReceiver类,实现一个广播接受类public class EoeAndroidReceiver extends BroadcastReceiver { Context context; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub this.context = context; //接受信息并处理 } }3. 注册和注销BroadcastReceiver
方法1:在AndroidManifest.xml中注册
<receiver Android:name="EoeAndroidReceiver1"> <intent-filter> <action Android:name="com.eoeandroid.action.NEW_BROADCAST_1"/> </intent-filter> </receiver> 方法2:直接在代码中注册 IntentFilter filter = new IntentFilter(NEW_BROADCAST); //这个原文没有写,NEW_BROADCAST应该是等于"com.eoeandroid.action.NEW_BROADCAST_1"EoeAndroidReceiver eoeAR = new EoeAndroidReceiver(); registerReceiver(eoeAR, filter); 注销 unregisterReceiver(eoeAR);
------------------------------------------------------悲伤的分割线----------------------------------------------------------------------------
三、那个终于彻底看懂了的程序学习源:
主要的部分如图所示。Main函数一开始就注册接收 action为com.webabcd.service.msg(自定义action)的intent。
MyService的SendMsg函数调用sendBroadcast,广播行为为com.webabcd.service.msg的intent。