1. 动态注册与退出

  If registering a receiver in your Activity.onResume() implementation, you should unregister it in Activity.onPause(). (You won't receive

intents when paused, and this will cut down on unnecessary system overhead). Do not unregister in Activity.onSaveInstanceState(), because

this won't be called if the user moves back in the history stack.

2. 广播 Intent

  Although the Intent class is used for sending and receiving these broadcasts, the Intent broadcast mechanism here is completely

separate from Intents that are used to start Activities with Context.startActivity(). There is no way for a BroadcastReceiver to see or

capture Intents used with startActivity(); likewise, when you broadcast an Intent, you will never find or start an Activity.

  These two operations are semantically very different: starting an Activity with an Intent is a foreground operation that modifies what

the user is currently interacting with; broadcasting an Intent is a background operation that the user is not normally aware of.

  虽然 Intent 是用来发送和接收Broadcast的,但这里的机制与用来启动Activity 的Intent 的机制 是不同的。 BroadcastReceiver无法捕捉

Intent用于调用 startActivity() 的 .  类似的,当你广播 Intent , 你将永远不会启动一个Actitity.

  这个操作在语义上是完全不同的:用Intent 启动 一个Activity 是修改与 当前交互界面 的 前台操作,而广播一个Intent 是用户不会无法意识到的后台

操作。

3. Receiver Lifecycle

  A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this

function, the system considers the object to be finished and no longer active.

  This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires

asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation,

but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous

operation completes.

  In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead

use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service.

  特别是,您可能无法从一个BroadcastReceiver中显示一个对话框或绑定一个服务。对于前者,你反而应该使用NotificationManager的API。对于后者,

你可以使用Context.startService()来发送一个命令给服务。

4. Process Lifecycle

  A process that is currently executing a BroadcastReceiver (that is, currently running the code in its onReceive(Context, Intent) method)

is considered to be a foreground process and will be kept running by the system except under cases of extreme memory pressure.

  Once you return from onReceive(), the BroadcastReceiver is no longer active, and its hosting process is only as important as any other

application components that are running in it. This is especially important because if that process was only hosting the BroadcastReceiver

(a common case for applications that the user has never or not recently interacted with), then upon returning from onReceive() the system

will consider its process to be empty and aggressively kill it so that resources are available for other more important processes.

  This means that for longer-running operations you will often use a Service in conjunction with a BroadcastReceiver to keep the

containing process active for the entire time of your operation.

  

  一旦从OnReceive()返回,则BroadcastReceiver不再active, 它的宿主线程和其他运行的应用组件一样重要。这是特别重要的,因为如果该进程只是承载

BroadcastReceiver的(一种常见的情况为该用户从未或最近没有交互的应用程序),然后从返回的OnReceive(),系统会认为它的进程是空的,

积极(侵略地; 攻击地; 有闯劲地; 激烈地)杀死它,使资源可用于其他更重要的进程。

  这意味着,对于长时间运行的操作,你经常会联合使用一个Service 与一个BroadcastReceiver,以保持进程在操作的整个时间段内是活动的。

五。两种注册方式的区别

1.在AndroidManifest.xml中注册

        <receiver android:name=".MyReceiver">
<intent-filter >
<action android:name="myaction"/>
</intent-filter>
</receiver>

2.在Activity中注册

         MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("myaction");
registerReceiver(receiver, filter);

两种注册BroadcastReceiver方法的比较:

  i. 第一种注册的方法可以保证在应用程序安装之后,BroadcastReceiver始终处于活动状态,通常用于监听系统状态的改变,比如说手机的电量,

wifi网卡的状态(当然,监视这些东西也是取决于软件的需求)。对于这样的BroadcastReceiver,通常是在产生某个特定的系统事件之后,进行

相应的操作,比如说wifi网卡打开时,给用户一个提示;

  ii. 第二种注册方法相对第一种要灵活的多,这样注册的BroadcastReceiver通常用于更新UI的状态。一般来说,都是在一个Activity启动的时候使

用这样的方法注册BroadcastReceiver,一旦接收到广播的事件,就可以在onReceive方法当中更新当前的这个Activity当中的控件。但是需要注

意的是如果这个Activity不可见了,就应该调用unregisterReceiver方法来解除注册;

public abstract Intent registerReceiver (BroadcastReceiver receiver, IntentFilter filter)

  Register a BroadcastReceiver to be run in the main activity thread. The receiver will be called with any broadcast Intent that

matches filter, in the main application thread.

  The system may broadcast Intents that are "sticky" -- these stay around after the broadcast as finished, to be sent to any

later registrations. If your IntentFilter matches one of these sticky Intents, that Intent will be returned by this function and sent

to your receiver as if it had just been broadcast.

  There may be multiple sticky Intents that match filter, in which case each of these will be sent to receiver. In this case, only

one of these can be returned directly by the function; which of these that is returned is arbitrarily decided by the system.

  If you know the Intent your are registering for is sticky, you can supply null for your receiver. In this case, no receiver is

registered -- the function simply returns the sticky Intent that matches filter. In the case of multiple matches, the same rules as

described above apply.

//sticky形式的intent,接收者可以为空。接收者为空时,通常是获取最后一个保存广播的intent,从而获取intent里的值,如获取电池的电量:

//因为BatteryManager发送的是sticky形式的intent,所以接收者可以为空
Intent batteryStatus = registerReceiver(null, ifilter); //得到电池当前的状态(共有5种,包括unkonwn、charging、discharging、not charging、full)
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//是否处于充电状态
boolean isCharging = BatteryManager.BATTERY_STATUS_CHARGING ;

  As of ICE_CREAM_SANDWICH, receivers registered with this method will correctly respect the setPackage(String) specified for an Intent

being broadcast. Prior to that, it would be ignored and delivered to all matching registered receivers. Be careful if using this for security.

  Note: this method cannot be called from a BroadcastReceiver component; that is, from a BroadcastReceiver that is declared in an

application's manifest. It is okay, however, to call this method from another BroadcastReceiver that has itself been registered at run time

with registerReceiver(BroadcastReceiver, IntentFilter), since the lifetime of such a registered BroadcastReceiver is tied to the object that

registered it.

六。怎么用好 BroadcastReceiver 

  如果需要完成一项比较耗时的工作 , 应该通过发送 Intent 给 Service 来完成 。这里不能使用子线程来解决 , 因为 BroadcastReceiver

的生命周期很短 , 子线程可能还没有结束,BroadcastReceiver 就先结束了 。BroadcastReceiver 一旦结束 , 此时 BroadcastReceiver 的

所在进程很容易在系统需要内存时被杀死 , 因为它属于空进程 ( 没有任何活动组件的进程 )。如果它的宿主进程被杀死 , 那么正在工作的子线程

也会被杀死。

七。广播类型

sendBroadcast(Intent intent)

  • Broadcast the given intent to all interested BroadcastReceivers. This call is asynchronous; it returns immediately, and you will continue executing

while the receivers are run. No results are propagated from receivers and receivers can not abort the broadcast. If you want to allow receivers to

propagate results or abort the broadcast, you must send an ordered broadcast using sendOrderedBroadcast(Intent, String).

sendOrderedBroadcast(Intent intent, String receiverPermission)

  • Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume

the broadcast before it is delivered to less preferred receivers. This call is asynchronous; it returns immediately, and you will continue executing while the

receivers are run.

sendStickyBroadcast(Intent intent)

  • Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others

can quickly retrieve that data through the return value ofregisterReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as

sendBroadcast(Intent).

八。删除

removeStickyBroadcast (Intent intent)

  • Remove the data previously sent with sendStickyBroadcast(Intent), so that it is as if the sticky broadcast had never happened.

九。实例

public class MainActivity extends Activity {  

 private Button mSendBroadcast;
private Button mSendStickyBroadcast;
private Button mNextActivity;
private Context mContext; private int mStickyBrcCount; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = getApplicationContext();
mSendBroadcast = (Button)findViewById(R.id.broadcast);
mSendStickyBroadcast = (Button)findViewById(R.id.sticky_broadcast);
mNextActivity = (Button)findViewById(R.id.next_activity); mSendBroadcast.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.android.action.broadcast");
mContext.sendBroadcast(intent);
}
}); mSendStickyBroadcast.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mStickyBrcCount++;
Intent intent = new Intent("com.android.action.sticky.broadcast");
intent.putExtra("sent_count", mStickyBrcCount);
mContext.sendStickyBroadcast(intent);
}
});
mNextActivity.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ReceiverActivity.class);
startActivity(intent);
}
});
} @Override
protected void onResume() {
super.onResume();
Log.d("main", "------------------onResume");
mStickyBrcCount = 0;
} }

2.接收类

public class ReceiverActivity extends Activity {  

     private IntentFilter mIntentFilter;
private final static String TAG = "ReceiverActivity"; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sub); mIntentFilter = new IntentFilter();
mIntentFilter.addAction("com.android.action.broadcast");
mIntentFilter.addAction("com.android.action.sticky.broadcast"); } @Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver); } @Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
} private BroadcastReceiver mReceiver = new BroadcastReceiver () {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
int count = intent.getIntExtra("sent_count", -1);
Log.d(TAG, "------- action = " + action + "and count = " + count);
removeStickyBroadcast(intent);
}
}; }

BroadcastReceiver 翻译的更多相关文章

  1. 赵雅智:android教学大纲

    带下划线为详细内容链接地址.点击后可跳转.希望给大家尽一些微薄之力.眼下还在整理中 教学章节 教学内容 学时安排 备注 1 Android高速入门 2 Android模拟器与常见命令 3 Androi ...

  2. BroadcastReceiver详解

    详解 2014-08-20 19:42 13492人阅读 评论(8) 收藏 举报 分类: 5.andriod开发(148) 版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[+] ...

  3. 4、android BroadcastReceiver详细用法

    BroadcastReceiver也就是“广播接收者”的意思,顾名思义,它就是用来接收来自系统和应用中的广播. 在Android系统中,广播体现在方方面面,例如当开机完成后系统会产生一条广播,接收到这 ...

  4. 【Android Api 翻译3】android api 完整翻译之Application Fundamentals (学习android必须知道的)

    Android应用程序是用Java编程语言编写的.Android SDK工具把应用程序的代码.数据和资源文件一起编译到一个Android程序包中(这个程序包是以.apk为后缀的归档文件),一个Andr ...

  5. Google Android官方文档进程与线程(Processes and Threads)翻译

    android的多线程在开发中已经有使用过了,想再系统地学习一下,找到了android的官方文档,介绍进程与线程的介绍,试着翻译一下. 原文地址:http://developer.android.co ...

  6. 翻译Android USB HOST API

    翻译Android USB HOST API 源代码地址:http://developer.android.com/guide/topics/connectivity/usb/host.html 译者 ...

  7. 【Android开发】Android Host详解(翻译自官方文档)

    原文:http://android.eoe.cn/topic/summary 文档内容 API概述 Android中manifest文件需求 工作的设备 * 发现设备 * 获得和设备进行“交流”的权限 ...

  8. Android Activity、Service、BroadcastReceiver 的生命周期

    Activity.Service.BroadcastReceiver这三个组建是Android开发中最常使用到的组件,在它们的生命周期的各个阶段我们需要针对性的做些事情,了解这些组件的生命周期有利于我 ...

  9. 《Django By Example》第五章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者@ucag注:大家好,我是新来的翻译, ...

随机推荐

  1. OpenCV使用标定图

    本文由 @lonelyrains 出品,转载请注明出处.  文章链接: http://blog.csdn.net/lonelyrains/article/details/46915705 上一步生成标 ...

  2. php 显示一个干净的,易被解析的json

    header("Content-type: text/html; charset=utf-8"); //试着从数据库里读取一条数据放进来 $con = mysql_connect( ...

  3. c/c++学习之c++ 中的list <>容器

    http://blog.csdn.net/mazidao2008/article/details/4802617 push 实例化 即添加 http://www.cnblogs.com/BeyondA ...

  4. 【BZOJ】1688: [Usaco2005 Open]Disease Manangement 疾病管理(状压dp)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1688 很水的状压.. 提交了很多次优化的,但是还是100msT_T #include <cst ...

  5. 【BZOJ】1620: [Usaco2008 Nov]Time Management 时间管理(贪心)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1620 一开始想不通啊.. 其实很简单... 每个时间都有个完成时间,那么我们就从最大的 完成时间的开 ...

  6. 【BZOJ】1629: [Usaco2007 Demo]Cow Acrobats(贪心+排序)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1629 这题我想了很久都没想出来啊... 其实任意两头相邻的牛交换顺序对其它牛是没有影响的.. 那么我 ...

  7. 哪些工具可以在word中快速绘制图形

    在数学试卷.论文.电子教案等编写过程中,我们经常要作出数学图形或图像,若用Word自身携带的绘图工具绘制,多有不便.比如一些曲线的形状很难画得像,画到位,作图时修修改改,颇为费力,所以需要借助一些辅助 ...

  8. JMS和ActiveMQ的关系

    JMS和MQ的关系: JMS是一个用于提供消息服务的技术规范,它制定了在整个消息服务提供过程中的所有数据结构和交互流程.而MQ则是消息队列服务,是面向消息中间件(MOM)的最终实现,是真正的服务提供者 ...

  9. Memcached 之 .NET(C#)实例分析

    一:Memcached的安装 step1. 下载memcache(http://jehiah.cz/projects/memcached-win32)的windows稳定版(这里我下载了memcach ...

  10. mysql用sql创建表完整实例

    create table user_login_latest( id int(11) unsigned NOT NULL AUTO_INCREMENT, user_id int(11) not nul ...