In everyday Android development, we often write some SDKS for others to call or call ourselves. Usually these SDKS involve initialization, although we usually let the caller call the initialization process. But today we will introduce a method that does not require the caller to call the SDK initialization. We will do the initialization ourselves. Here’s how
Create a Library
First we create a simple library. The function of this library is very simple:
- We need to pass in the context
- Provides a function to determine whether it has been initialized
class LibraryClient(val context: Context) {
var isInitialized = false
init {
isInitialized = true
}
fun hasInitialized(): Boolean {
returncontext ! = null && isInitialized } }Copy the code
class Library {
companion object {
private var client: LibraryClient? = null
@Synchronized
fun init(context: Context) {
if(this.client == null) { client = LibraryClient(context.applicationContext) } } fun isInitialized(): Boolean { client? .let {returnclient!! .hasInitialized() }return false}}}Copy the code
I: ContentProvider
The ContentProvider function is simply called library.init () in onCreate() to initialize the SDK
class InstallProvider: ContentProvider() {
override fun onCreate(): Boolean {
Library.init(context.applicationContext)
return true} override fun query(uri: Uri, projection: Array<String>? , selection: String? , selectionArgs: Array<String>? , sortOrder: String? ) : Cursor? {return null
}
.....
}
Copy the code
<application>
<provider
android:authorities="${applicationId}.library-installer"
android:name=".InstallProvider"
android:exported="false"/>
</application>
Copy the code
validation
So that’s the end of it, let’s verify that it’s really initialized
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
printLibrary()
}
private fun printLibrary() {
logd("library is initialized: ${Library.isInitialized()}")
shortToast("library is initialized: ${Library.isInitialized()}")}}Copy the code
The result shows successful initialization, and that’s the end of it. As to why initialization succeeds, we will explain in the next article!
link