里面一个Runnable上下文

里面一个Runnable上下文

本文介绍了里面一个Runnable上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从R.ra​​w播放声音。一个线程内/可运行
但我不能得到这个工作。

I try to play a sound from R.raw. inside a Thread/RunnableBut 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
    }
  }

我怎样才能获得的run方法里面的真实语境?这是空不管我试试。还是有更好的方式来做到这一点?

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?

推荐答案

您应该使用getBaseContext。相反,如果这是可运行的一个活动中,您应保存上下文在这样的类变量:

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

此外,你不应该有这样的播放声音一遍又一遍的无限循环 - 应该为了成为一个睡在里面prevent声音在玩一遍又一遍的时间和重叠少量相同的声音相互

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.

这篇关于里面一个Runnable上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:22