《第一行代码:Android》第三版第六章广播机制

本文主要是讲述安卓的广播机制,包括代码和解释。

广播分为两种:标准广播和有序广播。

标准广播:是完全异步的广播,广播发出后所有的广播接收者几乎在同一时刻接收到该广播,也是无法被截断的。

有序广播:是一种同步执行的广播,广播发出后,同一时刻只有一个广播接收者能收到广播,当这个广播接收者的内部逻辑执行完毕后,广播才可以继续传递。本文代码并没有实现有序广播。

BootCompleteReceiver.kt文件主要是实现了一个类BootCompleteReceiver,继承自BroadcastReceiver,重写了onReceive(),实现弹出一个Toast,显示一段文本,代码文件内容如下:

复制代码
package com.example.broadcasttest_emptyviewac

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast

class BootCompleteReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        // This method is called when the BroadcastReceiver is receiving an Intent broadcast.
        //TODO("BootCompleteReceiver.onReceive() is not implemented")
        Toast.makeText(context,"Boot Complete",Toast.LENGTH_LONG).show()
    }
}

MainActivity.kt 文件中实现了对系统时间的变化进行监听,对按钮事件进行响应,这个按钮事件实现了自定义广播功能的实现。代码文件内容如下:

复制代码
package com.example.broadcasttest_emptyviewac

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    lateinit var timeChangeReceiver:TimeChangeReceiver
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val intentFilter= IntentFilter()
        intentFilter.addAction("android.intent.action.TIME_TICK")
        timeChangeReceiver=TimeChangeReceiver()
        registerReceiver(timeChangeReceiver,intentFilter)
        //下面是按钮的事件响应代码
        val button: Button =findViewById(R.id.button)
        button.setOnClickListener{
            val intent=Intent("com.example.broadcasttest_emptyviewac.MY_BROADCAST")
            intent.setPackage(packageName)
            sendBroadcast(intent)
        }


    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(timeChangeReceiver)
    }
    inner class TimeChangeReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            Toast.makeText(context,"Time has changed",Toast.LENGTH_SHORT).show()
        }
    }
}

MyBroadReceiver.kt 文件主要是创建了MyBroadcastReceiver类,在接收事件函数中也是弹出一个Toast文本。

复制代码
package com.example.broadcasttest_emptyviewac

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast

class MyBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        // This method is called when the BroadcastReceiver is receiving an Intent broadcast.
        //TODO("MyBroadcastReceiver.onReceive() is not implemented")
        Toast.makeText(context,"received in MyBroadcastReceiver",Toast.LENGTH_SHORT).show()
    }
}

Manifest.xml文件内容如下:

复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BroadcastTest_EmptyViewAC"
        tools:targetApi="31">
        <receiver
            android:name=".MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.broadcasttest_emptyviewac.MY_BROADCAST" />
            </intent-filter>

        </receiver>
        <receiver
            android:name=".BootCompleteReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

注意看这里面有两个receiver,一个是系统的,一个是自己定义的。

布局文件 activity_main.xml 主要是声明了一个按钮,点击按钮就触发了自定义的广播。文件内容如下:

复制代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SendBroadcast"
        tools:layout_editor_absoluteX="161dp"
        tools:layout_editor_absoluteY="401dp" />

</androidx.constraintlayout.widget.ConstraintLayout>
相关推荐
檀越剑指大厂2 小时前
容器化 Android 开发效率:cpolar 内网穿透服务优化远程协作流程
android
MiyamuraMiyako3 小时前
从 0 到发布:Gradle 插件双平台(MavenCentral + Plugin Portal)发布记录与避坑
android
NRatel4 小时前
Unity 游戏提升 Android TargetVersion 相关记录
android·游戏·unity·提升版本
叽哥6 小时前
Kotlin学习第 1 课:Kotlin 入门准备:搭建学习环境与认知基础
android·java·kotlin
风往哪边走6 小时前
创建自定义语音录制View
android·前端
用户2018792831676 小时前
事件分发之“官僚主义”?或“绕圈”的艺术
android
用户2018792831676 小时前
Android事件分发为何喜欢“兜圈子”?不做个“敞亮人”!
android
Kapaseker8 小时前
你一定会喜欢的 Compose 形变动画
android
QuZhengRong9 小时前
【数据库】Navicat 导入 Excel 数据乱码问题的解决方法
android·数据库·excel
zhangphil10 小时前
Android Coil3视频封面抽取封面帧存Disk缓存,Kotlin(2)
android·kotlin