zoukankan      html  css  js  c++  java
  • 关于 android receiver

    可以在代码文件中声明一个receiver,也可以在manifest中声明一个,前者中的receiver只有在该activity launch起来以后才会监听其所感兴趣的事件,而如果在androidManifext.xml中声明的话,就不受限制,随时可以监听感兴趣的事件。 1.
    首先谈谈在androidManifext.xml中注册一个receiver, 例如我们想监听相机按钮按下事件的发生,并且发生后调用我们的camera程序
    <receiver android:name="CameraButtonIntentReceiver">             <intent-filter>   

    可以在代码文件中声明一个receiver,也可以在manifest中声明一个,前者中的receiver只有在该activity launch起来以后才会监听其所感兴趣的事件,而如果在androidManifext.xml中声明的话,就不受限制,随时可以监听感兴趣的事件。 1.
    首先谈谈在androidManifext.xml中注册一个receiver, 例如我们想监听相机按钮按下事件的发生,并且发生后调用我们的camera程序
    <receiver android:name="CameraButtonIntentReceiver">             <intent-filter>                 <action android:name="android.intent.action.CAMERA_BUTTON"/>             </intent-filter> </receiver>
    另外,当程序需要使用手机相关的服务, 如电话、短信、因特网等功能时,就得在Manifest中添加对于的user-permission。
    在这个配置文件中声明了一个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);
    在onStop及onDestroy中注销监听
    unregisterReceiver(mBatteryReceiver, Intent.ACTION_BATTERY_CHANGED);

    系统广播可以捕捉系统发出的行为有: 1. “android.provider.Telephony.SMS_RECEIVED” 收到短信 2. Intent.ACTION_BATTERY_CHANGED 剩余的手机电池量 3. Intent.ACTION_MEDIA_MOUNTED  SD卡成功挂载 4. Intent.ACTION_MEDIA_UNMOUNTED SD卡未挂载
    5. Intent.ACTION_NEW_OUTGOING_CALL拨打电话 6. Intent.ACTION_PACKAGE_ADDED执行安装 7. Intent.ACTION_PACKAGE_REMOVED 执行卸载
  • 相关阅读:
    python学习笔记(2)--sublimeText3运行python
    python学习笔记(1)--遍历txt文件,正则匹配替换文字
    JS学习笔记(4)--js变量的生命周期
    JS学习笔记(3)--json格式数据的添加,删除及排序方法
    JS学习笔记(2)--正则表达式获取指定字符串
    JS学习笔记(1)--sort排序
    VBA学习笔记(1)----VBA对象属性方法
    能够作图的软件都有哪些
    怎么用ChemDraw连接两个结构片段
    在几何画板上画椭圆可以根据椭圆第二定义
  • 原文地址:https://www.cnblogs.com/lzjsky/p/4941681.html
Copyright © 2011-2022 走看看