Android本地广播工具类

LocalBroadcastUtil
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.localbroadcastmanager.content.LocalBroadcastManager

/**
 * 本地广播工具类
 */
object LocalBroadcastUtil {

    private var manager: LocalBroadcastManager? = null

    fun receive(context: Context, callback: ((bundle: Bundle?) -> Unit)?) {
        manager = LocalBroadcastManager.getInstance(context)
        val intentFilter = IntentFilter()
        intentFilter.addAction("local_broad_cast")

        val receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                callback?.invoke(intent.getBundleExtra("data"))
                manager?.unregisterReceiver(this)
            }
        }
        manager?.registerReceiver(receiver, intentFilter)
    }

    fun send(bundle: Bundle? = null) {
        manager?.let {
            val intent = Intent()
            intent.setAction("local_broad_cast")
            intent.putExtra("data", bundle)
            it.sendBroadcast(intent)
        }
    }

}

 

posted @ 2024-11-01 13:59  野生野鸡码农  阅读(6)  评论(0编辑  收藏  举报