为什么我不能在这里使用getBaseContext()?

时间:2011-12-21 18:05:29

标签: android android-context

我想尝试使用以下代码从我的设置中获取一些值:

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.content.*;
public class TCPdumpHandler {

    public void getPreference() {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        Boolean checkboxPreference = prefs.getBoolean("checkboxPref", true);
    }
}

但错误是:The method getBaseContext() is undefined for the type TCPdumpHandler

你能告诉我原因吗?

2 个答案:

答案 0 :(得分:5)

因为TCPdumphandler未从“活动”扩展。 getBaseContext()是该类的一种方法(从技术上讲,是ContextWrapper类的方法)。您需要将上下文传递给TCPdumphandler的构造函数。

答案 1 :(得分:0)

getContext()方法只能从扩展了活动和服务的类中调用(但是,我不确定,应用程序)。要在其他类中使用上下文,您应该将上下文作为参数传递。