You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发求助:按下返回/主页键无法停止ImageView触发的循环音频

解决Android应用返回/主页键无法停止音频的问题

问题根源

按下返回键或主页键时,Activity会进入暂停(onPause)或销毁(onDestroy)状态,但你的代码没在这些生命周期节点处理音频的停止与资源释放,导致音频持续播放。另外,MediaPlayer被声明为onCreate方法内的局部变量,生命周期方法无法访问它,这也是无法控制它的核心原因。

修复步骤

  1. 将MediaPlayer改为成员变量:把MediaPlayer从onCreate内部移到类的成员位置,让生命周期方法能访问到它。
  2. 重写Activity生命周期方法:在onPause和onDestroy中停止并释放MediaPlayer,同时暂停/释放SoundPool资源,避免内存泄漏。

修改后的完整代码

ImageView imgPlay;
ImageView imgPause;
int sound1 = -1;
SoundPool soundPool;
// 将MediaPlayer改为类成员变量
MediaPlayer sound;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);

    imgPlay = findViewById(R.id.imgPlay);
    imgPause = findViewById(R.id.imgPause);

    // 初始化成员变量的MediaPlayer
    sound = MediaPlayer.create(play.this, R.raw.song1);

    // 修正SoundPool的音频流参数(原参数3已过时,改用标准常量)
    this.soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
    this.sound1 = this.soundPool.load(this, R.raw.sound1, 1);

    imgPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sound.start();
            sound.setLooping(true);
        }
    });

    imgPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sound.pause();
        }
    });
    
    ((Button) findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            play.this.soundPool.autoPause();
            play.this.soundPool.play(play.this.sound1, 1.0f, 1.0f, 0, 0, 1.0f);
        }
    });
}

// 当Activity暂停时停止音频播放
@Override
protected void onPause() {
    super.onPause();
    if (sound != null && sound.isPlaying()) {
        sound.pause();
    }
    if (soundPool != null) {
        soundPool.autoPause();
    }
}

// 当Activity销毁时彻底释放音频资源
@Override
protected void onDestroy() {
    super.onDestroy();
    if (sound != null) {
        sound.stop();
        sound.release();
        sound = null;
    }
    if (soundPool != null) {
        soundPool.release();
        soundPool = null;
    }
}

关键说明

  • onPause方法:按下主页键或切换其他应用时触发,暂停所有音频播放,保证应用后台时不再发声。
  • onDestroy方法:按下返回键销毁Activity时触发,彻底释放MediaPlayer和SoundPool的资源,避免内存泄漏。
  • 参数修正:把SoundPool构造中的第二个参数从3改为AudioManager.STREAM_MUSIC,原参数已过时,使用标准常量更规范。

内容的提问来源于stack exchange,提问作者anil halder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:01:23