gpt4 book ai didi

java - Android MediaPlayer onPause()

转载 作者:行者123 更新时间:2023-12-01 12:05:35 24 4
gpt4 key购买 nike

我是一名 Android 初学者开发人员,我想开发一个基本的应用程序,该应用程序在打开时开始播放音乐,在完成时停止(onPause)。当我创建方法“onPause”时,我的条件“musica.stop();”不工作。

我的代码:

import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final MediaPlayer mpBtnsom = MediaPlayer.create(this, R.raw.somvoa);
ImageButton btn1 = (ImageButton) findViewById(R.id.imageButton2);

MediaPlayer musica = MediaPlayer.create(this, R.raw.sommusica);
musica.start();
musica.setLooping(true);

btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mpBtnsom.start();
}
});
}

public void toast2(View view){
Toast toast = Toast.makeText(MainActivity.this, "Botão ToastMessage", Toast.LENGTH_LONG);
toast.show();
}

public void toast(View view){
Toast toast = Toast.makeText(MainActivity.this, "Botão Felpudo", Toast.LENGTH_SHORT);
toast.show();
}

protected void onPause(){
super.onPause();

musica.stop();
finish();
}
}

最佳答案

问题是在您的 onPause() 方法中无法访问变量 musica。您应该声明变量 musica 以便在类中全局使用,如下所示。

public class MainActivity extends ActionBarActivity {

private MediaPlayer musica;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final MediaPlayer mpBtnsom = MediaPlayer.create(this, R.raw.somvoa);
ImageButton btn1 = (ImageButton) findViewById(R.id.imageButton2);

musica = MediaPlayer.create(this, R.raw.sommusica);
musica.start();
musica.setLooping(true);

btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mpBtnsom.start();
}
});
}

public void toast2(View view){
Toast toast = Toast.makeText(MainActivity.this, "Botão ToastMessage", Toast.LENGTH_LONG);
toast.show();
}

public void toast(View view){
Toast toast = Toast.makeText(MainActivity.this, "Botão Felpudo", Toast.LENGTH_SHORT);
toast.show();
}

@Override
protected void onPause(){
super.onPause();

musica.stop();
finish();
}
}

关于java - Android MediaPlayer onPause(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27650798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com