《第一行代码: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>
相关推荐
一笑的小酒馆20 小时前
Android性能优化之截屏时黑屏卡顿问题
android
懒人村杂货铺1 天前
Android BLE 扫描完整实战
android
TeleostNaCl1 天前
如何安装 Google 通用的驱动以便使用 ADB 和 Fastboot 调试(Bootloader)设备
android·经验分享·adb·android studio·android-studio·android runtime
fatiaozhang95271 天前
中国移动浪潮云电脑CD1000-系统全分区备份包-可瑞芯微工具刷机-可救砖
android·网络·电脑·电视盒子·刷机固件·机顶盒刷机
2501_915918411 天前
iOS 开发全流程实战 基于 uni-app 的 iOS 应用开发、打包、测试与上架流程详解
android·ios·小程序·https·uni-app·iphone·webview
lichong9511 天前
【混合开发】vue+Android、iPhone、鸿蒙、win、macOS、Linux之dist打包发布在Android工程asserts里
android·vue.js·iphone
Android出海1 天前
Android 15重磅升级:16KB内存页机制详解与适配指南
android·人工智能·新媒体运营·产品运营·内容运营
一只修仙的猿1 天前
毕业三年后,我离职了
android·面试
编程乐学1 天前
安卓非原创--基于Android Studio 实现的新闻App
android·ide·android studio·移动端开发·安卓大作业·新闻app
雅雅姐1 天前
Android14 init.rc中on boot阶段操作4
android