栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

当应用程序进入后台时停止MediaPlayer服务

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

当应用程序进入后台时停止MediaPlayer服务

停止播放器后,需要重新准备播放器。如果您想在应用程序进入后台时停止播放,并在应用程序进入前台时从头开始播放媒体。只需将您的BroadcastReceiver代码修改为此:

private BroadcastReceiver StateReceiver = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) { String status = intent.getStringExtra("status"); if (parseInt(String.valueOf(status)) == 0) {     player.stop(); } else {     player = MediaPlayer.create(this, R.raw.music);     player.setLooping(true);     player.start(); }        }    };

但是,如果要暂停播放并从离开的位置继续播放,请进行以下更改:在Application类的onActivityDestroyed()中:

@Overridepublic void onActivityDestroyed(Activity activity) {    send_status(2);}

并在BroadcastReceiver中:

private BroadcastReceiver StateReceiver = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) { String status = intent.getStringExtra("status"); if (parseInt(String.valueOf(status)) == 0) {     player.pause();  //When app is in background and not killed, we just want to pause the player and not want to lose the current state. } else if (parseInt(String.valueOf(status)) == 1) {     if (player != null)         player.start();  // If the player was created and wasn't stopped, it won't be null, and the playback will be resumed from where we left of.     else {         // If the player was stopped, we need to prepare it once again.         player = MediaPlayer.create(this, R.raw.music);         player.setLooping(true);         player.start();     } } else if(player != null){     player.stop();     player.release(); }        }    };

另外,看看MediaPlayer的状态。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497144.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号