我在我的活动背景中使用音乐。但是当我试图取消它时它不起作用。音乐一直在持续运行,直到它完成。以下是代码:
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++)
并在asyncTask的try块中尝试了这个:
if(isCancelled())
player.stop();
我将如何解决它?
答案 0 :(得分:5)
为什么不创建MediaPlayer,而不是创建AsyncTask,而是从您的活动中启动它?
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();
答案 1 :(得分:1)
正如,vogella在他的网站上解释的那样: “AsyncTask不会自动处理配置更改,即如果重新创建活动,程序员必须在编码时处理它。
一个常见的解决方案是在保留的无头片段中声明AsyncTask。“
查找全文: http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html#androidbackground