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

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

问题描述

在我的 android 项目中,我有 ImageAdapter 类,我在其中传递应用程序上下文以满足一些进一步的需求.

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() 方法从我的一项活动传递到 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 的新手,我对在 Activity 之间传递数据的方式有点困惑.

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.

推荐答案

更新:18 年 3 月 6 日

使用 MyApplication 实例而不是 Context 实例.Application 实例本身就是一个单例上下文实例.

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

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

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天全站免登陆