在Kotlin中的伴随对象中访问应用程序上下文

时间:2019-01-07 13:48:18

标签: android kotlin companion-object

我们如何在Android kotlin中访问伴随对象内的应用程序上下文? 我在抽象类中有一个伴随对象,我想访问上下文以读取“共享首选项”,但无法获取上下文。

更新:我正在使用Android库中的这些东西,而且正在使用的类是抽象的

5 个答案:

答案 0 :(得分:1)

请参阅此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()
    }
}

答案 1 :(得分:1)

实际上,我在一个Android库中工作,并且该类是抽象的,因此不能使用已经建议的解决方案。但是,我找到了方法。

  1. 在伴随对象内创建一个lateinit上下文字段。
abstract class MyClass {

    companion object {

        private lateinit var context: Context

        fun setContext(con: Context) {
            context=con
        }
    }
}
  1. 然后在应用启动后进行设置
public class WelcomeActivity extends AppCompatActivity {

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

        MyClass.Companion.setContext(this);
    }
}

答案 2 :(得分:0)

扩展这样的Application类

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

}
}

然后获得这样的上下文

     val context = MyApplication.appContext

答案 3 :(得分:0)

Firebase的家伙们写了一篇很棒的文章,解释了how their SDK gets hold of the context

基本上我的contentprovider看起来像这样:

/**
 * 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
}

Common对象(我将其视为任何Application类的同级对象)如下:

/**
 * 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
    }
}

如您所见,无论当前构建版本是否为商店版本,我还使用要存储的标志丰富了Common对象。主要是因为app模块的BuildConfig在模块或库中也不可用。

别忘了在<application>标签内将ContentProvider添加到您库的AndroidManifest中

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

答案 4 :(得分:0)

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