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) } } }