当前位置:网站首页>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] using GB2312, the solution to abnormal program after packaging
- JS reverse row query data decryption
- 操作教程:EasyDSS如何将MP4点播文件转化成RTSP视频流?
- 三翼鸟两周年:羽翼渐丰,腾飞指日可待
- What are eNB, EPC and PGW?
- Bridge of undirected graph
- JS reverse massive creative signature
- Unity skframework framework (XV), singleton singleton
- Jerry's watch gets the default ringtone selection list [article]
猜你喜欢

OpenAPI generator: simplify the restful API development process

题解:《压缩技术》(原版、续集版)

Unity skframework framework (XVI), package manager development kit Manager

The second anniversary of the three winged bird: the wings are getting richer and the take-off is just around the corner

Japan bet on national luck: Web3.0, anyway, is not the first time to fail!

Unity SKFramework框架(十八)、RoamCameraController 漫游视角相机控制脚本

What are eNB, EPC and PGW?

Unity SKFramework框架(十二)、Score 计分模块

OpenApi-Generator:简化RESTful API开发流程
![[OpenGL] notes 29. Advanced lighting (specular highlights)](/img/6e/56bc7237f691a4355f0b7627b3003e.png)
[OpenGL] notes 29. Advanced lighting (specular highlights)
随机推荐
Numpy array calculation
Everyone wants to eat a broken buffet. It's almost cold
MySQL: Invalid GIS data provided to function st_ geometryfromtext
Jerry's weather code table [chapter]
Download files and preview pictures
[技术发展-22]:网络与通信技术的应用与发展快速概览-2- 通信技术
Unity skframework framework (XIII), question module
Unity skframework framework (XVIII), roamcameracontroller roaming perspective camera control script
What are eNB, EPC and PGW?
2、 Frame mode MPLS operation
D为何链接不了dll
Node. JS accessing PostgreSQL database through ODBC
Essential for operation and maintenance - Elk log analysis system
Research shows that "congenial" is more likely to become friends
How to get the operating system running PHP- How to get the OS on which PHP is running?
题解:《你的飞碟在这儿》、《哥德巴赫猜想》
Unity skframework framework (XIV), extension extension function
Jerry's watch gets the default ringtone selection list [article]
上海交大教授:何援军——包围盒(包容体/包围盒子)
记忆函数的性能优化