我还是Android的新手,但我在网上开发了一个无线电应用程序的教程,现在这是我遇到的问题,我希望这个收音机继续播放,以便app用户可以继续使用应用程序或其他应用程序而收音机在后台播放。当用户离开流媒体页面时,收音机停止播放。
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
player.start();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(" radio URL");
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
player.prepareAsync();
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(true);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.pause();
buttonStopPlay.setEnabled(false);
buttonPlay.setEnabled(true);
}
}
答案 0 :(得分:0)
参考此link
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
@Override
public void onLowMemory() {
}
}