《第一行代码: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 核心组件深度系列 · 第 2 篇 Service》
android
前行的小黑炭3 小时前
Compose页面切换的几种方式:Navigation、NavigationBar+HorizontalPager,会导致LaunchedEffect执行?
android·kotlin·app
前行的小黑炭3 小时前
Android :Comnpose各种副作用的使用
android·kotlin·app
BD_Marathon17 小时前
【MySQL】函数
android·数据库·mysql
西西学代码17 小时前
安卓开发---耳机的按键设置的UI实例
android·ui
maki0771 天前
虚幻版Pico大空间VR入门教程 05 —— 原点坐标和项目优化技巧整理
android·游戏引擎·vr·虚幻·pico·htc vive·大空间
千里马学框架1 天前
音频焦点学习之AudioFocusRequest.Builder类剖析
android·面试·智能手机·车载系统·音视频·安卓framework开发·audio
fundroid1 天前
掌握 Compose 性能优化三步法
android·android jetpack
TeleostNaCl1 天前
如何在 IDEA 中使用 Proguard 自动混淆 Gradle 编译的Java 项目
android·java·经验分享·kotlin·gradle·intellij-idea
旷野说1 天前
Android Studio Narwhal 3 特性
android·ide·android studio