我有一个打开时播放音乐的应用程序。但是当我停止音乐并使用后退按钮时,我得到一个异常并且应用程序强制关闭。这是我的代码:
@Override
protected void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.media_player_layout);
final Uri uri = getIntent() != null ? getIntent().getData() : null;
final SharedPreferences premiumSettings = getSharedPreferences("PREMIUM", Context.MODE_PRIVATE);
final boolean isPremium = premiumSettings.getBoolean("isPremium", false);
Button play = (Button) findViewById(R.id.play);
Button stop = (Button) findViewById(R.id.stop);
if (isPremium) {
musicPlayer = MediaPlayer.create(MusicPlayer.this, uri);
musicPlayer.start();
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(musicPlayer.isPlaying()){
musicPlayer.pause();
}
else {musicPlayer = MediaPlayer.create(MusicPlayer.this, uri);
musicPlayer.start();
}}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (musicPlayer.isPlaying()) {
musicPlayer.stop();
musicPlayer.release();
}
}
});
Button exit = (Button) findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (musicPlayer != null && musicPlayer.isPlaying()) {
musicPlayer.stop();
musicPlayer.release();
musicPlayer = null;
finish();
}
}
});
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(MusicPlayer.this);
builder.setTitle("Error");
builder.setMessage("You are not premium user. Please enter the promocode or buy the full version");
builder.setIcon(R.drawable.holo_dark_action_info);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}}
public void onBackPressed () {
if(musicPlayer.isPlaying()) {
musicPlayer.stop();
musicPlayer.release();
}
musicPlayer = null;
finish();
}
}
这是我的日志:
09-30 18:00:33.106 23141-23141/com.tproductions.Openit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tproductions.Openit, PID: 23141
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.tproductions.Openit.MusicPlayer.onBackPressed(MusicPlayer.java:76)
我怎样才能让它工作?我已经尝试过 if-else 语句,但它也不起作用。