显示来自与MainActivity不同的类中的线程的Toast消息

时间:2014-01-24 09:43:19

标签: android multithreading android-toast

我刚刚开始学习Android并尝试编写一个简单的应用程序。点击按钮后,MP开始播放。

以下代码运行正常  但我无法弄清楚如何显示祝酒词 当媒体播放器尝试捕获语句发生异常时。

我想将播放器线程保持在单独的类中以进行进一步的实验。

public class MainActivity extends Activity {
static String url="http://stream001.radio.hu:8080/mr3.mp3";
static Activity context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
        context=this;
        //set button listener
        Button btn=(Button) findViewById(R.id.button1);
        btn.setOnClickListener(
            new OnClickListener(){
                public void onClick(View v){
                    myMediaPlayerClass.startMediaPlayer(url, context);
                }
            }
        );
    }
  ...   
}


public class myMediaPlayerClass {
    static MediaPlayer mp=new MediaPlayer();

    public static void startMediaPlayer(  final String myUrl, final Activity myContext){

        new Thread(new Runnable(){

            public void run(){
            string url=myUrl;
                Context context=myContext;
            //***********************************************
            // trying to Toast from here results in crash
        //Toast.makeText(context, "Thread running", Toast.LENGTH_LONG).show();
                //*********************************************************************
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

            try {mp.setDataSource(url);} 
            catch (IllegalArgumentException e) {}
            catch (SecurityException e) {} 
            catch (IllegalStateException e) {} 
            catch (IOException e) {}

            mp.setOnPreparedListener(new OnPreparedListener() {
            @Override
                public void onPrepared(MediaPlayer paramMediaPlayer){}
                    });

            mp.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {}
                });

        try {mp.prepare();} 
        catch (IllegalStateException e) {} 
        catch (IOException e) {}

        mp.setVolume(1, 1);
        mp.start();
            }   
    }).start();

    }
 }

2 个答案:

答案 0 :(得分:1)

您无法直接从非UI线程显示吐司。是的,你可以通过实施runOnUiThread来实现。

runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(getApplicationContext(), "Your message", Toast.LENGTH_LONG).show();
                                }
                            });

在不同的线程上显示Toast消息......

答案 1 :(得分:0)

在run()方法中使用它

Toast.makeText(getApplicationContext(),"toast msg here",Toast.LENGTH_SHORT).show();