从非活动单例类中获取应用程序上下文 [英] Get application context from non activity singleton class

查看:164
本文介绍了从非活动单例类中获取应用程序上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的android项目中,我有ImageAdapter类,我在其中传递app context以满足其他需求。

In my android project, I have ImageAdapter class in which I pass app context for some further needs.

public class ImageAdapter extends BaseAdapter {
    private Context c;

    public ImageAdapter(Context c) {
            this.c = c;
    }
    ...
}

问题在于我想让ImageAdapter成为一个单例,以便从我的所有活动中轻松访问这个类的实例。但是我不知道如何将getApplicationContext()方法中的app context从我的一个活动传递给ImageAdapter。那么有什么魔力可以做到这一点吗?

The problem is that I wanna make ImageAdapter as a singleton to have an easy access to the instance of this class from all of my activities. But I have no idea how to pass app context from getApplicationContext() method from one of my activities to ImageAdapter. So is there any "magic" to do that as follows?

public class ImageAdapter extends BaseAdapter {

    private Context c;

    private static class Holder {
            public static final ImageAdapter IA = new ImageAdapter();
    }

    private ImageAdapter() {
            this.c = /* some magic here */.getApplicationContext();
    }

    public static ImageAdapter getInstance() {
            return Holder.IA;
    }
    ...
}

也许你有一些为我的任何活动分享ImageAdapter的其他想法。
我是android的新手,我对在活动中传递数据的方式有点困惑。

Maybe you have some other ideas for sharing ImageAdapter for any of my activities. I'm a newbie to android and I'm a little bit confused with the ways of passing data among activities.

我将不胜感激任何帮助。

I will be grateful for any help.

推荐答案

更新:06年3月6日

使用 MyApplication 实例而不是 Context 实例。 Application instance是一个单例上下文实例。

Use MyApplication instance instead of Context instance. Application instance is a singleton context instance itself.

public class MyApplication extends Application {

    private static MyApplication mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public static MyApplication getContext() {
        return mContext;
    }
}

上一个答案

您可以像这样获得应用程序上下文:

You can get the the application context like this:

public class MyApplication extends Application {

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getContext() {
        return mContext;
    }
}

然后,您可以从方法中调用应用程序上下文 MyApplication.getContext()

Then, you can call the application context from the method MyApplication.getContext()

不要忘记在清单文件中声明应用程序:

Don't forget to declare the application in your manifest file:

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

这篇关于从非活动单例类中获取应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆