android - 从任何地方访问上下文?全局背景?

标签 android

我有一个应用程序需要始终访问许多不同类中的上下文,以保存和序列化数据、显示对话框等。

根据 Android 开发者网站上的一篇文章,这会导致内存泄漏: http://developer.android.com/resources/articles/avoiding-memory-leaks.html

访问上下文的一般方法是什么?是否应该创建一个单例类,在应用程序启动后立即保存对上下文的一个引用,或者最好的方法是什么?

例如,现在我的方法看起来像这样

public void saveData(TheCassName classObject, Context context){
//do some stuff that involves context
}

并在我需要的任何地方被调用。

谢谢!

最佳答案

只是要清楚:没有内存泄漏,因为正在保存的上下文是应用程序的一部分,而应用程序是一个进程,只有在应用程序关闭时才会被杀死。

Extend application in your app and then use the application context by making static variable in that.

public class MyApp extends Application {

    private static Context context;

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

    public static Context getAppContext() {
        return MyApp.context;
    }
}

You need to define application also in your manifest too.

<manifest>
  <application android:name="com.abc.MyApp">

  </application>
</manifest>

关于android - 从任何地方访问上下文?全局背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7827971/

相关文章:

android - 插入电源时如何使Android设备启动?

Android 4.1 - 使用 VideoView 和 MediaController 的 RTSP

Android webview 页面不可用

android - 如何使用 Volley 解析 JSON

android - React Native PDF 签名

android - 是否可以使用彩信在 Android 中播放互联网广播?

android - EventBus 不在主线程

没有 SQL 的 Android 内容提供程序

android - 如何在 Android 2.3.5 中测试我的应用程序?

android - 如何在多行 TextView 的最后一个字之后添加图像?