2011-12-21 58 views
1

我想尝试使用下面的代码从我的设置得到一些价值:为什么我不能在这里使用getBaseContext()?

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

[你不应该使用'getBaseContext()'](http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-如果你不知道你为什么需要这个上下文*(因为这是一个初学者问题,你可能不知道)*。坚持活动的上下文。 – 2011-12-21 18:17:48

回答

5

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

+0

谢谢!我现在明白了 – 2011-12-21 18:20:45

0

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

相关问题