在上下文无效后使用通过android Context获得的对象

时间:2011-08-04 09:14:26

标签: android garbage-collection thread-safety android-context

我现在已经和android一起工作了一段时间,对平台感觉很舒服,但是我对上下文对象的生命周期感到困惑。查看层次结构,很容易看出Activity和Service都扩展了Context,虽然这很方便,但却很有用。我已经避免了需要共享资源的辅助类有一个静态字段来保存上下文(因为几乎所有资源都是通过与Context对象的一些交互),所以当一个活动被销毁时,GC可以自由地释放它任何时候,但我想知道从上下文中获取的资源。

例如,如果我有一个静态字段,它将一个文件保存在一个类中。然后让这个类的构造函数获取当前上下文,并通过传入的Context分配File a File资源,对我的第二个类中的Context不做任何其他操作,我是否仍然以某种方式继续使用Context?

class testClass{
    private static File someFile;
    public testClass(Context context){
        synchronized(testClass.class){
            if(someFile!=null){
                //even though I am holding a File, or a SharedPreference Object generated from this context, am I correctly preventing this utility class from holding the Activity object in memory for no reason?
                someFile = context.openFileOutput("Some_File.txt", Context.MODE_PRIVATE);
            }
        }
    }
}

我刚刚读过关于Context.getApplicationContext()(可悲的不是静态的)。它说它返回一个相对于进程而不是活动的上下文,所以如果我需要保持一个上下文,请使用那个。但上述问题仍然存在。

1 个答案:

答案 0 :(得分:2)

我记得我问了这个问题并且认为我会回答它。

虽然可能有更多种类的上下文,但开发人员使用的主要内容是活动上下文和应用程序上下文(以及服务上下文等其他内容)。使用活动创建和销毁Activity上下文,因此使用存储在活动创建和销毁之间的常量引用不是一个好主意。 Application Context没有Activity Context所具有的一些东西,但是你想要静态上下文引用的所有东西都在那里(文件IO,首选项......)。应用程序上下文也是通过应用程序创建和销毁的,因此您可以保证只要您的应用程序代码正在运行,上下文就是有效的。

因此,应用程序上下文应该用于工作线程之类的东西,这些工作线程可能需要一个到上下文的常量访问点,但不需要访问活动。我学会这样做的最好方法是扩展android Application类。在内存中创建应用程序时会创建此类,并且只要调用Application onCreate方法,Application Context就会生效。这意味着您可以在自定义应用程序类中创建一个静态函数,以便访问上下文。

public class CustomApplication extends Application {
private static Context context;

public void onCreate() {
    super.onCreate();
    context = getApplicationContext();
}

public Context getAppContext() {
    return context;
};
}

你需要做的唯一其他事情就是对你的清单文件进行修改,以便android知道使用你的应用程序类而不是默认文件。

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name=".CustomApplication" >