Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1066272
  • 博文数量: 226
  • 博客积分: 10000
  • 博客等级: 上将
  • 技术积分: 2504
  • 用 户 组: 普通用户
  • 注册时间: 2006-06-21 14:12
文章分类

全部博文(226)

文章存档

2011年(1)

2010年(2)

2009年(68)

2008年(4)

2007年(27)

2006年(124)

我的朋友

分类: 嵌入式

2010-02-09 21:27:12

可以在代码文件中声明一个receiver,也可以在manifest中声明一个,前者中的receiver只有在该activity launch起来以后才会监听其所感兴趣的文件,而如果在androidManifext.xml中声明的话,就不受限制,随时可以监听感兴趣的事件。

首先谈谈在androidManifext.xml中注册一个receiver, 例如我们想监听相机按钮按下事件的发生,并且发生后调用我们的camera程序


<receiver android:name="CameraButtonIntentReceiver">
            <intent-filter>
                <action android:name="android.intent.action.CAMERA_BUTTON"/>
            </intent-filter>
</receiver>


在这个配置文件中声明了一个receiver用来监听相机的按键事件,所以还需要在代码文件定义与配置文件中同名的receiver



public class CameraButtonIntentReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
    Intent i = new Intent(Intent.ACTION_MAIN);
        i.setClass(context, Camera.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
}
}



2.

      关于另外一种,在代码中注册一个receiver,例如我们想在代码文件中监听电池电量的变化,就可以按照如下方法




private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
       @Override
        public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
              if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
              …
              }
        }
}


这种方法需要在onCreate 或者onStart中注册该receiver所感兴趣的intent,如:

registerReceiver(mBatteryReceiver, Intent.ACTION_BATTERY_CHANGED);


onStoponDestroy中注销监听


registerReceiver(mBatteryReceiver, Intent.ACTION_BATTERY_CHANGED);



阅读(3963) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~