Android 广播 Broadcast学习

 

Android Broadcast 广播

 

进程内本地广播

  如果你是在你的应用之内使用广播,即不需要跨进程,考虑使用LocalBroadcastManager ,这样更有效率(因为不需要跨进程通信),并且你不用考虑一些其他应用可以发送或接收你的广播相关的安全问题。

 

  下面介绍更一般的方法。

 

广播的两种注册方法

  广播有静态和动态两种注册方法:

  静态注册:在AndroidManifest.xml中加上<receiver> 标签。

  动态注册:通过 Context.registerReceiver()方法进行注册。比如在onResume中注册,在onPause中注销。

 

  附上例子(例子中的布局、MyReceiver类,常量类都是相同的,在前面列出):

  布局文件都一样:

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".DemoBroadcastActivity" ><TextViewandroid:id="@+id/helloText"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/hello_world" /><Buttonandroid:id="@+id/sendBtn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/helloText"android:text="@string/send" /></RelativeLayout>

 

 

  自己写的Receiver类:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;public class MyReceiver extends BroadcastReceiver
{public MyReceiver(){super();Log.d(AppConstants.LOG_TAG, "Receiver constructor");}@Overridepublic void onReceive(Context context, Intent intent){Log.d(AppConstants.LOG_TAG, "onReceive");String message = intent.getStringExtra(AppConstants.MSG_KEY);Log.i(AppConstants.LOG_TAG, message);Toast.makeText(context, "Received! msg: " + message, Toast.LENGTH_SHORT).show();}}

  应用常量:

public class AppConstants
{public static final String LOG_TAG = "Broadcast";public static final String MSG_KEY = "msg";public static final String BROADCAST_ACTION ="com.example.demobroadcast.BroadcastAction";}

 

  下面就是不同的部分了!

 

  静态注册的实例代码:

  静态注册是在manifest文件中进行:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.demobroadcast"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="17" /><uses-permission android:name="android.permission.RECEIVE_SMS" /><uses-permission android:name="android.permission.SEND_SMS" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="com.example.demobroadcast.DemoBroadcastActivity"android:label="@string/app_name" ><intent-filter android:priority="1000"><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><receiverandroid:name="com.example.demobroadcast.MyReceiver"><intent-filter  ><action android:name="com.example.demobroadcast.BroadcastAction" /></intent-filter></receiver></application></manifest>

 

  所以Java代码:

package com.example.demobroadcast;import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;public class DemoBroadcastActivity extends Activity
{private Button sendBtn = null;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_demo_broadcast);sendBtn = (Button) findViewById(R.id.sendBtn);sendBtn.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){Intent intent = new Intent();intent.setAction(AppConstants.BROADCAST_ACTION);intent.putExtra("msg", "圣骑士wind");sendBroadcast(intent);}});}}

 

 

  动态注册的实例代码:

  动态注册是在Java代码中进行:

 

package com.example.demobroadcast2;import com.example.demobroadcast.R;import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;public class DemoBroadcastActivity extends Activity
{private Button sendBtn = null;private MyReceiver mReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_demo_broadcast);sendBtn = (Button) findViewById(R.id.sendBtn);sendBtn.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){Intent intent = new Intent();intent.setAction(AppConstants.BROADCAST_ACTION);intent.putExtra("msg", "圣骑士wind");sendBroadcast(intent);}});}@Overrideprotected void onResume(){super.onResume();mReceiver = new MyReceiver();IntentFilter intentFilter= new IntentFilter(AppConstants.BROADCAST_ACTION);registerReceiver(mReceiver, intentFilter);}@Overrideprotected void onPause(){super.onPause();unregisterReceiver(mReceiver);}@Overrideprotected void onDestroy(){super.onDestroy();}}

 

  所以Manifest文件中不需要添加标签,正常就行。

 

 

两种广播

  Normal broadcasts

  通过 Context.sendBroadcast发送,完全是异步的(asynchronous)。所有的接收器以不确定的顺序运行,通常是同时。

  这样更有效率,但是也意味着接收器不能传递结果,也不能退出广播。

  Ordered broadcasts

  通过 Context.sendOrderedBroadcast发送。一次只向一个接收器发送。

  由于每个接收器按顺序执行,它可以向下一个接收器传递结果,也可以退出广播不再传递给其他接收器。

  接收器运行的顺序可以通过 android:priority 属性来控制,相同优先级的接收器将会以随机的顺序运行。

 

接收器的生命周期

  一个BroadcastReceiver的对象只在 onReceive(Context, Intent)被调用的期间有效,一旦从这个方法返回,系统就认为这个对象结束了,不再活跃。

  这对你在onReceive中能做什么有很大的影响:不能做任何需要的操作(anything that requires asynchronous operation is not available)。

  因为你需要从方法返回去进行你的异步操作,而返回时BroadcastReceiver的对象已经不再活跃了,系统可以(在异步操作完成前)任意杀死它的进程。

  特别地,不可以在BroadcastReceiver中显示对话框或者绑定一个service,前者应该用 NotificationManager,后者应该用Context.startService()。

 

参考资料

  官方文档BroadcastReceiver:

  http://developer.android.com/reference/android/content/BroadcastReceiver.html

  LocalBroadcastManager:

  http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html 

  Training: Manipulating Broadcast Receivers On Demand

  http://developer.android.com/training/monitoring-device-state/manifest-receivers.html

  receiver标签

  http://developer.android.com/guide/topics/manifest/receiver-element.html

 

 

 

转载于:https://www.cnblogs.com/mengdd/archive/2013/06/14/3135431.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/376607.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python:将时间戳转换成格式化日期

import time # 将时间戳转换成格式化日期 def timestamp_to_str(timestampNone, format%Y-%m-%d %H:%M:%S):if timestamp:time_tuple time.localtime(timestamp) # 把时间戳转换成时间元祖result time.strftime(format, time_tuple) # 把时间元祖转换成格式化好的时间retur…

WebApp 里Meta标签大全

1.先说说mate标签里的viewport&#xff1a; viewport即可视区域&#xff0c;对于桌面浏览器而言&#xff0c;viewport指的就是除去所有工具栏、状态栏、滚动条等等之后用于看网页的区域。对于传统WEB页面来说&#xff0c;980的宽度在iphone上显示是很正常的&#xff0c;也是满屏…

python:封装CRUD操作

# 封装数据库操作 def SELECT(db, cursor, sql):try:# 执行SQL语句db.ping(reconnectTrue)cursor.execute(sql)# 获取所有记录列表results cursor.fetchall()logging.debug("select commit")except:logging.error(sql)logging.error("select 语句执行出错"…

我的osu游戏程序设计(oo)

osu是一款社区元素为主旨的音乐游戏,由澳大利亚人Dean Herbert (peppy)独立制作并运行. 游戏的方法简单,就是 1. 圈圈(Circle)&#xff1a;圈圈(Circle) 50。没打中显示X,并减少生命值。圈中序号的最后一个的300、100会显示为激300、喝100。2.滑条(Slider) : 在开始端点击按住不…

影像数据库调研

参考Paul Graham比较各种编程语言的方法&#xff0c;我们比较各种数据库的特点如下&#xff1a; Oracle: 我们需要企业级数据库。 MySQL: Oracle不开源。 PostgreSQL: MySQL的功能不够多。 SQLite: 你可以把我嵌入到任何地方。这样&#xff0c;4种数据库够大家用了。 MongoDB: …

linux进程间通信快速入门【三】:信号量(XSI、POSIX以及PV原语)

文章目录XSIsemgetsemop、semtimedopsemctl基于共享内存demo修改XSI信号量的限制PV原语PV控制并发进程数POSIX信号量使用posix命名信号量使用posix匿名信号量参考在前两篇文章中我们使用的racingdemo都没有对临界区代码进行加锁&#xff0c;这里我们介绍以下信号量的使用。Linu…

QTableWidget的使用详细介绍和美工总结(转)

基本外观设置 FriendTable->setFrameShape(QFrame::NoFrame); //设置边框 FriendTable->setHorizontalHeaderLabels(HeadList); 设置表头 FriendTable->setSelectionMode(QAbstractItemView::SingleSelection); 设置选择的模式为单选择 FriendTable->setSelect…

Android programming on Mac 之安装Eclipse

1.安装包在此链接下载&#xff1a; http://developer.android.com/sdk/index.html google GoAgent翻墙不好用&#xff0c;更新了host文件也不行&#xff0c;整了半天&#xff0c;还是一怒之下续签了vpn账号。早知如此&#xff0c;何必折腾。~~~~(>_<)~~~~ 更新文件时…

c++关于虚表的一些笔记

文章目录1、虚函数表指针2、多态构成的条件3、重载、重写、重定义 三者区别4、继承与虚函数5、单继承中的虚函数表无虚函数覆盖有虚函数覆盖6、单继承中的虚函数表无虚函数覆盖有虚函数覆盖参考看《深度探索c对象模型》的时候对虚表有了点疑惑&#xff0c;正好网上有些文章解除…

4、在Shell程序中的使用变量

学习目标变量的赋值变量的访问变量的输入 12-4-1 变量的赋值在Shell编程中&#xff0c;所有的变量名都由字符串组成&#xff0c;并且不需要对变量进行声明。要赋值给一个变量&#xff0c;其格式如下&#xff1a;变量名值。注意&#xff1a;等号()前后没有空格例如&#xff1a; …

C语言技巧:把单一元素的数组放在末尾,struct可以拥有可变大小的数组

《C 对象模型》第19页有这样一句话 C程序员的巧计有时候却成为c程序员的陷阱。例如把单一元素的数组放在一个struct的末尾&#xff0c;于是每个struct objects可以拥有可变数组的数组&#xff1a; struct mumble {/* stuff */char pc[1]; };//从文件或标准输入装置中取得一个…

探讨C++ 变量生命周期、栈分配方式、类内存布局、Debug和Release程序的区别(二)...

看此文&#xff0c;务必需要先了解本文讨论的背景&#xff0c;不多说&#xff0c;给出链接&#xff1a; 探讨C 变量生命周期、栈分配方式、类内存布局、Debug和Release程序的区别&#xff08;一&#xff09; 本文会以此问题作为讨论的实例&#xff0c;来具体讨论以下四个问题&a…

后台系统可扩展性学习笔记(一)概要

文章目录系统大致架构可扩展性负载均衡器与会话保持引入冗余增强系统可用性缓存减轻数据库压力异步处理参考系统大致架构 当一个用户请求从客户端出发&#xff0c;经过网络传输&#xff0c;达到 Web 服务层&#xff0c;接着进入应用层&#xff0c;最后抵达数据层&#xff0c;它…

poj 3728(LCA + dp)

题目链接&#xff1a;http://poj.org/problem?id3728 思路&#xff1a;题目的意思是求树上a -> b的路径上的最大收益&#xff08;在最小值买入&#xff0c;在最大值卖出&#xff09;。 我们假设路径a - > b 之间的LCA(a, b) f, 并且另up[a]表示a - > f之间的最大收益…

成功之路

1、每天都要有进步&#xff0c;都要有新知识的收获。 2、工作认真负责&#xff0c;高效的完成&#xff0c;多总结。 3、自己多练习一些感兴趣的东西&#xff0c;实践&#xff01;&#xff01;&#xff01; 4、写博客。 5、百度、腾讯、阿里是目标&#xff0c;差距还很大&#x…

后台系统可扩展性学习笔记(二)权衡取舍

文章目录性能与可扩展性延迟与吞吐量可用性与一致性一致性模式可用性模式可用性衡量参考系统设计中也面临许多权衡取舍&#xff1a;性能与可扩展性延迟与吞吐量可用性与一致性 性能与可扩展性 可扩展&#xff0c;意味着服务能以加资源的方式成比例地提升性能&#xff0c;性能…

iOS中使用子线程的完整方法

第一步&#xff1a;开启子线程 //开启子线程到网络上获取数据myFirstThread [[NSThread alloc]initWithTarget:self selector:selector(thread1GetData) object:nil];[myFirstThread setName:"第一个子线程,用于获取网络数据"];[myFirstThread start]; 第二步&…

DIV的表单布局

表单布局其实用表格最好了&#xff0c;可是表格的话&#xff0c;无法定位&#xff0c;这个是一个硬伤。 <!DOCTYPE html> <html> <head> <meta charset"utf-8" /> <title>表单布局</title> <link rel"stylesheet" …

后台系统可扩展性学习笔记(三)DNS机制原理

文章目录DNS概念梳理域名基本概念资源记录基本概念路由策略DNS 域空间结构实现原理复制机制查询机制缓存机制参考DNS概念梳理 DNS&#xff08;Domain Name System&#xff09;相当于互联网的通讯录&#xff0c;能够把域名翻译成 IP 地址。 从技术角度来讲&#xff0c;DNS 是个…