開いたときに音楽を再生するアプリがあります。しかし、音楽を停止して戻るボタンを使用すると、例外が発生し、アプリが強制終了します。これは私のコードです:
@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();
}
}
これは私のlogcatです:
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 ステートメントを試しましたが、どちらも機能しません。