С помощью этой части кода я смог запустить песню в фоновом режиме, нажав кнопку «Да», и остановить ее «нет», но она работает только один раз. Если я снова нажму кнопку «Да» (второй раз), приложение остановится. Так что нужна помощь, я хочу, чтобы моя моя деятельность запускалась и останавливала музыку с помощью этих кнопок диалога оповещения при каждом нажатии.Android-плеер не работает во второй раз
public class Music extends Activity {
final Context context = this;
MediaPlayer song;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder
.setMessage("Turn ON the music?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
song.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
song = MediaPlayer.create(Music.this, R.raw.fing);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
try {
song.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
song.start();
}
// dialog.cancel();
}
)
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick (DialogInterface dialog,int id){
// if this button is clicked, just close
// the dialog box and do nothing
if(song!=null && song.isPlaying()){
song.stop();
dialog.cancel();
}
}});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();}}
попробуйте назначить и установить аудио 'MediaPlayer song' в' onCreate', в 'PositiveButton' просто' song.start(); ' – waki
@Waki Я попробовал сначала, он работает, но только один раз; Если я нажму «yes'_first time_», песня будет воспроизводиться, и если я нажму «no'_first time_», она остановится, и когда я снова нажму «да» _ секунд второго раза, приложение остановится. Поэтому я использовал try/catch, но это не сработало. – Journey
вы меня не понимаете, 'setAudioStreamType',' MediaPlayer.create' и 'prepare' также помещены в' onCreate', в 'PositiveButton'' onClick' просто' song.start(); ' – waki