2013-07-01 27 views
0

在Eclipse的Java開發Android ...的Android getBaseContext getApplicationContext不工作

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 

正如你可以看到我不能讓應用程序或在所有的基本上下文。嘗試獲取沒有它們的文件dir不起作用。我怎樣才能訪問我的文件目錄?

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

任何機會,你可以發佈您的代碼,所以我們得到你_where_的想法調用這些方法? IIRC'Contexts'應該保持爲null,直到你的Activity的超類「onCreate()'被調用。此外,您應該發佈已拋出的異常(帶有完整堆棧跟蹤)。 –

+0

換句話說,你在哪裏打電話? – LuckyMe

+0

您是否通過調用其構造函數來啓動該活動? –

回答

0

您可能會自行實例化活動或服務或BroadcastReceiver。如果是這種情況,請了解這些是Android可管理的對象,除了單元測試外,您不能實例化它們。 Android系統將負責根據提供的意圖來實例化它們。所以不要稱他們的構造函數,它可能似乎「工作」,但它會顯示像你遇到的這些怪異的副作用。

0

applicationContext,系統服務全部在onCreate中的setContentView之後初始化。它不會像java對象一樣工作,因爲Android將Activity定義爲構建塊,就像java定義的public static void main一樣。這裏偏離基礎的選擇較少。

您需要啓動背景Service並使用其上下文來完成您所需的一切。這樣你就不會有前端用戶界面,你仍然可以在後臺完成所有你需要的功能。

0

好吧,我想出了這一個。我必須這樣做。

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

其中「mHome」是我主要的總體應用活動的句柄(或ID或上下文或任何你喜歡稱之爲的)。即它是傳遞給此公共類的構造函數的參數。即如果這個類被稱爲PlayMyAudio,它在文件PlayMyAudio.java中,它不是我的應用程序的主要活動。然後「mHome」是遞交到我的函數參數

公共類PlayMyAudio延伸活動{

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

}

相關問題