我已经让一个MediaPlayer从soundcloud播放了一些音频,播放和暂停正在运行,但问题是,当我按下手机上的后退按钮时它继续播放?任何建议都会很棒。 onBackPressed代码位于底部:)
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
String res = "https://api.soundcloud.com/tracks/84973999/stream?client_id=cd9d2e5604410d714e32642a4ec0eed4";
final MediaPlayer mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.prepare();
mp.start();
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
} catch (IOException e) {
}
mp.setOnCompletionListener(new OnCompletionListener() {
//When audio is done will change pause to play
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if(mp.isPlaying()){
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}}});
}
//To update progress bar
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<=total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if(mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed(){
if (mp != null){
if(mp.isPlaying())
mp.stop();
mp.release();
}
//there is no reason to call super.finish(); here
//call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}}
答案 0 :(得分:3)
我认为问题在于:
final MediaPlayer mp = new MediaPlayer();
您正在创建mp
的本地实例,因此您的全局实例始终为空。
只需替换为:
mp = new MediaPlayer();
希望它有效
答案 1 :(得分:0)
不确定为什么它不起作用,在我的应用程序中,我通常以这种方式覆盖它:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
...
文档说它应该是相同的,但我试一试:)
编辑:final MediaPlayer
从onCreate中删除此内容(我注意到太晚了抱歉)哈哈