【Android】BroadcastReceiver全局广播和本地广播总结

 TestBroadcastReceiver.kt

package com.example.kotlingradleandroid8_1template.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.widget.Toast

class TestBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {

        if (intent?.action?.equals(ConnectivityManager.CONNECTIVITY_ACTION) == true) {

            val connectivityManager =
                context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkCapabilities = connectivityManager.getNetworkCapabilities(
                connectivityManager.activeNetwork
            )

            if (networkCapabilities != null) {
                when {
                    networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                        // Wi-Fi 网络
                        Toast.makeText(context, "Wi-Fi 网络", Toast.LENGTH_SHORT).show()
                    }
                    networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                        // 蜂窝数据网络
                        Toast.makeText(context, "蜂窝数据网络", Toast.LENGTH_SHORT).show()
                    }
                    networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
                        // 以太网网络
                        Toast.makeText(context, "以太网网络", Toast.LENGTH_SHORT).show()
                    }
                    else -> {
                        // 其他网络类型...
                        Toast.makeText(context, "其他网络类型...", Toast.LENGTH_SHORT).show()
                    }
                }
            } else {
                // 当前无活跃网络
                Toast.makeText(context, "当前无活跃网络", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

MainActivity.kt 

package com.example.kotlingradleandroid8_1template

import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.example.kotlingradleandroid8_1template.broadcast.TestBroadcastReceiver

class MainActivity : AppCompatActivity() {
    private lateinit var testBroadcastReceiver: TestBroadcastReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById

你可能感兴趣的:(android)