简体   繁体   中英

Access application context in companion object in kotlin

How can we access application context inside companion object in Android kotlin? I have a companion object inside an abstract class and I want to access context to read Shared Preferences, but I'm not able to get the context.

UPDATE: I'm working with this stuff in an Android library and also the class that I'm working in is abstract

please see this go to link

class MainApplication : Application() {

    init {
        instance = this
    }

    companion object {
        private var instance: MainApplication? = null

        fun applicationContext() : Context {
            return instance!!.applicationContext
        }
    }

    override fun onCreate() {
        super.onCreate()
        // initialize for any

        // Use ApplicationContext.
        // example: SharedPreferences etc...
        val context: Context = MainApplication.applicationContext()
    }
}

Extends Application class like this

import android.app.Application
import android.content.Context

class MyApplication : Application() {

override fun onCreate() {
super.onCreate()
MyApplication.appContext = applicationContext
 }

companion object {

lateinit  var appContext: Context

}
}

then get context like this

     val context = MyApplication.appContext

Actually I'm working inside an Android library and the class is abstract, so can't go with the already suggested solutions. However, I found way to do that.

  1. Creat a lateinit Context field inside companion object.
abstract class MyClass {

    companion object {

        private lateinit var context: Context

        fun setContext(con: Context) {
            context=con
        }
    }
}
  1. And then set it after the app has started
public class WelcomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        MyClass.Companion.setContext(this);
    }
}

There is a super cool article from the guys from Firebase explaining how their SDK gets hold of the context .

Basically my contentprovider looks like this:

/**
 * This content provider is only responsible to inject the application context into the common module.
 */
class ContextProvider : ContentProvider() {

    companion object {
        private val TAG = ContextProvider::class.java.simpleName
    }

    override fun onCreate(): Boolean {
        context?.let {
            Common.setContext(it)
            return true
        }
        Logger.e(TAG, "Context injection to common failed. Context is null! Check ContextProvider registration in the Manifest!")
        return false
    }

    override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null

    override fun getType(uri: Uri): String? = null

    override fun insert(uri: Uri, values: ContentValues?): Uri? = null

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0

    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0
}

And the Common object, which I treat like an sibling of any Application class looks like this:

/**
 * Partially working like an Application class by holding the appContext which makes it accessible inside this module.
 */
@SuppressLint("StaticFieldLeak")
object Common {
    /**
     * App appContext
     */
    @Volatile
    lateinit var appContext: Context

    var isStoreVersion: Boolean = false

    fun setContext(context: Context) {
        appContext = context
    }
}

As you can see I also enriched the Common object with a flag to store if the current build is a store version or not. Mainly because the BuildConfig of the app module is also not available in a module or library.

Don't forget to add the ContentProvider to the AndroidManifest of your library within the <application> tag

<provider android:name=".util.ContextProvider"
          android:authorities="${applicationId}.common.util.contextprovider"
          android:exported="false" />
class Test { 

    companion object {
        lateinit var sharedPreferences: SharedPreferences

        fun init(context: Context) {
            // to prevent multiple initialization
            if (!Companion::sharedPreferences.isInitialized) {
                sharedPreferences = context.getSharedPreferences("preference_name", Context.MODE_PRIVATE)   
            }
        }
    }
}

You can save the instance directly inside a companion object and accessing it outside without problems, I think this approach is the simplest.

IMPORTANT : change the visibility of the instance property to private to ensure no one but Application has write access.

class App : Application() {

    override fun onCreate() {
        super.onCreate()
        instance = this
    }

    companion object {
        lateinit var instance: App
            private set
    }
}

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