Android getBaseContext getApplicationContext不起作用

时间:2013-07-01 23:37:34

标签: android eclipse

在Eclipse Java开发中为Android ...

Context c = getBaseContext();  // returns null
Context c = this.getBaseContext(); // throws an exception.

Context c = getApplicationContext();  // throws an exception
Context c = this.getApplicationContext();  // throws an exception.

File f = getFilesDir(); // throws an exception
File f = this.getFilesDir(); // throws an exception

如您所见,我根本无法获得应用程序或基本上下文。试图获取没有它们的文件目录不起作用。我怎么能访问我的文件目录?

public class SoundHandler extends Activity {
private Button mButtonPlay;
private Button mButtonDone;
// private LinearLayout mOverallView;
private PeekActivity mHome;
private MyButtonListener myButtonListener;
private MediaPlayer mPlayer; 
private File audioFilePath;

public SoundHandler(PeekActivity home) {
    mHome = home;
    myButtonListener = new MyButtonListener();
}

public void onCreate(Bundle savedInstanceState) {        
    super.onCreate(savedInstanceState);
}

public void open() {
    mHome.setContentView(R.layout.sounds);
    mButtonDone = (Button) mHome.findViewById(R.id.soundDone);     
    mButtonDone.setOnClickListener(myButtonListener);
    mButtonPlay = (Button) mHome.findViewById(R.id.playSound);     
    mButtonPlay.setOnClickListener(myButtonListener);
    mPlayer = null;

                // This is what I thought would work, but it does not
    audioFilePath = this.getBaseContext().getFilesDir().getAbsolutePath();  

                // These are my attempts to see what, if anything works and is not null
                // but I've tried all the combinations and permutations above.
    SoundHandler a = this;
    Context b = getBaseContext();
    Context c = getApplicationContext();
    File d = this.getFilesDir();

                // I'm really just trying to get access to an audio file that is included
                // in my build in file /res/raw/my_audio_file.mp3
                // mPlayer = MediaPlayer.create(this, R.raw.my_audio_file); doesn't work either
}

3 个答案:

答案 0 :(得分:0)

您可能需要自己实例化Activity或Service或BroadcastReceiver。如果是这种情况,请知道这些是Android可管理对象,除了单元测试之外,您无法实例化它们。 Android系统将负责根据提供的Intent实例化它们。因此,不要打电话给他们的构造函数,它似乎“工作”,但它会显示像您正在经历的这些奇怪的副作用。

答案 1 :(得分:0)

applicationContext,系统服务都是在onCreate中的setContentView之后初始化的。它不像java对象那样工作,因为Android将Activity定义为构建块,就像java定义public static void main一样。这里偏离基础知识的选择较少。

您需要启动后台Service并使用其上下文执行您需要的所有操作。这样你就没有前端用户界面,你仍然可以在后台完成所需的一切。

答案 2 :(得分:0)

好吧,我想出了这个。我不得不这样做。

audioFilePath = mHome.getBaseContext()。getFilesDir()。getAbsolutePath();

其中“mHome”是我的主要整体App活动的句柄(或id或上下文或任何你喜欢称之为的)。即它是传递给此公共类的构造函数的参数。即如果这个类被称为PlayMyAudio并且它在文件PlayMyAudio.java中并且它不是我的应用程序的主要活动。然后“mHome”是交给我的函数的参数

公共类PlayMyAudio扩展了活动{

   public PlayMyAudio(AppNameActvity home) {
       mHome = home;
       audioFilePath = mHome.getBaseContext().getFilesDir().getAbsolutePath();  
   }

}