问题
I'm trying to follow the Core App Quality guideline FN-A1 that says that audio shouldn't play when the screen is off, so I checked it, and it does continue playing after I turn the screen off, but I'm not sure why. I don't think I'm using a service, and it seems that MediaPlayer should stop playing by default. Can anyone help me figure what I did wrong? I've copied the relevant parts of code. Thanks
public class RecordActivity extends BaseActivity {
MediaPlayer playback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
listView = (ListView)findViewById(R.id.listView);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getString(R.string.app_name));
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String item = ((TextView) view).getText().toString();
File itemFile = new File(dir + "/" + item + ".wav");
if (itemFile.exists()) {
playback = MediaPlayer.create(getApplicationContext(), Uri.fromFile(itemFile));
try {
playback.start();
} catch (NullPointerException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), R.string.errorFileNull, Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(getApplicationContext(), R.string.errorNotRecorded, Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
回答1:
You should stop the MediaPlayer in onPause:
if (playback != null && playback.isPlaying()) {
playback.pause();
}
Resume it in onResume:
if (playback != null && !playback .isPlaying()) {
playback.start();
}
回答2:
Heads Up!
Notes About Media player
- MediaPlayer is state oriented, and handling its errors is not as easy as it seems. If you need this in a reliable environment you have to consider setting an OnErrorListener at least
Notes About the code itself
- You are catching a NullPointerException
// the better way is to check
if(playback == null){
Toast.makeText(getApplicationContext(), R.string.errorFileNull, Toast.LENGTH_SHORT).show();
}
来源:https://stackoverflow.com/questions/33381519/android-mediaplayer-continues-playing-after-screen-is-turned-off