我建立了应用程序来播放来自互联网的音频,我使用服务在后台播放音频,问题是如何在媒体播放器准备服务(背景)时使用我的代码来显示loding对话框。
package com.uqifm.onlineradio;
.......
public class MainActivity extends AppCompatActivity {
Button b_play;
Boolean started = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_play = (Button) findViewById(R.id.b_play);
b_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(started){
started = false;
stopService(new Intent(MainActivity.this,MyService.class));
b_play.setText("PLAY");
}else{
started = true;
startService(new Intent(MainActivity.this,MyService.class));
b_play.setText("STOP");
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
stopService(new Intent(MainActivity.this,MyService.class));
}
}
package com.uqifm.onlineradio;
....................
public class MyService extends Service {
MediaPlayer mediaPlayer;
String stream = "http://xxxxx:36365";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(stream);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
mediaPlayer.release();
}
}
答案 0 :(得分:1)
注册广播,在开始服务之前启动404
。然后等待广播。广播后,隐藏对话框。请参阅此主题中的示例。 Send data from Service back to my activity
答案 1 :(得分:0)
将ProgressDialog放在xml中,并根据您的要求设置可见性。使用界面与服务进行通信。
答案 2 :(得分:0)
您可以使用Broadcast
或尝试EventBus
,这样更容易。您可以使用EventBus
在服务中发布活动,并在MainActivity
中接收广播并更新进度对话框。
Please follow the link.
答案 3 :(得分:0)
也许是这样的:
fun playAudio(audioUrl: String){
showProgressBar()
var mediaPlayer: MediaPlayer? = MediaPlayer().apply {
setAudioStreamType(AudioManager.STREAM_MUSIC)
setDataSource(audioUrl)
prepareAsync() // might take long! (for buffering, etc)
}
mediaPlayer?.setOnPreparedListener {
hideProgressBar()
it.start()
}
mediaPlayer?.setOnCompletionListener {
mediaPlayer.release()
}
}