Android四大组件之broadcast广播详解

  package com.zhiyiyi.listviewdemo

  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.Toast

  import androidx.recyclerview.widget.LinearLayoutManager

  import androidx.recyclerview.widget.RecyclerView

  import androidx.recyclerview.widget.StaggeredGridLayoutManager

  import com.zhiyiyi.listviewdemo.R

  import com.zhiyiyi.listviewdemo.RecyclerAdapter

  import kotlinx.android.synthetic.main.activity_main.*

  import java.util.*

  import kotlin.collections.ArrayList

  class MainActivity : AppCompatActivity() {

  // 延迟初始化监听器

  lateinit var timeChangeReceiver: TimeChangeReceiver

  override fun onCreate(savedInstanceState: Bundle?) {

  super.onCreate(savedInstanceState)

  setContentView(R.layout.activity_main)

  // 设置过滤器

  val intentFilter = IntentFilter()

  // 过滤的广播类型为TIME_TICK

  intentFilter.addAction("android.intent.action.TIME_TICK")

  // 实例化监听器

  timeChangeReceiver = TimeChangeReceiver()

  // 注册广播监听器

  registerReceiver(timeChangeReceiver, intentFilter)

  }

  override fun onDestroy() {

  super.onDestroy()

  // 销毁activity的时候别忘了注销广播监听器

  unregisterReceiver(timeChangeReceiver)

  }

  // 使用内部类动态注册广播监听器

  inner class TimeChangeReceiver : BroadcastReceiver() {

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

  Toast.makeText(context, "time changed", Toast.LENGTH_SHORT).show()

  }

  }

  }