Android中的广播基本实现及回调方法的理解

在Android中broadcast这一节的内容其实不算多主要是牵扯到一个broadcastreceiver类,这个类是一个抽象类,下面有一个抽象方法onreceiver(),可以再我们收到网络状态变化时执行,改抽象方法是一个回调方法,说道回调方法一般只能是抽象方法或者是接口,因为回调方法就是为了让父类或者其他类能调用一个统一的方法(主要是方便其他类),这就像是c+中的动态联编。不同的子类有不同的实现。可以看博客https://blog.csdn.net/chenyefei/article/details/78558974。好了回到broadcastreceiver类,看看api中对他的Lifecycle的解释:BroadcastReceiver对象仅在调用OnReceive(android.content.context,android.content.intent)期间有效。一旦您的代码从此函数返回,系统将认为该对象已完成且不再处于活动状态。这对您在onReceive(android.content.context,android.content.intent)实现中可以执行的操作有重要影响:任何需要异步操作的操作都不可用,因为您需要从函数返回以处理异步操作,但此时,BroadcastReceiver不再处于活动状态,并且因此,在异步操作完成之前,系统可以*地终止其进程。特别是,您不能显示一个对话框或从广播接收器中绑定到服务。对于前者,您应该使用notificationmanager API。对于后者,可以使用context.startService()向服务发送命令。这说明broadcastreciver类是在onrecive方法回调之前存活,但是为什么broadcastreciver类会自动回调onrevive方法我在broadcastreciver类的源码中找了一下并没有哪个方法调用了onrecive方法所以,我并不明白onrecive是怎么自动回调的。总之在重写onrecive方法时实现了具体的功能,然后就是注册了调用registerreciver方法注意这个方法至少需要一个intentfilter实例和一个broadcastreciver实例。然后在activity的ondestory方法中要unregisterreciver方法注销。这就是大概的过程了还是很简单的。

This has important repercussions to what you can do in an onReceive(android.content.Context, android.content.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.

zhèduìnínzài在 o n R e c e i v e ( a n d r o i d . c o n t e n t . c o n t e x t , a n d r o i d . c o n t e n t . i n t e n t ) shíxiànzhōngzhíxíngdecāozuòyǒuzhòngyàoyǐngxiǎng响 : rènyàocāozuòdecāozuòdōuyòng用 , yīnwèinínyàocónghánshùfǎnhuíchǔcāozuò作 , dànshí时 , B r o a d c a s t R e c e i v e r zàichǔhuódòngzhuàngtài态 , bìngqiěyīn此 , zàicāozuòwánchéngzhīqián前 , tǒngyóudezhōngzhǐjìnchéng程 。

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.

上一篇:python练习程序(显示图像)


下一篇:Python中的三种数据结构