有了這段代碼,我可以在後臺運行歌曲,點擊'yes'按鈕並用'no'停止它,但它只能運行一次。如果我再次單擊「是」按鈕(第二次),則應用程序停止。所以需要幫助,我希望我的活動能夠在每次單擊時使用這些警報對話框的按鈕來運行和停止音樂。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();}}
試着在'onCreate'中設置音頻'MediaPlayer歌曲',在'PositiveButton'中設置'song.start();' – waki
@Waki我首先試過,它只能工作一次;如果我點擊'yes'_first time_歌曲播放,如果我點擊'no'_first time_它會停止,當我再次點擊'是'時 - 應用程序停止。所以我使用了try/catch,但它沒有起作用。 – Journey
你不理解我,'setAudioStreamType','MediaPlayer.create'和'prepare'也放在'onCreate'中,在'PositiveButton'' onClick'只是'song.start();' – waki