Context inside a Runnable

后端 未结 4 837

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 Null         


        
4条回答
  •  后悔当初
    2021-01-17 21:01

    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.

提交回复
热议问题