BroastcastReceiver,Broastcast是应用程序间通信的手段。BroastcastReceiver也是跟Intent紧密相连的,动态/静态注册了BroastcastReceiver之后,使用sendBroadcast把Intent发送之后,系统会自动把符合条件的BroastcastReceiver启动,跟嵌入式系统的中断类似。

前面分别讨论了Activity和Service,这次就轮到BroastcastReceiver,Broastcast是应用程序间通信的手段。BroastcastReceiver也是跟Intent紧密相连的,动态/静态注册了BroastcastReceiver之后,使用sendBroadcast把Intent发送之后,系统会自动把符合条件的BroastcastReceiver启动,跟嵌入式系统的中断类似。

本文主要演示了如何静态/动态注册BroastcastReceiver,向系统索取电量信息,以及枚举信息的字段。本文运行截图如下:

上图是发送Intent至内部动态注册的BroadcastReceiver,接收到之后显示消息名称。动态注册BroadcastReceiver用到registerReceiver()。

上图是发送Intent至内部静态注册的BroadcastReceiver,接收到之后显示消息名称。静态注册比动态注册麻烦点,先新建一个类继承BroadcastReceiver,然后到AndroidManifest.xml 添加

view plaincopy to clipboardprint?
<receiver android:name="clsReceiver2"> 
    <intent-filter> 
        <action 
            android:name="com.testBroadcastReceiver.Internal_2"/> 
    </intent-filter> 
</receiver> 
  <receiver android:name="clsReceiver2">
   <intent-filter>
    <action
     android:name="com.testBroadcastReceiver.Internal_2"/>
   </intent-filter>
  </receiver>

第一个name是类名,第二个是action的名称。

上图是枚举Intent消息的字段,这个功能比较适合懒人,把收到的Intent消息的字段全部分解了,再看看哪个需要的,懒得记住。实现这部分的代码如下:

view plaincopy to clipboardprint?
//当未知Intent包含的内容,则需要通过以下方法来列举  
                Bundle b=intent.getExtras();  
                Object[] lstName=b.keySet().toArray();  
 
                for(int i=0;i<lstName.length;i++)  
                {  
                    String keyName=lstName[i].toString();  
                    Log.e(keyName,String.valueOf(b.get(keyName)));  
                } 
//当未知Intent包含的内容,则需要通过以下方法来列举
    Bundle b=intent.getExtras();
    Object[] lstName=b.keySet().toArray();

for(int i=0;i<lstName.length;i++)
    {
     String keyName=lstName[i].toString();
     Log.e(keyName,String.valueOf(b.get(keyName)));
    }

main.xml的代码如下:

view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
 
    <Button android:id="@+id/Button01" android:layout_width="wrap_content" 
        android:layout_height="wrap_content" android:text="发送至内部动态注册的BroadcastReceiver"></Button> 
    <Button android:id="@+id/Button02" android:layout_width="wrap_content" 
        android:layout_height="wrap_content" android:text="发送至内部静态注册BroadcastReceiver"></Button> 
    <Button android:id="@+id/Button03" android:layout_width="wrap_content" 
        android:layout_height="wrap_content" android:text="发送至系统BroadcastReceiver"></Button> 
</LinearLayout> 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">

<Button android:id="@+id/Button01" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:text="发送至内部动态注册的BroadcastReceiver"></Button>
 <Button android:id="@+id/Button02" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:text="发送至内部静态注册BroadcastReceiver"></Button>
 <Button android:id="@+id/Button03" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:text="发送至系统BroadcastReceiver"></Button>
</LinearLayout>

testBroadcastReceiver.java的代码如下:

view plaincopy to clipboardprint?
package com.testBroadcastReceiver;  
 
import android.app.Activity;  
import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.content.IntentFilter;  
import android.os.Bundle;  
import android.util.Log;  
import android.view.View;  
import android.widget.Button;  
import android.widget.Toast;  
 
public class testBroadcastReceiver extends Activity {  
    Button btnInternal1,btnInternal2,btnSystem;  
    static final String INTENAL_ACTION_1 = "com.testBroadcastReceiver.Internal_1";  
    static final String INTENAL_ACTION_2 = "com.testBroadcastReceiver.Internal_2";  
    static final String INTENAL_ACTION_3 = "com.testBroadcastReceiver.Internal_3";  
    @Override 
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        btnInternal1=(Button)this.findViewById(R.id.Button01);  
        btnInternal1.setOnClickListener(new ClickEvent());  
        btnInternal2=(Button)this.findViewById(R.id.Button02);  
        btnInternal2.setOnClickListener(new ClickEvent());  
        btnSystem=(Button)this.findViewById(R.id.Button03);  
        btnSystem.setOnClickListener(new ClickEvent());  
        //动态注册广播消息  
        registerReceiver(bcrIntenal1, new IntentFilter(INTENAL_ACTION_1));  
    }  
    class ClickEvent implements View.OnClickListener{  
 
        @Override 
        public void onClick(View v) {  
            if(v==btnInternal1)//给动态注册的BroadcastReceiver发送数据  
            {  
                Intent intent = new Intent(INTENAL_ACTION_1);  
                sendBroadcast(intent);  
            }  
            else if(v==btnInternal2)//给静态注册的BroadcastReceiver发送数据  
            {  
                Intent intent = new Intent(INTENAL_ACTION_2);  
                sendBroadcast(intent);  
            }  
            else if(v==btnSystem)//动态注册 接收2组信息的BroadcastReceiver  
            {  
                IntentFilter filter = new IntentFilter();//  
                filter.addAction(Intent.ACTION_BATTERY_CHANGED);//系统电量检测信息  
                filter.addAction(INTENAL_ACTION_3);//第三组自定义消息  
                registerReceiver(batInfoReceiver, filter);  
                  
                Intent intent = new Intent(INTENAL_ACTION_3);  
                intent.putExtra("Name", "hellogv");  
                intent.putExtra("Blog", "http://blog.csdn.net/hellogv");  
                sendBroadcast(intent);//传递过去  
            }  
        }  
          
    }  
      
    /* 
     * 接收动态注册广播的BroadcastReceiver 
     */ 
    private BroadcastReceiver bcrIntenal1 = new BroadcastReceiver() {  
          
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            Toast.makeText(context, "动态:"+action, 1000).show();  
        }  
    };  
      
 
    private BroadcastReceiver batInfoReceiver = new BroadcastReceiver() {  
          
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            //如果捕捉到的action是ACTION_BATTERY_CHANGED  
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {  
                //当未知Intent包含的内容,则需要通过以下方法来列举  
                Bundle b=intent.getExtras();  
                Object[] lstName=b.keySet().toArray();  
 
                for(int i=0;i<lstName.length;i++)  
                {  
                    String keyName=lstName[i].toString();  
                    Log.e(keyName,String.valueOf(b.get(keyName)));  
                }  
            }  
            //如果捕捉到的action是INTENAL_ACTION_3  
            if (INTENAL_ACTION_3.equals(action)) {  
                //当未知Intent包含的内容,则需要通过以下方法来列举  
                Bundle b=intent.getExtras();  
                Object[] lstName=b.keySet().toArray();  
 
                for(int i=0;i<lstName.length;i++)  
                {  
                    String keyName=lstName[i].toString();  
                    Log.e(keyName,b.getString(keyName));  
                }  
            }  
        }  
    };  
 
 

package com.testBroadcastReceiver;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class testBroadcastReceiver extends Activity {
    Button btnInternal1,btnInternal2,btnSystem;
    static final String INTENAL_ACTION_1 = "com.testBroadcastReceiver.Internal_1";
    static final String INTENAL_ACTION_2 = "com.testBroadcastReceiver.Internal_2";
    static final String INTENAL_ACTION_3 = "com.testBroadcastReceiver.Internal_3";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnInternal1=(Button)this.findViewById(R.id.Button01);
        btnInternal1.setOnClickListener(new ClickEvent());
        btnInternal2=(Button)this.findViewById(R.id.Button02);
        btnInternal2.setOnClickListener(new ClickEvent());
        btnSystem=(Button)this.findViewById(R.id.Button03);
        btnSystem.setOnClickListener(new ClickEvent());
        //动态注册广播消息
  registerReceiver(bcrIntenal1, new IntentFilter(INTENAL_ACTION_1));
    }
    class ClickEvent implements View.OnClickListener{

@Override
  public void onClick(View v) {
   if(v==btnInternal1)//给动态注册的BroadcastReceiver发送数据
   {
    Intent intent = new Intent(INTENAL_ACTION_1);
    sendBroadcast(intent);
   }
   else if(v==btnInternal2)//给静态注册的BroadcastReceiver发送数据
   {
    Intent intent = new Intent(INTENAL_ACTION_2);
    sendBroadcast(intent);
   }
   else if(v==btnSystem)//动态注册 接收2组信息的BroadcastReceiver
   {
    IntentFilter filter = new IntentFilter();//
          filter.addAction(Intent.ACTION_BATTERY_CHANGED);//系统电量检测信息
          filter.addAction(INTENAL_ACTION_3);//第三组自定义消息
    registerReceiver(batInfoReceiver, filter);
    
    Intent intent = new Intent(INTENAL_ACTION_3);
    intent.putExtra("Name", "hellogv");
    intent.putExtra("Blog", "http://blog.csdn.net/hellogv");
    sendBroadcast(intent);//传递过去
   }
  }
     
    }
   
    /*
     * 接收动态注册广播的BroadcastReceiver
     */
 private BroadcastReceiver bcrIntenal1 = new BroadcastReceiver() {
  
  public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   Toast.makeText(context, "动态:"+action, 1000).show();
  }
 };

private BroadcastReceiver batInfoReceiver = new BroadcastReceiver() {
  
  public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   //如果捕捉到的action是ACTION_BATTERY_CHANGED
   if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
    //当未知Intent包含的内容,则需要通过以下方法来列举
    Bundle b=intent.getExtras();
    Object[] lstName=b.keySet().toArray();

for(int i=0;i<lstName.length;i++)
    {
     String keyName=lstName[i].toString();
     Log.e(keyName,String.valueOf(b.get(keyName)));
    }
   }
   //如果捕捉到的action是INTENAL_ACTION_3
   if (INTENAL_ACTION_3.equals(action)) {
    //当未知Intent包含的内容,则需要通过以下方法来列举
    Bundle b=intent.getExtras();
    Object[] lstName=b.keySet().toArray();

for(int i=0;i<lstName.length;i++)
    {
     String keyName=lstName[i].toString();
     Log.e(keyName,b.getString(keyName));
    }
   }
  }
 };

}

clsReceiver2.java的代码如下:

view plaincopy to clipboardprint?
package com.testBroadcastReceiver;  
 
import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.widget.Toast;  
 
/* 
 * 接收静态注册广播的BroadcastReceiver, 
 * step1:要到AndroidManifest.xml这里注册消息 
 *      <receiver android:name="clsReceiver2"> 
            <intent-filter> 
                <action 
                    android:name="com.testBroadcastReceiver.Internal_2"/> 
            </intent-filter> 
        </receiver> 
    step2:定义消息的字符串 
    step3:通过Intent传递消息来驱使BroadcastReceiver触发 
 */ 
public class clsReceiver2 extends BroadcastReceiver{  
    @Override 
    public void onReceive(Context context, Intent intent) {  
        String action = intent.getAction();  
        Toast.makeText(context, "静态:"+action, 1000).show();  
          
    }  
}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hellogv/archive/2010/11/10/5999170.aspx

Android提高篇1 之 BroadcastReceiver 应用程序间通信的手段相关推荐

  1. Android提高篇内容整理

    1.Android提高第一篇之MediaPlayer http://www.apkbus.com/android-23947-1-1.html 2.Android提高第二篇之SurfaceView的基 ...

  2. android 面试 android 知识点 提高篇

    来源:以前网上买的资料+面试遇到的+百度到的 ____本篇为提高篇 一.Android性能优化 1.如何对Android应用进行性能分析 一款App流畅与否安装在自己的真机里,玩几天就能有个大概的感性 ...

  3. Android自动化测试第二季(提高篇)-金阳光-专题视频课程

    Android自动化测试第二季(提高篇)-17804人已学习 课程介绍         [金阳光测试]是由金阳光等创办的国内个人免费培训测试.欢迎喜欢测试的朋友来观看学习,提意见. 课程收益      ...

  4. 【建议收藏】2020年中高级Android大厂面试秘籍,为你保驾护航金三银四,直通大厂(Android高级篇上)...

    前言 成为一名优秀的Android开发,需要一份完备的知识体系,在这里,让我们一起成长为自己所想的那样~. A awesome android expert interview questions a ...

  5. 【建议收藏】2020年中高级Android大厂面试秘籍,为你保驾护航金三银四,直通大厂(Android基础篇)...

    前言 成为一名优秀的Android开发,需要一份完备的知识体系,在这里,让我们一起成长为自己所想的那样~. A awesome android expert interview questions a ...

  6. 【建议收藏】2020年中高级Android大厂面试秘籍,为你保驾护航金三银四,直通大厂(Android高级篇-2)...

    前言 成为一名优秀的Android开发,需要一份完备的知识体系,在这里,让我们一起成长为自己所想的那样~. A awesome android expert interview questions a ...

  7. 【朝花夕拾】Android性能篇之(二)Java内存分配

    前言       原文:[朝花夕拾]Android性能篇之(二)Java内存分配        在内存方面,相比于C/C++程序员,咱们java系程序员算是比较幸运的,因为对于内存的分配和回收,都交给 ...

  8. 【转】java提高篇(十)-----详解匿名内部类

    原文网址:http://www.cnblogs.com/chenssy/p/3390871.html 在java提高篇-----详解内部类中对匿名内部类做了一个简单的介绍,但是内部类还存在很多其他细节 ...

  9. 一款APP设计的从0到1之:Android设计规范篇(转载)

    一款APP设计的从0到1之:Android设计规范篇 原创 2017-08-29 U妹 UI妹儿 之前U妹给大家分享了<一款APP设计的从0到1之:iOS精华篇>,今天U妹给大家带来的是A ...

最新文章

  1. python数据框新建一个列并赋值_pandas.DataFrame 根据条件新建列并赋值的方法
  2. centos6 kvm网卡桥接
  3. 【Python】参考ggplot2,Seaborn将迎来超大版本更新!
  4. python中变量作用域
  5. Java基础 main 参数String[] args的用法
  6. 问题六十七:ray tracing学习总结(2016.11.13, 2017.02.05)
  7. c++修复工具_别再花钱修复旧照片啦!老照片一键修复工具,独创方法支持PS2020...
  8. Python | 实现pdf文件分页
  9. android投影电脑屏幕,如何在电脑上投影手机屏幕
  10. python word文档合并_[Python 学习笔记]用Python进行docx文档合并
  11. [bzoj5369][状压DP]最大前缀和
  12. Acwing-4645. 选数异或
  13. 【算法】滴滴-2021校招在线笔试0913 X星文
  14. 在论文中加入(制作)目录方法
  15. ubuntu可爱的玩具:小猫咪 oneko
  16. 计算机音乐乐谱再也没有,在古代.这类音乐作品只有文字记载.没有乐谱资料.既无法演奏.也无法演唱.(在“既无法演奏 前加上“在今天 )...
  17. JAVA视频学习笔记-马士兵(七)
  18. H5微信内置浏览器携带参数跳转APP和监听是否安装APP(wx-open-launch-app)
  19. 机器学习01_吴恩达版学习笔记
  20. Sql中如何保留小数点两位

热门文章

  1. openssh升级_Redhat 6.5源码编译升级openssh到7.8版本
  2. _报告指出:黑客已将攻击的目标逐渐迁移到 Linux 服务器和工作站上
  3. kind富文本编辑器_在项目中集成富文本编辑器
  4. 使用该JavaBean可以将数据在JSP页面中以表格的形式显示出来 并具有动态排序 动态生成查询 自动分页功能
  5. 《天天数学》连载14:一月十四日
  6. 英语学习笔记2019-11-01
  7. VB讲课笔记02:VB程序开发环境
  8. 5.过滤器作为模板——寻找沃尔多、不相同的模板匹配_3
  9. php输出mysql查询结果_PHP简单获取数据库查询结果并返回JSON
  10. Intel Sandy Bridge/Ivy Bridge架构/微架构/流水线 (7) - 流水线前端/译码后指令缓存