该问题的解决方法是在后台服务中播放音频。以下是实现此方法的示例代码:
首先,创建一个Service类:
public class AudioService extends Service implements MediaPlayer.OnPreparedListener {
private static final String TAG = "AudioService";
private MediaPlayer mediaPlayer;
private String audioUrl;
private boolean isPlaying;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
audioUrl = intent.getStringExtra("url");
if (audioUrl != null && !audioUrl.isEmpty()) {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
}
try {
mediaPlayer.setDataSource(audioUrl);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
mediaPlayer.release();
mediaPlayer = null;
super.onDestroy();
}
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
isPlaying = true;
}
public boolean isPlaying() {
return isPlaying;
}
}
然后在Activity中启动后台Service:
private AudioService audioService; private ServiceConnection serviceConnection;
private void startAudioService(String url) { Intent intent = new Intent(this, AudioService.class); intent.putExtra("url", url); startService(intent);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
AudioService.LocalBinder binder = (AudioService.LocalBinder) iBinder;
audioService = binder.getService();
Log.d(TAG, "onServiceConnected: ");
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
audioService = null;
Log.d(TAG, "onServiceDisconnected: ");
}
};
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
}
最后,当应用关闭时,调用以下