当我按下屏幕上的图像时,它调用powerButton.OnClickListener()就像它应该的那样,并且在几秒钟的缓冲之后,流播放得很好。然而,人们希望显示一个简短的吐司弹出窗口以通知用户“无线电流连接,请等待......”
这就是问题所在,无论我尝试过什么,我在哪里设置了创建Toast弹出窗口的行,它在进入缓冲之前根本不会显示。
我们将非常感谢任何帮助,并且我已添加了大部分代码,并在必要时提供更多代码。
// run on powerButton click
powerButton.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
// check if the player is started or stopped
if (isPlaying) // player is streaming
{
// stop the stream and set isPlaying to false
mediaPlayer.stop();
// release the media player
releaseMediaPlayer();
// update notification
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
// set power button to "powered off" image
powerButton.setImageResource(R.drawable.power_off);
}
else // player not streaming
{
// notify the user that the stream is loading
final Toast streamLoading = toast.makeText(getBaseContext(), "Radio Stream Connecting, Please Wait...", Toast.LENGTH_SHORT);
streamLoading.show();
// try catch block to attempt connecting to radioUrl
try
{
// create new instance of media player
mediaPlayer = new MediaPlayer();
// set media player to handle audio streams
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// connect to radio stream and fill buffer
mediaPlayer.setDataSource(radioUrl);
mediaPlayer.prepare(); // might take long depending on buffering speed
// start the media player and set isPlaying to true
mediaPlayer.start();
isPlaying = true;
// update notification, clear stream message
createNotification();
// set power button to "powered on" image
powerButton.setImageResource(R.drawable.power_on);
}
catch (IllegalArgumentException e) // cannot connect to stream
{
// clear streaming text and notify user of failure
final Toast streamError1 = Toast.makeText(MainMenu.this, "Failed to load: Unable to connect to stream!", Toast.LENGTH_SHORT);
streamError1.show();
// release the media player and display error
releaseMediaPlayer();
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
e.printStackTrace();
}
catch (IllegalStateException e) // stream cannot play audio
{
// clear streaming text and notify user of failure
final Toast streamError2 = Toast.makeText(getBaseContext(), "Failed to load: cannot play stream!", Toast.LENGTH_SHORT);
streamError2.show();
// release the media player and display error
releaseMediaPlayer();
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
e.printStackTrace();
}
catch (IOException e) // general connection issue
{
// clear streaming text and notify user of failure
final Toast streamError3 = Toast.makeText(getBaseContext(), "Failed to Load: Connection issue!", Toast.LENGTH_SHORT);
streamError3.show();
// release the media player and display error
releaseMediaPlayer();
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
e.printStackTrace();
}
}
}
});
答案 0 :(得分:2)
那是因为在你从onClick返回之前,toast不会显示,因为那是UI线程。我在缓冲开始之后才会这样做。我想要获得你想要的效果,你检查AsynchTask在后台线程中进行缓冲并立即返回onClick。
事实上你正在这样做的方式,如果缓冲时间过长你的应用程序将被标记为没有响应的android。
答案 1 :(得分:0)
尝试使用AsyncTask,其中AsyncTask做的第一件事就是在进入缓冲过程之前显示吐司。