2014-01-24 45 views
0

我剛開始學習Android並試圖編寫一個簡單的應用程序。點擊按鈕後,MP開始播放。從不同於MainActivity的類中的線程顯示Toast消息

下面的代碼正常工作 但我不知道如何在media player try-catch語句發生異常時顯示敬酒消息 。

我想讓播放器線程在單獨的類中進行進一步的實驗。

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(); 

    } 
} 
+0

不能顯示來自非UI線程敬酒。使用['Handler'](http://developer.android.com/reference/android/os/Handler.html) –

+0

使用getApplicationContext()而不是上下文 – jyomin

回答

1

您無法直接顯示來自非UI線程的烤麪包。是的,你可以做到這一點,但通過執行runOnUiThread。在不同的線程

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

顯示敬酒消息...

+0

謝謝你帕雷什先生... –

0

使用它在run()方法

Toast.makeText(getApplicationContext(),"toast msg here",Toast.LENGTH_SHORT).show(); 
相關問題