在 Android 中的静态 class 中引用 non-static 方法 - getSharedPref

Referencing a non-static method in a static class in Android - getSharedPref

我有以下代码:

  Context context = Activity.getApplicationContext();
             SharedPreferences settings = context.getSharedPreferences("AutoMsgSharedPrefs", MODE_PRIVATE);

            // Writing data to SharedPreferences
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("key", "some value");
            editor.commit();

我一直在尝试使用 SharedPrefs 来存储 - "Conversation" class 中给出的消息,如示例 - https://developer.android.com/samples/MessagingService/index.html 中所示。但是,如果我尝试在 "Conversation" class 的构造函数中实现它,我得到“无法从静态 class 引用 non-static 方法。那么我该如何解决这个问题?

这里是我按照提示更新的错误截图:

获取上下文无需使用 Activity class。更改此代码

Context context = Activity.getApplicationContext();

Context context = getApplicationContext();

说明:Activityclass没有静态方法getApplicationContext(),因为这个方法是非静态的,所以你需要有一个对象实例。因此,在 Context 实例的 Activity 上调用此方法。

这里

Context context = Activity.getApplicationContext();

此行不是 return 您的应用程序调用 getSharedPreferences 的有效上下文。

要从非 Activity,Service,... classes 调用 getSharedPreferences,您应该需要从应用程序组件传递有效上下文,例如来自 Activity,Service ,..

要在 Conversation 中获得 Context,请使用已在给定示例中创建的 Conversation class 构造函数,您需要再添加一个参数:

Context mContext;
public Conversation(int conversationId, String participantName,
                            List<String> messages,Context mContext) {
            .....
            this.mContext=mContext;
        }

现在使用 mContextConversation 调用 getSharedPreferences 方法 class :

SharedPreferences settings = mContext.getSharedPreferences("AutoMsgSharedPrefs", 
                                                           Context.MODE_PRIVATE);

正如 @ρяσѕρєя K 已经指出的那样,您必须以某种方式授予您的非 Context class 访问您的 Context 实例的权限。例如通过引入一个新参数.

public Conversation(int conversationId, String participantName,
                            List<String> messages, Context context) {
            .....

        }

但请记住:

不鼓励在您的 class 中保存对 Context 等长寿命和重量级组件的引用,因为这 strong reference 将从 垃圾收集 中排除 context,从而导致 内存泄漏

所以而不是存储你的Context你可以用它来初始化你的Conversation对象,让构造函数的范围来照顾丢弃对 Context 的短期引用。 如果你应该多次需要 Context,你可以编写一个方法,将 Context 实例作为参数并调用它来完成脏工作:

public void doStuff(Context context) {
          // do your work here
}