《第一行代码: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
火柴就是我3 小时前
flutter 之真手势冲突处理
android·flutter
法的空间3 小时前
Flutter JsonToDart 支持 JsonSchema
android·flutter·ios
循环不息优化不止3 小时前
深入解析安卓 Handle 机制
android
恋猫de小郭3 小时前
Android 将强制应用使用主题图标,你怎么看?
android·前端·flutter
jctech3 小时前
这才是2025年的插件化!ComboLite 2.0:为Compose开发者带来极致“爽”感
android·开源
用户2018792831673 小时前
为何Handler的postDelayed不适合精准定时任务?
android
叽哥4 小时前
Kotlin学习第 8 课:Kotlin 进阶特性:简化代码与提升效率
android·java·kotlin
Cui晨4 小时前
Android RecyclerView展示List<View> Adapter的数据源使用View
android
氦客4 小时前
Android Doze低电耗休眠模式 与 WorkManager
android·suspend·休眠模式·workmanager·doze·低功耗模式·state_doze