是否有一种方法来获得静态方法内的当前上下文实例?

我正在寻找这种方式,因为我讨厌保存'Context'实例每次它改变。


当前回答

在Kotlin中,将Context/App Context放在同伴对象中仍然会产生警告,不要将Android Context类放在静态字段中;这是一个内存泄漏(也破坏了即时运行)

或者如果你使用这样的东西:

    companion object {
        lateinit var instance: MyApp
    }

这只是愚弄lint不发现内存泄漏,App实例仍然可以产生内存泄漏,因为Application类及其后代是一个Context。

或者,你可以使用功能界面或功能属性来帮助你获得应用上下文。

简单地创建一个对象类:

object CoreHelper {
    lateinit var contextGetter: () -> Context
}

或者你可以使用nullable type更安全:

object CoreHelper {
    var contextGetter: (() -> Context)? = null
}

在你的App类中添加这一行:


class MyApp: Application() {

    override fun onCreate() {
        super.onCreate()
        CoreHelper.contextGetter = {
            this
        }
    }
}

在你的manifest中声明应用名。MyApp


    <application
            android:name=".MyApp"

当你想获取上下文时,只需调用:

CoreHelper.contextGetter()

// or if you use the nullable version
CoreHelper.contextGetter?.invoke()

希望能有所帮助。

其他回答

如果你愿意使用RoboGuice,你可以将上下文注入到任何你想要的类中。下面是如何使用RoboGuice 2.0(在撰写本文时是beta 4)的一个小示例

import android.content.Context;
import android.os.Build;
import roboguice.inject.ContextSingleton;

import javax.inject.Inject;

@ContextSingleton
public class DataManager {
    @Inject
    public DataManager(Context context) {
            Properties properties = new Properties();
            properties.load(context.getResources().getAssets().open("data.properties"));
        } catch (IOException e) {
        }
    }
}

另一种获得上下文而不子类化Application对象和不使用隐藏类的方法是使用ContentProvider。一旦onCreate方法被调用,上下文应该是可用的。您可以在Kotlin中执行类似的操作

class ContextContentProvider : ContentProvider() {
    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?) = 0

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

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

    override fun onCreate(): Boolean {
        applicationContext = context
        return true
    }

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

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

    companion object {
        private var applicationContext: Context? = null

        @JvmStatic
        fun applicationContext() = applicationContext
    }
}

在任何需要上下文的地方,都可以调用ContextContentProvider.applicationContext()方法

如果你已经有了另一个内容提供程序,并且没有导出该内容提供程序,请确保在AndroidManifest.xml中使用不同的权限。

<application>
    <provider
        android:name=".ContextContentProvider"
        android:authorities="${applicationId}.ContextContentProvider"
        android:enabled="true"
        android:exported="false" />
</application>

这取决于您使用上下文的目的。我认为这种方法至少有一个缺点:

如果您正在尝试使用AlertDialog创建AlertDialog。Builder,应用程序上下文将无法工作。我相信你需要了解当前活动的背景……

科特林

open class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        mInstance = this
    }

    companion object {
        lateinit var mInstance: MyApp
        fun getContext(): Context? {
            return mInstance.applicationContext
        }
    }
}

然后得到Context

MyApp.mInstance

or

MyApp.getContext()

根据这个源代码,您可以通过扩展ContextWrapper来获得自己的Context

public class SomeClass extends ContextWrapper {

    public SomeClass(Context base) {
      super(base);
    }

    public void someMethod() {
        // notice how I can use "this" for Context
        // this works because this class has it's own Context just like an Activity or Service
        startActivity(this, SomeRealActivity.class);

        //would require context too
        File cacheDir = getCacheDir();
    }
}

JavaDoc for ContextWrapper

Context的代理实现,简单地将其所有调用委托给另一个Context。可以通过子类化来修改行为而不改变原始上下文。