phone 进入睡眠状态后,我的 MediaPlayer 停止播放约 20 秒
My MediaPlayer stops playing about 20 seconds after phone goes to sleep
我的 MediaPlayer
在 phone 大约 20 到 30 秒后进入睡眠状态后停止播放。我失败的尝试在下面提前致谢。
MediaPlayer mediaPlayer = new MediaPlayer();
SeekBar seekBar;
boolean wasPlaying = false;
ImageButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mediaplayer);
fab = findViewById(R.id.imageButton);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
playSong();
}
});
final TextView seekBarHint = findViewById(R.id.textView);
seekBar = findViewById(R.id.seekbar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekBarHint.setVisibility(View.VISIBLE);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
seekBarHint.setVisibility(View.VISIBLE);
int x = (int) Math.ceil(progress / 1000f);
if (x < 10)
seekBarHint.setText("0:0" + x);
else
seekBarHint.setText("0:" + x);
double percent = progress / (double) seekBar.getMax();
int offset = seekBar.getThumbOffset();
int seekWidth = seekBar.getWidth();
int val = (int) Math.round(percent * (seekWidth - 2 * offset));
int labelWidth = seekBarHint.getWidth();
seekBarHint.setX(offset + seekBar.getX() + val
- Math.round(percent * offset)
- Math.round(percent * labelWidth / 2));
if (progress > 0 && mediaPlayer != null && !mediaPlayer.isPlaying()) {
clearMediaPlayer();
fab.setImageDrawable(ContextCompat.getDrawable(MediaPlayerActivity.this, android.R.drawable.ic_media_play));
MediaPlayerActivity.this.seekBar.setProgress(0);
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(seekBar.getProgress());
}
}
});
}
public void playSong() {
try {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
clearMediaPlayer();
seekBar.setProgress(0);
wasPlaying = true;
fab.setImageDrawable(ContextCompat.getDrawable(MediaPlayerActivity.this, android.R.drawable.ic_media_play));
}
if (!wasPlaying) {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
}
fab.setImageDrawable(ContextCompat.getDrawable(MediaPlayerActivity.this, android.R.drawable.ic_media_pause));
Intent intent = getIntent();
String user_name = intent.getStringExtra("USER_NAME");
String file = intent.getStringExtra("FILE_NAME");
TextView Namee = findViewById(R.id.textView3);
Namee.setText(file);
mediaPlayer.setDataSource(user_name);
mediaPlayer.prepare();
mediaPlayer.setVolume(0.5f, 0.5f);
mediaPlayer.setLooping(false);
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
new Thread(this).start();
}
wasPlaying = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
int currentPosition = mediaPlayer.getCurrentPosition();
int total = mediaPlayer.getDuration();
while (mediaPlayer != null && mediaPlayer.isPlaying() && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
clearMediaPlayer();
}
private void clearMediaPlayer() {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
问题的发生是因为当你的 phone 休眠时,你的 activity 在一段时间后根据你的空闲内存和其他
销毁
重点是,对于像音乐播放这样的长时间 运行 任务,activity 不是一个选项。 Activity 大多数情况下,仅适用于需要用户关注、交互的任务,而不是 运行 在后台无限时间。
音乐播放器和如此长的 运行 作业需要使用服务,该服务会无限期地运行,直到用户或 OS 销毁它。
来自google doc关于服务
A Service is an application component that can perform long-running operations in the background, and it doesn't provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
具体来说,对于一个音乐应用,你需要前台服务
A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app.
我的 MediaPlayer
在 phone 大约 20 到 30 秒后进入睡眠状态后停止播放。我失败的尝试在下面提前致谢。
MediaPlayer mediaPlayer = new MediaPlayer();
SeekBar seekBar;
boolean wasPlaying = false;
ImageButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mediaplayer);
fab = findViewById(R.id.imageButton);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
playSong();
}
});
final TextView seekBarHint = findViewById(R.id.textView);
seekBar = findViewById(R.id.seekbar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekBarHint.setVisibility(View.VISIBLE);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
seekBarHint.setVisibility(View.VISIBLE);
int x = (int) Math.ceil(progress / 1000f);
if (x < 10)
seekBarHint.setText("0:0" + x);
else
seekBarHint.setText("0:" + x);
double percent = progress / (double) seekBar.getMax();
int offset = seekBar.getThumbOffset();
int seekWidth = seekBar.getWidth();
int val = (int) Math.round(percent * (seekWidth - 2 * offset));
int labelWidth = seekBarHint.getWidth();
seekBarHint.setX(offset + seekBar.getX() + val
- Math.round(percent * offset)
- Math.round(percent * labelWidth / 2));
if (progress > 0 && mediaPlayer != null && !mediaPlayer.isPlaying()) {
clearMediaPlayer();
fab.setImageDrawable(ContextCompat.getDrawable(MediaPlayerActivity.this, android.R.drawable.ic_media_play));
MediaPlayerActivity.this.seekBar.setProgress(0);
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(seekBar.getProgress());
}
}
});
}
public void playSong() {
try {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
clearMediaPlayer();
seekBar.setProgress(0);
wasPlaying = true;
fab.setImageDrawable(ContextCompat.getDrawable(MediaPlayerActivity.this, android.R.drawable.ic_media_play));
}
if (!wasPlaying) {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
}
fab.setImageDrawable(ContextCompat.getDrawable(MediaPlayerActivity.this, android.R.drawable.ic_media_pause));
Intent intent = getIntent();
String user_name = intent.getStringExtra("USER_NAME");
String file = intent.getStringExtra("FILE_NAME");
TextView Namee = findViewById(R.id.textView3);
Namee.setText(file);
mediaPlayer.setDataSource(user_name);
mediaPlayer.prepare();
mediaPlayer.setVolume(0.5f, 0.5f);
mediaPlayer.setLooping(false);
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
new Thread(this).start();
}
wasPlaying = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
int currentPosition = mediaPlayer.getCurrentPosition();
int total = mediaPlayer.getDuration();
while (mediaPlayer != null && mediaPlayer.isPlaying() && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
clearMediaPlayer();
}
private void clearMediaPlayer() {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
问题的发生是因为当你的 phone 休眠时,你的 activity 在一段时间后根据你的空闲内存和其他
销毁重点是,对于像音乐播放这样的长时间 运行 任务,activity 不是一个选项。 Activity 大多数情况下,仅适用于需要用户关注、交互的任务,而不是 运行 在后台无限时间。
音乐播放器和如此长的 运行 作业需要使用服务,该服务会无限期地运行,直到用户或 OS 销毁它。
来自google doc关于服务
A Service is an application component that can perform long-running operations in the background, and it doesn't provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
具体来说,对于一个音乐应用,你需要前台服务
A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app.