1

我为音频示例创建了一个简单的 Activity 类。但问题是即使我离开应用程序,音频文件也会继续运行。我只想通过按下任何电话中间的“确定/完成”按钮来停止活动。我应该在活动类中覆盖哪种方法?

public class Audio extends Activity {

    private MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_audio, menu);
    return true;
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    int resId;
    switch (keyCode) {
    case KeyEvent.KEYCODE_DPAD_UP:
    resId = R.raw.up;
    break;
    case KeyEvent.KEYCODE_DPAD_DOWN:
    resId = R.raw.down;
    break;

    default:
        return super.onKeyDown(keyCode, event);
    }

    // Release any resources from previous MediaPlayer
    if (mp != null) {
        mp.release();
        }

    // Create a new MediaPlayer to play this sound
    mp = MediaPlayer.create(this, resId);
    mp.start();

    // Indicate this key was handled
    return true;


}

}/// end class
4

2 回答 2

2

尝试使用这个:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
    Toast.makeText(Audio.this, "You pressed the home button!", Toast.LENGTH_LONG).show();  
    Audio.this.finish();                  
    return true;
}
return super.onKeyDown(keyCode, event);

}

于 2012-09-10T06:25:23.647 回答
0

你可以在 onPause() 方法中处理你想要的。或者你也可以实现 onDestroy() 方法。当您按下主页按钮或关闭应用程序时,它会转到 onPause(),然后是 onDestroy()。

@Override
protected void onPause() {
    // stop player here
    super.onPause();
}
于 2012-09-10T06:48:02.950 回答