[英]How to pause/stop music when home or back button is pressed?
Here is my code. 这是我的代码。 I'm very new to Java and I know that this question is already been posted but still I didn't get the expected outpost so I had to post.
我对Java非常陌生,我知道这个问题已经发布了,但是我仍然没有得到预期的前哨,所以我不得不发布。
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (policeSound.isPlaying()){
policeSound.stop();
}
else {
policeSound.start();
}
}
});
}
}
I tried adding onBackPressed()
code to this but it couldn't detect the 'policeSound' as it was detected in the previous method! 我尝试在此方法上添加
onBackPressed()
代码,但无法检测到“ policeSound”,因为在以前的方法中已检测到它!
And someone please even teach me how to use @Override
annotations! 还有人甚至
@Override
我如何使用@Override
注释!
To detect the 'policeSound' in other methods you need to make it be a field of a class: 要检测其他方法中的“ policeSound”,您需要使其成为类的字段:
private MediaPlayer policeSound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (policeSound.isPlaying()) {
policeSound.stop();
} else {
policeSound.start();
}
}
}
);
}
In your codes policeSound is a local variable which is be seen only in Oncreate()
method,as Oleh Sokolov said, you should declare policeSound as a field of class. 在您的代码中, PoliceSound是一个局部变量,仅在
Oncreate()
方法中可见,如Oleh Sokolov所说,您应将PoliceSound声明为类的字段。
About @Override
, you could see this good explanation 关于
@Override
,您可以看到这个很好的解释
and in android studio , when you press ctrl + o
in java class file, you can override superclass method, and IDE will add @Override
automatically for you. 在android studio中,当您在Java类文件中按
ctrl + o
时,您可以覆盖超类方法,IDE会自动为您添加@Override
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.