解决Agora声网音视频在后台没有声音的问题

前言:本文会介绍 Android 与 iOS 两个平台的处理方式

一、Android高版本在应用退到后台时,系统为了省电会限制应用的后台活动,因此我们需要开启一个前台服务,在前台服务中发送常驻任务栏通知,以此来保证App 退到后台时不会被限制活动.

前台服务代码如下:

package com.notify.test.service;import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;import com.notify.test.R;import androidx.annotation.Nullable;/*** desc:解决声网音视频锁屏后听不到声音的问题* (可以配合Application.ActivityLifecycleCallbacks使用)** Created by booyoung* on 2023/9/8 14:46*/
public class KeepAppLifeService extends Service {@Nullable@Overridepublic IBinder onBind(Intent intent) {return null;}private final String notificationId = "app_keep_live";private final String notificationName = "audio_and_video_call";@Overridepublic void onCreate() {super.onCreate();NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);//创建NotificationChannelif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);//不震动channel.enableVibration(false);//静音channel.setSound(null, null);notificationManager.createNotificationChannel(channel);}startForeground(1, getNotification());}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();}@Overridepublic void onTaskRemoved(Intent rootIntent) {super.onTaskRemoved(rootIntent);//stop servicethis.stopSelf();}/*** 获取通知(Android8.0后需要)* @return*/private Notification getNotification() {Notification.Builder builder = new Notification.Builder(this).setSmallIcon(R.mipmap.logo).setOngoing(true).setContentTitle("App名称").setContentIntent(getIntent()).setContentText("音视频通话中,轻击以继续");if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {builder.setChannelId(notificationId);}return builder.build();}/*** 点击后,直接打开app* @return*/private PendingIntent getIntent() {//获取启动ActivityIntent msgIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage(getPackageName());PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),1,msgIntent,PendingIntent.FLAG_UPDATE_CURRENT);return pendingIntent;}
}

不要忘记在AndroidManifest.xml中声明Service哈

 <service android:name=".service.KeepAppLifeService"android:enabled="true"android:exported="false"android:stopWithTask="true" />

然后接下来就需要在声网音视频接通与挂断分别开启与关闭前台服务了,此处回调使用了EaseCallKit的写法,如果没使用EaseCallKit UI库的可以自己在EaseVideoCallActivity中的接通与挂断回调开启与关闭前台服务

  public void addCallkitListener() {callKitListener = new EaseCallKitListener() {@Overridepublic void onInviteUsers(Context context, String userId[], JSONObject ext) {}@Overridepublic void onEndCallWithReason(EaseCallType callType, String channelName, EaseCallEndReason reason, long callTime) {EMLog.d(TAG, "onEndCallWithReason" + (callType != null ? callType.name() : " callType is null ") + " reason:" + reason + " time:" + callTime);SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");formatter.setTimeZone(TimeZone.getTimeZone("UTC"));String callString = "通话时长";callString += formatter.format(callTime);Toast.makeText(MainActivity.this, callString, Toast.LENGTH_SHORT).show();//关闭任务栏通知stopBarNotify();}@Overridepublic void onGenerateToken(String userId, String channelName, String appKey, EaseCallKitTokenCallback callback) {EMLog.d(TAG, "onGenerateToken userId:" + userId + " channelName:" + channelName + " appKey:" + appKey);//获取声网TokengetAgoraToken(userId, channelName, callback);//创建服务开启任务栏通知(此处为了模拟,最好将openBarNotify()方法放在获取成功声网token后调用)openBarNotify();}@Overridepublic void onReceivedCall(EaseCallType callType, String fromUserId, JSONObject ext) {EMLog.d(TAG, "onRecivedCall" + callType.name() + " fromUserId:" + fromUserId);}@Overridepublic void onCallError(EaseCallKit.EaseCallError type, int errorCode, String description) {EMLog.d(TAG, "onCallError");}@Overridepublic void onInViteCallMessageSent() {
//                LiveDataBus.get().with(DemoConstant.MESSAGE_CHANGE_CHANGE).postValue(new EaseEvent(DemoConstant.MESSAGE_CHANGE_CHANGE, EaseEvent.TYPE.MESSAGE));}@Overridepublic void onRemoteUserJoinChannel(String channelName, String userName, int uid, EaseGetUserAccountCallback callback) {}};EaseCallKit.getInstance().setCallKitListener(callKitListener);}private void openBarNotify(){keepAppIntent = new Intent(this, KeepAppLifeService.class);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//android8.0以上通过startForegroundService启动servicestartForegroundService(keepAppIntent);} else {startService(keepAppIntent);}}private void stopBarNotify(){if (keepAppIntent != null) {stopService(keepAppIntent);}}

二、iOS想在后台时播放声音,需要在添加App plays audio or streams audio/video using AirPlay权限

1.Info.plist里找到选项Required background modes 添加App plays audio or streams audio/video using AirPlay

2.在Signing&Capabilities -> Background Modes -> 勾选 Audio,AirPlay, and Picture in Picture

3.在AppDelegate.m中实现applicationDidEnterBackground代理方法

- (void)applicationDidEnterBackground:(UIApplication *)application{//环信已实现了进入后台的处理逻辑,如果要自己处理,可以参考下边注释代码[[EMClient sharedClient] applicationDidEnterBackground:application];
}#if Ease_UIKIT
//    - (void)applicationDidEnterBackground:(NSNotification *)notification {
//        if (!self.config.shouldRemoveExpiredDataWhenEnterBackground) {
//            return;
//        }
//        Class UIApplicationClass = NSClassFromString(@"UIApplication");
//        if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
//            return;
//        }
//        UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
//        __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
//            // Clean up any unfinished task business by marking where you
//            // stopped or ending the task outright.
//            [application endBackgroundTask:bgTask];
//            bgTask = UIBackgroundTaskInvalid;
//        }];
//
//        // Start the long-running task and return immediately.
//        [self deleteOldFilesWithCompletionBlock:^{
//            [application endBackgroundTask:bgTask];
//            bgTask = UIBackgroundTaskInvalid;
//        }];
//    }
#endif

 4.因为App plays audio or streams audio/video using AirPlay权限只能是音乐播放类与具有音视频通话场景的App使用,所以审核的时候需要在备注描述清楚使用该场景的方式.如果审核失败,可以录制视频在附件上传,然后等待苹果重新审核即可.如果录制的视频没有问题,那就坐等着审核通过了,good luck!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/80996.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Limit分页遇到百万级数据该何去何从

一、Limit分页基础 mysql使用查询语句的时候&#xff0c;经常要返回前几条或者中间某几行数据&#xff0c;也就是我们说的分页&#xff0c;语法如下&#xff1a; SELECT * FROM table LIMIT offset,lengthLIMIT 子句可以被用于强制 SELECT 语句返回指定的记录数。LIMIT 接受一…

TCP详解之滑动窗口

TCP详解之滑动窗口 引入窗口概念的原因 我们都知道 TCP 是每发送一个数据&#xff0c;都要进行一次确认应答。当上一个数据包收到了应答了&#xff0c; 再发送下一个。 这个模式就有点像我和你面对面聊天&#xff0c;你一句我一句。但这种方式的缺点是效率比较低的。 如果你…

git中无法使用方向键的问题

windows下使用git命令行执行react脚本安装&#xff0c;发现无法使用上下键来去选中选项。最后只能换成cmd命令执行&#xff0c;发现可以上下移动以选中需要的选项。 bash命令行&#xff1a;移动光标无法移动选项 cmd命令行

算法宝典1——Java版本(此系列持续更新,这篇文章有20道)(有题目的跳转链接)(此份宝典包含了链表、栈、队列、二叉树的算法题)

注&#xff1a;由于字数的限制&#xff0c;我打算把算法宝典做成一个系列&#xff0c;一篇文章就20题&#xff01;&#xff01;&#xff01; 目录 一、链表的算法题&#xff08;目前10道&#xff09; 1. 移除链表元素&#xff08;力扣&#xff1b;思路&#xff1a;前后指针&…

Linux-Nginx安装

一、Nginx下载 官网下载地址&#xff1a; https://nginx.org/en/download.html 国内镜像地址&#xff1a; https://mirrors.huaweicloud.com/nginx 二、Nginx安装 1. 将下载的Nginx安装包上传到Linux服务器指定安装盘符下&#xff0c;解压zip包 tar -zxvf nginx-1.23.3.ta…

【PHP】麻醉临床信息系统

麻醉临床信息系统以服务围术期临床业务工作的开展为核心&#xff0c;为医护人员、业务管理人员、院级领导提供流程化、信息化、自动化、智能化的临床业务综合管理平台。 麻醉信息系统处理的数据包含病人的手术信息、麻醉信息、病人手术过程中从监护仪上采集到的数据和病人情况等…

【嵌入式】2024届校招岗位汇总

公司岗位博世嵌入式自动化测试工程师博世嵌入式开发&#xff08;软件刷写及启动&#xff09;工程师博世Linux/C软件工程师博世自动驾驶软件开发工程师博世嵌入式软件工程师(BSP)博世嵌入式电子工程师 &#xff08;BMS&电源&#xff09;博世物联网嵌入式开发工程师 &#xf…

vue3-vant4-vite-pinia-axios-less学习日记

代码地址 GitHub&#xff1a;vue3-vant4-vite-pinia-axios-less 效果如图 1.首页为导航栏 2.绑定英雄页 3.注册页 4.英雄列表页 5.后面不截图了&#xff0c;没啥了 模块 1.vant4&#xff1a;按需引入组件样式文档 2.安装该vite-plugin-vue-setup-extend插件可以直接在…

数据结构与算法(一)

文章目录 数据结构与算法(一)1 位运算、算法是什么、简单排序1.1 实现打印一个整数的二进制1.2 给定一个参数N,返回1!+2!+3!+4!+...+N!的结果1.3 简单排序算法2 数据结构大分类、前缀和、对数器2.1 实现前缀和数组2.2 如何用1\~5的随机函数加工出1\~7的随机函数2.3 如何把不…

C++学习笔记--项目知识点集合

一、同步IO、异步IO、阻塞IO、非阻塞IO 首先来看看两种I/O的定义&#xff1a;同步I/O和异步I/O 同步&#xff08;阻塞&#xff09;I/O&#xff1a;在一个线程中&#xff0c;CPU执行代码的速度极快&#xff0c;然而&#xff0c;一旦遇到IO操作&#xff0c;如读写文件、发送网络…

vue+electron一键入门

前言 帮公司弄了一个vueelectron项目&#xff0c;里面用到了axios、element-ui、ue-router、js-md5、sqlite3这些依赖库&#xff0c;其中sqlite3比较难搞下面会详细展开来讲&#xff0c;同时也涉及打包&#xff08;window包、mac包&#xff09; 开始 其实项目整体没啥好讲&a…

Linux安装logstash

相关链接 项⽬主⻚&#xff1a; https://www.elastic.co/cn/downloads/logstash 下载地址&#xff1a; wget https://artifacts.elastic.co/downloads/logstash/logstash-7.5.1.tar.gz 官网下载可能比较慢&#xff0c;下面提供下载地址 百度云链接&#xff1a;https://pan.…

[golang 流媒体在线直播系统] 4.真实RTMP推流摄像头把摄像头拍摄的信息发送到腾讯云流媒体服务器实现直播

用RTMP推流摄像头把摄像头拍摄的信息发送到腾讯云流媒体服务器实现直播,该功能适用范围广,比如:幼儿园直播、农场视频直播, 一.准备工作 要实现上面的功能,需要准备如下设备: 推流摄像机&#xff08;监控&#xff09; 流媒体直播服务器(腾讯云流媒体服务器,自己搭建的流媒体服务…

【LeetCode-简单题】541. 反转字符串 II

文章目录 题目方法一&#xff1a;双指针 题目 方法一&#xff1a;双指针 题目的意思&#xff1a; 通俗一点说&#xff0c;每隔k个反转k个&#xff0c;末尾不够k个时全部反转&#xff1b; 需要注意右边界的取值 int r Math.min(l k -1,n-1);//取右边界与n-1的最小值 确定边界…

第28节-PhotoShop基础课程-图层操作

文章目录 前言1.像素图层2.删除 Delete3.合并 Ctrl E4.盖印 Ctrl Shift Alt5.图层顺序-拖动就可以6.编组-Ctrl G 管理图层-分类存放7.锁定图层-背景图层8.不透明度9.查找图层 2.智能图层1.能保持图片放大缩小&#xff08;Ctrl T&#xff09;的时候不丢失分辨率2.和滤镜配合使…

Java手写哈希集合和案例拓展

Java手写哈希集合和案例拓展 1. 思维导图 #mermaid-svg-hx4PFS8HX0SmLwDA {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-hx4PFS8HX0SmLwDA .error-icon{fill:#552222;}#mermaid-svg-hx4PFS8HX0SmLwDA .error-text…

Prometheus 基础入门

一.Prometheus Prometheus是由SoundCloud开发的开源监控报警系统和时序列数据库(TSDB)。Prometheus使用Go语言开发,是Google BorgMon监控系统的开源版本。2016年由Google发起Linux基金会旗下的原生云基金会(Cloud Native Computing Foundation), 将Prometheus纳入其下第二大开…

Linux学习第18天:Linux并发与竞争: 没有规矩不成方圆

Linux版本号4.1.15 芯片I.MX6ULL 大叔学Linux 品人间百味 思文短情长 提到锁”&#xff0c;可能想到的更多的是限制。现实中&#xff0c;生活中锁也 存在于身边的方方面面。正所谓没有规矩不成方圆&#xff0c; 没有身边的这些锁&…

vue 引入zTree

下载js包解压后找个地方放文件夹内 引入 import "/common/zTree/js/jquery-1.4.4.min" import "/common/zTree/js/jquery.ztree.core.min.js" import "/common/zTree/js/jquery.ztree.excheck.min.js" import "/common/zTree/css/metroSt…

《TCP/IP网络编程》阅读笔记--epoll的使用

1--epoll的优点 select()的缺点&#xff1a; ① 调用 select() 函数后针对所有文件描述符的循环语句&#xff1b; ② 调用 select() 函数时需要向操作系统传递监视对象信息&#xff1b; epoll()的优点&#xff1a; ① 无需编写以监视状态变化为目的的针对所有文件描述符的循环语…