我正在使用我的活动背景音乐。但是当我想取消它的时候,它不起作用。音乐一直在播放,直到它自己结束。下面是代码:
public class xx extends Activity
{ BackgroundSound mBackgroundSound = new BackgroundSound();
@Override
protected void onCreate(Bundle savedInstanceState)
{ ....
}
@Override
protected void onResume()
{
super.onResume();
mBackgroundSound.execute();
}
@Override
protected void onPause()
{
super.onPause();
mBackgroundSound.cancel(true);
}
和选项菜单选择:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mBackgroundSound.cancel(true);
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.menu_Add:
{ mBackgroundSound.cancel(true);
Intent intent = new Intent(xx.this,yy.class);
intent.putExtra("flag", "add");
intent.putExtra("AddObj", "mm");
startActivity(intent);
break;
}
case R.id.menu_list_quote:
{
mBackgroundSound.cancel(true);
Intent intent = new Intent(xx.this,zz.class);
intent.putExtra("Obj", "nn");
startActivity(intent);
break;
}
}
//return true;
return super.onOptionsItemSelected(item);
}
和asynTask:
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try
{
while( !isCancelled())
{
// FileDescriptor afd = openFd("cock_alarm.mp3");
MediaPlayer player = new MediaPlayer();
player.setDataSource(_musicFilePath);
player.prepare();
//player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
// if(isCancelled())
// player.stop();
}
}
catch(Exception exp)
{
exp.printStackTrace();
}
return null;
}
}
还有,尝试使用for循环:
for(int i=0;i<100 && !isCancelled();i++)
and try this inside try block of asyncTask:
if(isCancelled())
player.stop();
我要怎么解决它?
而不是创建一个AsyncTask,为什么不只是创建MediaPlayer,并从你的活动开始?
MediaPlayer有自己的线程逻辑。您不需要创建一个线程来管理媒体播放器。您可以在这里阅读更多内容:http://developer.android.com/guide/topics/media/mediaplayer.html
在您的活动中,您可以执行以下操作:
private MediaPlayer mMediaPlayer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initalize the media player
mMediaPlayer = ... however you are initializing it ...;
// Set the listener so the media player can tell you when it is finished preparing
mMediaPlayer.setOnPreparedListener(this);
// Prepare the MediaPlayer asynchronously so that the UI thread does not lock up
mMediaPlayer.prepareAsync();
}
// You need to listen for when the Media Player is finished preparing and is ready
public void onPrepared(MediaPlayer player) {
// Start the player
player.start();
}
当你需要停止播放时,只需调用
mMediaPlayer.stop();
vogella在他的网站上解释道:AsyncTask不会自动处理配置更改,也就是说,如果活动被重新创建,程序员必须在他的编码中处理它。
一个常见的解决方案是在一个保留的headless片段中声明AsyncTask。"查看全文:http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html androidbackground