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> 
                    <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 执行卸载
  • 相关阅读:
    vmware ubuntu 异常关机无法连接到网络
    Speed up GCC link
    常用的一些解压命令
    Log4j 漏洞复现
    Test Case Design method Boundary value analysis and Equivalence partitioning
    CCA (Citrix Certified Administrator) exam of “Implementing Citrix XenDesktop 4”
    What is Key Word driven Testing?
    SAP AGS面试小结
    腾讯2013终端实习生一面
    指针的引用
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318023.html
Copyright © 2011-2022 走看看