我有一个带有按钮的应用程序,可以播放或暂停音乐。在播放音乐的同时按返回按钮可使其暂停,并在再次按下播放按钮后再次打开该应用以恢复音乐。但这不适用于“主页”或“最近”按钮。音乐暂停,但是在重新打开应用程序并按“播放”按钮后,直到强行关闭才播放音乐。这是代码:
package com.example.firozkaoo2222.myapplication;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import static com.example.firozkaoo2222.myapplication.R.raw.police;
public class MainActivity extends AppCompatActivity {
private MediaPlayer policeSound = MediaPlayer.create(this, police);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button policeSounds = this.findViewById(R.id.police);
policeSounds.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (policeSound == null) {
policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police);
}
if (policeSound.isPlaying()) {
policeSound.pause();
} else {
policeSound.start();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if (policeSound != null) {
policeSound = MediaPlayer.create(this, R.raw.police);
policeSound.start();
}
}
@Override
public void onPause() {
super.onPause();
if (policeSound.isPlaying())
policeSound.pause();
}
//Back button pressed.
@Override
public void onBackPressed() {
super.onBackPressed();
if (policeSound.isPlaying())
policeSound.pause();
}
@Override
protected void onDestroy() {
super.onDestroy();
policeSound.stop();
policeSound = null;
}
}
答案 0 :(得分:0)
如果按下主屏幕按钮,应用将进入后台,当您从后台进入时,您应该覆盖onResume();
代码:
public class MainActivity extends AppCompatActivity {
//THIS IS YOUR LAST MISTAKE. IF YOU TRY TO CREATE THE OBJECT WITH THE CONTEXT AND THE RESOUERCES
//WHEN THE ACTIVITY IS NOT CREATED YET, YOUR APP CRASH
//private MediaPlayer policeSound = MediaPlayer.create(this, R.raw.police);
private MediaPlayer policeSound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button policeSounds = this.findViewById(R.id.police);
policeSounds.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (policeSound == null) {
policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police);
}
if (policeSound.isPlaying()) {
policeSound.pause();
} else {
policeSound.start();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if (policeSound != null) {
policeSound = MediaPlayer.create(this, R.raw.police);
policeSound.start();
}
}
@Override
public void onPause() {
super.onPause();
if (policeSound.isPlaying())
policeSound.pause();
}
//Back button pressed.
@Override
public void onBackPressed() {
super.onBackPressed();
if (policeSound.isPlaying())
policeSound.pause();
}
@Override
protected void onDestroy() {
super.onDestroy();
policeSound.stop();
policeSound = null;
}
}
希望对您有帮助。