Context inside a Runnable

2019-02-22 05:05发布

I try to play a sound from R.raw. inside a Thread/Runnable But I can't get this to work.

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  
    }  
  }

How can I get the real Context inside the run method? It is null no matter what I try. Or is there a better way to do this?

4条回答
贼婆χ
2楼-- · 2019-02-22 05:21

You should use getBaseContext. Instead, if this runnable is within an activity, you should store the context in a class variable like this:

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  
            }  
        }
    }
}

Also you shouldn't have an infinite loop like that playing a sound over and over - there should be a sleep in there in order to prevent the sound from playing over and over in a small amount of time and overlapping the same sounds with each other.

查看更多
我只想做你的唯一
3楼-- · 2019-02-22 05:22

You need to declare a Handler object in your UI thread.

Then in your Thread use

YourHandler.post(new Runnable() {
    public void run() {
        //do something to the UI (i.e. play something)
    }});
查看更多
祖国的老花朵
4楼-- · 2019-02-22 05:35

You should also be able to get the this reference from the outer class by using MainActivity.this.

查看更多
疯言疯语
5楼-- · 2019-02-22 05:40

I guess you need to create a Thread and call Thread.start().

查看更多
登录 后发表回答