声音停止时的动作? Android Studio

时间:2015-07-14 09:10:39

标签: android audio

我在Android Studio中创建了我的第一个应用。我得到了这个活动,它只是用MediaPlayer播放声音,然后它应该返回主要活动,通过一个按钮(工作正常)或声音停止(我缺少的)。有没有一种简单的方法来检查声音是否已经停止播放,然后让它触发一个动作?

到目前为止,这是我的代码:

import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;


public class image_button_2 extends ActionBarActivity implements View.OnClickListener {

ImageButton imageButton6;
MediaPlayer mySound;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_button_2);
    imageButton6 = (ImageButton) findViewById(R.id.imageButton6);
    imageButton6.setOnClickListener(this);
    mySound = MediaPlayer.create(this, R.raw.hb);
    mySound.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_image_button_2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void imageButton6Click(){

    mySound.stop();
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);

}

@Override
public void onClick(View v) {

    switch (v.getId()){
        case R.id.imageButton6:
            imageButton6Click();
            break;
    }

}

}

2 个答案:

答案 0 :(得分:1)

  

试一试,音乐播放完成后会进入MainActivity

 mySound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            imageButton6Click();
        }
    });

答案 1 :(得分:0)

我认为您正在寻找OnCompletionListener callback