当前位置:网站首页>Android kotlin broadcast technology point
Android kotlin broadcast technology point
2022-07-02 13:31:00 【lpf_ wei】
Android In order to facilitate system level message notification , The broadcasting mechanism is introduced . If you want to receive the broadcast, you must register the broadcast receiver -BroadcastReceiver
1. Classification of broadcasting
- Standard radio : Is a completely asynchronous broadcast , After sending, all recipients will receive it almost at the same time , There is no backward order , This kind of broadcasting is more efficient .
- Ordered broadcasting : It is a synchronous broadcast , Only one receiver receives this broadcast at the same time , And there is the concept of priority , The receiver with high priority receives the broadcast first . The receiver who receives this broadcast can terminate this broadcast .
2. Registration of radio
Dynamic registration : The receiver registered in the code , You need to de register in the corresponding declaration cycle .
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_broadcast) register() } /** * Dynamic registration broadcast */ private fun register() { val intentFilter=IntentFilter() intentFilter.addAction("android.intent.action.TIME_TICK") receiver=TimeChangeReceiver() registerReceiver(receiver,intentFilter) } inner class TimeChangeReceiver :BroadcastReceiver(){ override fun onReceive(context: Context?, intent: Intent?) { showToast("time change") } } override fun onDestroy() { super.onDestroy() // Unregister broadcast unregisterReceiver(receiver) }Static registration : stay AndroidManifest List the broadcast recipients registered by the file , The application can receive the broadcast even if it is not started , And execute the relevant code logic in the broadcast .
class BootCompleteReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // This method is called when the BroadcastReceiver is receiving an Intent broadcast. showToast("reboot already") } } <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application ... android:theme="@style/AppTheme"> <receiver android:name=".broadcast.BootCompleteReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> ... </application>
In this way, a static broadcast is registered , Can listen to the radio and pop up Tooast.exported=“true” Indicates that you are allowed to receive broadcasts other than this program ,enabled=“true” Indicates that this broadcast receiver is enabled .
Android In order to protect the security and privacy of users' devices : If the program needs to do some sensitive operations , Permission must be declared , The above one needs to declare permission to start broadcasting, otherwise it will crash .
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Restart the phone , Then I received the startup broadcast .
3. Implicit broadcasting
Implicit broadcasts are those that are not specifically assigned to that application .Android System 8.0 After that, all implicit broadcasts are not allowed to use static registration to receive . A few special system broadcasts are still available , such as :RECEIVE_BOOT_COMPLETED. The custom broadcast we send is also an implicit broadcast , If you want to be received by your own application , You need to specify the package name explicitly .
4. Send a broadcast
Statically register custom broadcast recipients , And designate Action
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// This method is called when the BroadcastReceiver is receiving an Intent broadcast.
showToast("receive my Broadcast" )
}
}
//AndroidManifest add to
<receiver
android:name=".broadcast.MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.test.kotlin_test.MY_RECEIVER"/>
</intent-filter>
</receiver>
Send standard broadcast , Note that you need to set the package name of the application ,intent.setPackage(“com.test.kotlin_test”) Indicate which application this broadcast is sent to , So this broadcast is not an implicit broadcast , Otherwise, static registration cannot receive .
fun sendBroadcast(view: View){
val intent=Intent()
intent.action = "com.test.kotlin_test.MY_RECEIVER"
intent.setPackage("com.test.kotlin_test")
sendBroadcast(intent)
}
5. Send an orderly broadcast
fun sendOrBroadcast(view: View){
val intent=Intent()
intent.action = "com.test.kotlin_test.MY_RECEIVER"
intent.setPackage("com.test.kotlin_test")
sendOrderedBroadcast(intent,null)
}
To send an ordered broadcast, you only need to use this method :sendOrderedBroadcast, The second parameter is related to permissions , It can be transmitted temporarily null, The receiver with high priority receives the ordered broadcast first , You can call abortBroadcast() This method terminates the broadcast . Other recipients cannot receive this broadcast .
<receiver
android:name=".broadcast.OtherReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="100">
<action android:name="com.test.kotlin_test.MY_RECEIVER"/>
</intent-filter>
</receiver>
stay intent-filter Medium configurable priority This is the priority of the broadcast receiver , The default is 0, The higher the value, the higher the priority , The value range is -1000,1000 Value between .
6. Application of broadcasting , Force logout
Forced exit function , You can use the function of broadcasting to realize , The idea is to send a broadcast when forced exit is needed , After receiving the broadcast, a pop-up window pops up , After the user confirms to exit, kill all Activity And launch the login page .
object ActivityController {
private val activitys=ArrayList<Activity>()
fun addActivity(activity: Activity){
activitys.add(activity)
}
fun removeActivity(activity: Activity){
activitys.remove(activity)
}
fun finishAll(){
for (activity in activitys){
if (!activity.isFinishing){
activity.finish()
}
}
activitys.clear()
}
}
Need to close all Activity, So we need to build a Activity The manager of , This is for management Activity
open class BaseActivity :AppCompatActivity() {
private lateinit var receiver:ForceOfflineReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ActivityController.addActivity(this)
}
override fun onDestroy() {
super.onDestroy()
ActivityController.removeActivity(this)
}
override fun onResume() {
super.onResume()
val intentFilter=IntentFilter()
intentFilter.addAction("com.test.kotlin_test.FORCE_OFFLINE")
receiver=ForceOfflineReceiver()
registerReceiver(receiver,intentFilter)
}
override fun onPause() {
super.onPause()
unregisterReceiver(receiver)
}
inner class ForceOfflineReceiver :BroadcastReceiver(){
override fun onReceive(context: Context, intent: Intent?) {
AlertDialog.Builder(context).apply {
setTitle(" Be careful ")
setMessage(" You are operating to force logout ")
setCancelable(false)
setPositiveButton("ok"){
_,_->
ActivityController.finishAll() // Destroy all Activity
val intent=Intent(context,LoginActivity::class.java)
context.startActivity(intent)
}
show()
}
}
}
Define a baseActivity, Let all others Activity All inherit this , Easy to manage other pages , At the same time, note that the registration and de registration of broadcast recipients are in onResume and onPause In the declaration cycle , In this way, you can register and unregister broadcasts in time , After receiving the broadcast, a pop-up window pops up , After the user clicks OK, first close all Activity Then launch the login page .
In this way, the function of forced exit is realized .
边栏推荐
- Unity skframework framework (XX), VFX lab special effects library
- 屠榜多目标跟踪!BoT-SORT:稳健的关联多行人跟踪
- The second anniversary of the three winged bird: the wings are getting richer and the take-off is just around the corner
- Node. JS accessing PostgreSQL database through ODBC
- Numpy array calculation
- Unity skframework framework (XVI), package manager development kit Manager
- PR usage skills, how to use PR to watermark?
- D为何链接不了dll
- Lucky numbers in the [leetcode daily question] matrix
- Solve "sub number integer", "jump happily", "turn on the light"
猜你喜欢
![[indomitable medal activity] life goes on and writing goes on](/img/c1/54e3f1b37db25af3f1998b39da301b.png)
[indomitable medal activity] life goes on and writing goes on

Unity skframework framework (XV), singleton singleton

Solve "sub number integer", "jump happily", "turn on the light"

2022零代码/低代码开发白皮书【伙伴云出品】附下载

SAP MM 因物料有负库存导致MMPV开账期失败问题之对策

Unity SKFramework框架(十三)、Question 问题模块

嵌入式软件开发

leetcode621. task scheduler

题解:《你的飞碟在这儿》、《哥德巴赫猜想》

最近公共祖先LCA的三种求法
随机推荐
屠榜多目标跟踪!BoT-SORT:稳健的关联多行人跟踪
Redis数据库持久化
Jerry's watch modifies the alarm clock [chapter]
Lucky numbers in the [leetcode daily question] matrix
Explanation: here is your UFO, Goldbach conjecture
解答:EasyDSS视频点播时音频是否可以设置为默认开启?
Let juicefs help you with "remote backup"
Solution: Compression Technology (original version and sequel version)
(7) Web security | penetration testing | how does network security determine whether CND exists, and how to bypass CND to find the real IP
Nohup command
机器学习基础(二)——训练集和测试集的划分
Ali on three sides, it's really difficult to successfully get the offer rated P7
Countermeasures for the failure of MMPV billing period caused by negative inventory of materials in SAP mm
科技的成就(二十七)
Unity skframework framework (XIII), question module
不会看器件手册的工程师不是个好厨子
2022零代码/低代码开发白皮书【伙伴云出品】附下载
Web Foundation
Unforgettable Ali, 4 skills, 5 hr additional written tests, it's really difficult and sad to walk
I did it with two lines of code. As a result, my sister had a more ingenious way