Runnable中的上下文

时间:2010-10-06 17:46:04

标签: android multithreading media-player runnable android-context

我尝试播放R.raw的声音。在Thread / Runnable中 但是我无法让它发挥作用。

new Runnable(){ 
  public void run() {  

    //this is giving me a NullPointerException, because getBaseContext is null  
    MediaPlayer mp = MediaPlayer.create( getBaseContext(), R.raw.soundfile);  

    while (true) {  
      if (something)  
          play something  
    }  
  }

如何在run方法中获得真正的Context?无论我尝试什么,它都是null。或者有更好的方法吗?

4 个答案:

答案 0 :(得分:23)

您还应该能够使用MainActivity.this从外层获取此引用。

答案 1 :(得分:13)

您应该使用getBaseContext。相反,如果此runnable在一个活动中,您应该将上下文存储在类变量中,如下所示:

public class MainActivity extends Activity {
    private Context context;

    public void onCreate( Bundle icicle ) {
        context = this;


        // More Code
    }

    // More code

    new Runnable(){ 
        public void run() {  
            MediaPlayer mp = MediaPlayer.create(context, R.raw.soundfile);  

            while (true) {  
                if (something)  
                    play something  
            }  
        }
    }
}

此外,你不应该像一遍又一遍地播放声音那样有一个无限循环 - 那里应该有一个睡眠,以防止声音在很短的时间内反复播放并重叠相同的声音彼此。

答案 2 :(得分:0)

我猜你需要创建一个Thread并调用Thread.start()。

答案 3 :(得分:0)

您需要在UI线程中声明一个Handler对象。

然后在你的线程中使用

YourHandler.post(new Runnable() {
    public void run() {
        //do something to the UI (i.e. play something)
    }});
相关问题