我想创建一个包含toggleButton的无线电应用程序,因为在收音机执行之前应始终显示progressBar。
我正在尝试显示ProgressBar,直到doInBackground()完成。我的代码适用于所有Android版本execpt android api 23(android marshmallow 6.0),其中onPostExecute()在doInBackground()之前执行。这是我的代码:
MainActivity :
ToggleButton MusicButton;
MediaPlayer mediaPlayer;
String stream = "RADIO_URL";
boolean prepared = false;
boolean started = false ;
public static final String PREFS_NAME = "MyPrefsFile1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
mediaPlayer.setAudioAttributes(attribs);
}else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
new PlayerTask().execute(stream);
/****/
MusicButton = (ToggleButton) findViewById(R.id.toggleButton);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if ( started && MusicButton.isChecked()) {
started=false;
mediaPlayer.pause();
MusicButton.setChecked(true);
} else {
started=true;
mediaPlayer.start();
MusicButton.setChecked(false);
}
}
});
class PlayerTask extends AsyncTask<String,Void,Boolean> {
ProgressBar radio = (ProgressBar)findViewById(R.id.radioloading);
@Override
protected void onPreExecute() {
super.onPreExecute();
radio.setVisibility(View.VISIBLE);
}
@Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared=true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
radio.setVisibility(View.GONE);
}
}
答案 0 :(得分:1)
我认为这是calssic&#34;使用UI线程来更新UI组件&#34;问题。您的UI组件的可见性根本没有被更改,因为您正在尝试更改另一个线程(AsyncTask的线程)的可见性。请尝试使用AsyncTask的publishProgress(someProgress)
方法并从AsyncTask中的onProgressUpdate(aListener)
方法挂钩并更新那里的UI可见性。
如果这不能解决问题,请告诉我。