简体   繁体   中英

How do I do a BaseActivity or something similar so that I only have to do an Internet Connection BroadcastReceiver once?

I currently have my own broadcast receiver in every activity, but with 10 or more activities this is really unpleasant. Now my question is:

How do I do a BaseActivity or something similar so that I only have to do an Internet Connection BroadcastReceiver once? Or am I completely wrong?

You can create an Abstract Class extending from AppCompatActivity, And all your activities will extend from this base class from now on and there you can register/unregister your receiver in proper lifecycle methods, and you can also create an abstract method and forcing other activities to implement that.

In every activity what you wanna do when you get notified will on that abstract method implementation, and the you call that from baseActivity when you receive the broadcast.

Or if you are using Kotlin the you can also use DSL to that, that would be kind of cool.

you can create a function variable in Baseactivity, and a method to pass the function -

val onInternetConnect : (() -> Unit)? = null

onConnect(block : (() -> Unit)){

onInternetConnect = block

}

the on from each Activity onCreate you can that like this -

onConnect {
Your Code Goes Here
}

And from BaseActivity, Invoke it in when you receive the broadcast -

onInternetConnect?.invoke()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM