合并声网代码

This commit is contained in:
zlzw 2024-06-05 17:55:05 +08:00
parent c926037cb6
commit 405909f3b3
200 changed files with 18645 additions and 2565 deletions

View File

@ -39,6 +39,7 @@ android {
versionName rootProject.ext.android.versionName versionName rootProject.ext.android.versionName
manifestPlaceholders = rootProject.ext.manifestPlaceholders manifestPlaceholders = rootProject.ext.manifestPlaceholders
ndk { ndk {
//abiFilters "armeabi-v7a", "arm64-v8a","x86","x86_64"
abiFilters "armeabi-v7a", "arm64-v8a" abiFilters "armeabi-v7a", "arm64-v8a"
} }
} }
@ -72,10 +73,10 @@ dependencies {
implementation rootProject.ext.dependencies["recyclerview-androidx"] implementation rootProject.ext.dependencies["recyclerview-androidx"]
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
//common //common
implementation project(path: ':common') api project(path: ':common')
implementation 'com.faceunity:core:8.3.1' api 'com.faceunity:core:8.7.0'
implementation 'com.faceunity:model:8.3.1' api 'com.faceunity:model:8.7.0'
//implementation 'com.faceunity:nama:8.3.1' //- //implementation 'com.faceunity:nama:8.3.1' //-

View File

@ -1,26 +0,0 @@
package com.yunbao.faceunity;
import android.content.Context;
import androidx.test.platform.app.Instrimport com.yunbao.common.utils.MobclickAgent;ntationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.yunbao.faceunity.test", appContext.getPackageName());
}
}

View File

@ -96,11 +96,17 @@ public class FaceManager implements SensorEventListener {
faceUnityView.setIFaceUnityInter(new FaceUnityView.IFaceUnityInter() { faceUnityView.setIFaceUnityInter(new FaceUnityView.IFaceUnityInter() {
@Override @Override
public void onPause() { public void onPause() {
if(onMirrorChanged!=null){
onMirrorChanged.onChange(false);
}
pauseFace = true; pauseFace = true;
} }
@Override @Override
public void onStart() { public void onStart() {
if(onMirrorChanged!=null){
onMirrorChanged.onChange(true);
}
pauseFace = false; pauseFace = false;
} }
}); });
@ -295,7 +301,18 @@ public class FaceManager implements SensorEventListener {
} }
OnMirrorChanged onMirrorChanged;
public void setOnMirrorChanged(OnMirrorChanged onMirrorChanged) {
this.onMirrorChanged = onMirrorChanged;
}
public interface FaceStatusChanged { public interface FaceStatusChanged {
void onFaceChanged(int num); void onFaceChanged(int num);
} }
public interface OnMirrorChanged{
void onChange(boolean falg);
}
} }

View File

@ -52,10 +52,10 @@ public class FURenderer extends IFURenderer {
/* 特效FURenderKit*/ /* 特效FURenderKit*/
private FURenderKit mFURenderKit; public FURenderKit mFURenderKit;
/* AI道具*/ /* AI道具*/
public static String BUNDLE_AI_FACE = "model" + File.separator + "ai_face_processor_lite.bundle"; public static String BUNDLE_AI_FACE = "model" + File.separator + "ai_face_processor.bundle";
public static String BUNDLE_AI_HUMAN = "model" + File.separator + "ai_human_processor.bundle"; public static String BUNDLE_AI_HUMAN = "model" + File.separator + "ai_human_processor.bundle";
/* GL 线程 ID */ /* GL 线程 ID */

View File

@ -15,7 +15,7 @@ public class FaceUnityConfig {
/************************** 算法Model ******************************/ /************************** 算法Model ******************************/
// 人脸识别 // 人脸识别
public static String BUNDLE_AI_FACE = "model" + File.separator + "ai_face_processor_lite.bundle"; public static String BUNDLE_AI_FACE = "model" + File.separator + "ai_face_processor.bundle";
// 手势 // 手势
public static String BUNDLE_AI_HAND = "model" + File.separator + "ai_hand_processor.bundle"; public static String BUNDLE_AI_HAND = "model" + File.separator + "ai_hand_processor.bundle";

View File

@ -40,6 +40,7 @@ android {
manifestPlaceholders = rootProject.ext.manifestPlaceholders manifestPlaceholders = rootProject.ext.manifestPlaceholders
ndk { ndk {
abiFilters "armeabi-v7a", "arm64-v8a" abiFilters "armeabi-v7a", "arm64-v8a"
//abiFilters "armeabi-v7a", "arm64-v8a","x86","x86_64"
} }
} }
aaptOptions { aaptOptions {

View File

@ -1,26 +0,0 @@
package com.yunbao.share;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.yunbao.share.test", appContext.getPackageName());
}
}

View File

@ -229,6 +229,7 @@ android {
ndk { ndk {
// TODO: // TODO:
abiFilters "armeabi-v7a", "arm64-v8a" abiFilters "armeabi-v7a", "arm64-v8a"
//abiFilters "armeabi-v7a", "arm64-v8a","x86","x86_64"
} }
javaCompileOptions { javaCompileOptions {
annotationProcessorOptions { annotationProcessorOptions {

View File

@ -190,6 +190,8 @@ rx.internal.util.atomic.LinkedQueueNode* consumerNode;
-keep class org.greenrobot.eventbus.android.AndroidComponentsImpl* -keep class org.greenrobot.eventbus.android.AndroidComponentsImpl*
#--------ARouter #--------ARouter
-keep public class com.alibaba.android.arouter.**{*;}
-keep public class com.alibaba.android.arouter.routes.**{*;} -keep public class com.alibaba.android.arouter.routes.**{*;}
-keep public class com.alibaba.android.arouter.facade.**{*;} -keep public class com.alibaba.android.arouter.facade.**{*;}
-keep class * implements com.alibaba.android.arouter.facade.template.ISyringe{*;} -keep class * implements com.alibaba.android.arouter.facade.template.ISyringe{*;}
@ -308,6 +310,8 @@ rx.internal.util.atomic.LinkedQueueNode* consumerNode;
-keep class com.shayu.lib_google.**{*;} -keep class com.shayu.lib_google.**{*;}
-keep class com.shayu.lib_huawei.**{*;} -keep class com.shayu.lib_huawei.**{*;}
-keep class io.agora.**{*;}
-keep class com.qiniu.**{*;} -keep class com.qiniu.**{*;}
-keep class com.qiniu.**{public <init>();} -keep class com.qiniu.**{public <init>();}
-ignorewarnings -ignorewarnings

View File

@ -89,6 +89,11 @@
<!-- <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />--> <!-- <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />-->
<!-- <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />--> <!-- <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />-->
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" /> <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
<!-- 声网新增 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<queries> <queries>
<package android:name="com.twitter.android" /> <package android:name="com.twitter.android" />
<package android:name="jp.naver.line.android" /> <package android:name="jp.naver.line.android" />
@ -160,6 +165,12 @@
<meta-data <meta-data
android:name="firebase_crashlytics_collection_enabled" android:name="firebase_crashlytics_collection_enabled"
android:value="${isUploadLog}" /> android:value="${isUploadLog}" />
<meta-data
android:name="BUILD_TIME"
android:value="${buildTime}" />
<meta-data
android:name="SW_RELEASE_MODEL"
android:value="${swReleaseModel}" />
<meta-data <meta-data
android:name="com.openinstall.APP_KEY" android:name="com.openinstall.APP_KEY"
android:value="dnwyyj" /> android:value="dnwyyj" />

View File

@ -29,10 +29,12 @@ import com.google.gson.Gson;
import com.pandoralive.shayu.R; import com.pandoralive.shayu.R;
import com.shayu.phonelive.utils.LogUtils; import com.shayu.phonelive.utils.LogUtils;
import com.tencent.imsdk.v2.V2TIMGroupMemberInfo; import com.tencent.imsdk.v2.V2TIMGroupMemberInfo;
import com.yunbao.common.http.Data;
import com.tencent.imsdk.v2.V2TIMManager; import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMSimpleMsgListener; import com.tencent.imsdk.v2.V2TIMSimpleMsgListener;
import com.tencent.imsdk.v2.V2TIMUserInfo; import com.tencent.imsdk.v2.V2TIMUserInfo;
import com.yunbao.common.utils.MobclickAgent; import com.yunbao.common.utils.MobclickAgent;
import com.yunbao.common.manager.OpenAdManager;
import com.yalantis.ucrop.UCropActivity; import com.yalantis.ucrop.UCropActivity;
import com.yunbao.common.BuildConfig; import com.yunbao.common.BuildConfig;
import com.yunbao.common.CommonAppConfig; import com.yunbao.common.CommonAppConfig;
@ -59,9 +61,11 @@ import com.yunbao.common.utils.MessageSayHiNotifyManager;
import com.yunbao.common.utils.SpUtil; import com.yunbao.common.utils.SpUtil;
import com.yunbao.common.utils.WordUtil; import com.yunbao.common.utils.WordUtil;
import com.yunbao.live.activity.LiveActivity; import com.yunbao.live.activity.LiveActivity;
import com.yunbao.live.activity.SudGameActivity; import com.yunbao.live.activity.SudRyGameActivity;
import com.yunbao.live.activity.SudSwGameActivity;
import com.yunbao.live.socket.SocketReceiveBean; import com.yunbao.live.socket.SocketReceiveBean;
import com.yunbao.live.socket.SocketRyClient; import com.yunbao.live.socket.SocketRyClient;
import com.yunbao.live.socket.SocketSwClient;
import com.yunbao.live.utils.LiveImDeletUtil; import com.yunbao.live.utils.LiveImDeletUtil;
import com.yunbao.live.views.PortraitLiveManager; import com.yunbao.live.views.PortraitLiveManager;
import com.yunbao.live.views.RecommendLiveRoomProvider; import com.yunbao.live.views.RecommendLiveRoomProvider;
@ -82,6 +86,7 @@ import java.io.IOException;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date;
import java.util.List; import java.util.List;
import io.rong.imkit.config.RongConfigCenter; import io.rong.imkit.config.RongConfigCenter;
@ -111,7 +116,7 @@ public class AppContext extends CommonAppContext {
private static final class AdjustLifecycleCallbacks implements ActivityLifecycleCallbacks { private static final class AdjustLifecycleCallbacks implements ActivityLifecycleCallbacks {
@Override @Override
public void onActivityResumed(Activity activity) { public void onActivityResumed(@NonNull Activity activity) {
Log.e("打招呼定时器", "onActivityResumed: " + activity); Log.e("打招呼定时器", "onActivityResumed: " + activity);
MessageChatNotifyManager.getInstance().restart(activity); MessageChatNotifyManager.getInstance().restart(activity);
if (activity instanceof LiveActivity) { if (activity instanceof LiveActivity) {
@ -126,7 +131,11 @@ public class AppContext extends CommonAppContext {
MessageSayHiNotifyManager.getInstance().stop(); MessageSayHiNotifyManager.getInstance().stop();
return; return;
} }
if (activity instanceof SudGameActivity) { if (activity instanceof SudRyGameActivity) {
MessageSayHiNotifyManager.getInstance().stop();
return;
}
if (activity instanceof SudSwGameActivity) {
MessageSayHiNotifyManager.getInstance().stop(); MessageSayHiNotifyManager.getInstance().stop();
return; return;
} }
@ -157,7 +166,7 @@ public class AppContext extends CommonAppContext {
} }
@Override @Override
public void onActivityPaused(Activity activity) { public void onActivityPaused(@NonNull Activity activity) {
} }
@Override @Override
@ -172,10 +181,11 @@ public class AppContext extends CommonAppContext {
@Override @Override
public void onActivityDestroyed(@NonNull Activity activity) { public void onActivityDestroyed(@NonNull Activity activity) {
AppManager.getInstance().removeActivity(activity);
for (WeakReference<Activity> reference : activities) { for (WeakReference<Activity> reference : activities) {
if (reference.get() == activity) { if (reference.get() == activity) {
activities.remove(reference); activities.remove(reference);
return; break;
} }
} }
AppManager.getInstance().removeActivity(activity); AppManager.getInstance().removeActivity(activity);
@ -184,11 +194,12 @@ public class AppContext extends CommonAppContext {
@Override @Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
activities.add(new WeakReference<>(activity)); activities.add(new WeakReference<>(activity));
if(activity instanceof LoginActivity){ if (activity instanceof LoginActivity) {
AppManager.getInstance().clear(); AppManager.getInstance().clear();
} }
CrashSaveBean.getInstance().setActivitySize(activities); CrashSaveBean.getInstance().setActivitySize(activities);
AppManager.getInstance().addActivity(activity); AppManager.getInstance().addActivity(activity);
OpenAdManager.getInstance().dismiss();
} }
@Override @Override
@ -279,7 +290,7 @@ public class AppContext extends CommonAppContext {
RongcloudIMManager.addRongcloudIMOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() { RongcloudIMManager.addRongcloudIMOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() {
@Override @Override
public boolean onReceived(io.rong.imlib.model.Message message, int i, boolean b, boolean b1) { public boolean onReceived(io.rong.imlib.model.Message message, int i, boolean b, boolean b1) {
Log.e("wewe", message.getConversationType() + "112121"); Log.e("wewe", message.getConversationType() + "112121 " + message.getContent());
MessageIMManager.get(sInstance).getSystemForRongcloud(message); MessageIMManager.get(sInstance).getSystemForRongcloud(message);
//融云直播间聊天 //融云直播间聊天
Message msg = Message.obtain(); Message msg = Message.obtain();
@ -303,7 +314,30 @@ public class AppContext extends CommonAppContext {
} }
if (content.getContent().contains("_method_")) { if (content.getContent().contains("_method_")) {
msg.obj = content.getContent(); msg.obj = content.getContent();
//观众页面 String time = String.valueOf(new Date().getTime());
//声网
if (SocketSwClient.mSocketHandler != null && (TextUtils.equals("__system__", message.getTargetId()) || ("g" + PortraitLiveManager.liveID).contains(message.getTargetId()))) {
SocketSwClient.mSocketHandler.sendMessage(msg);
} else if (content.getContent().contains("LivePK_anchorStartLiveNotify")) {//开播通知
SocketReceiveBean received = JSON.parseObject(content.getContent(), SocketReceiveBean.class);
JSONObject map = received.getMsg().getJSONObject(0);
sendStartAnchorLive(map);
} else if (message.getTargetId().contains("v")) {
String contentJson = ((TextMessage) message.getContent()).getContent();
Log.e("wewe", contentJson);
SudGameSocketImEvent sudGameSocketImEvent = new Gson().fromJson(contentJson, SudGameSocketImEvent.class);
if (sudGameSocketImEvent.getMsg().isEmpty()) {
return false;
}
sudGameSocketImEvent.getMsg().get(0).setTime(time);
Bus.get().post(sudGameSocketImEvent);
}
//主播页面
if (TextUtils.isEmpty(PortraitLiveManager.liveID) && SocketSwClient.mSocketHandler != null) {
SocketSwClient.mSocketHandler.sendMessage(msg);
}
//融云
if (SocketRyClient.mSocketHandler != null && (TextUtils.equals("__system__", message.getTargetId()) || ("g" + PortraitLiveManager.liveID).contains(message.getTargetId()))) { if (SocketRyClient.mSocketHandler != null && (TextUtils.equals("__system__", message.getTargetId()) || ("g" + PortraitLiveManager.liveID).contains(message.getTargetId()))) {
SocketRyClient.mSocketHandler.sendMessage(msg); SocketRyClient.mSocketHandler.sendMessage(msg);
} else if (content.getContent().contains("LivePK_anchorStartLiveNotify")) {//开播通知 } else if (content.getContent().contains("LivePK_anchorStartLiveNotify")) {//开播通知
@ -314,6 +348,10 @@ public class AppContext extends CommonAppContext {
String contentJson = ((TextMessage) message.getContent()).getContent(); String contentJson = ((TextMessage) message.getContent()).getContent();
Log.e("wewe", contentJson); Log.e("wewe", contentJson);
SudGameSocketImEvent sudGameSocketImEvent = new Gson().fromJson(contentJson, SudGameSocketImEvent.class); SudGameSocketImEvent sudGameSocketImEvent = new Gson().fromJson(contentJson, SudGameSocketImEvent.class);
if (sudGameSocketImEvent.getMsg().isEmpty()) {
return false;
}
sudGameSocketImEvent.getMsg().get(0).setTime(time);
Bus.get().post(sudGameSocketImEvent); Bus.get().post(sudGameSocketImEvent);
} }
//主播页面 //主播页面

View File

@ -113,6 +113,7 @@ public class LauncherActivity extends AppCompatActivity implements View.OnClickL
res.updateConfiguration(config, res.getDisplayMetrics()); res.updateConfiguration(config, res.getDisplayMetrics());
return res; return res;
} }
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS); getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);
@ -144,7 +145,11 @@ public class LauncherActivity extends AppCompatActivity implements View.OnClickL
} }
}; };
mHandler.sendEmptyMessageDelayed(WHAT_GET_CONFIG, 1000); mHandler.sendEmptyMessageDelayed(WHAT_GET_CONFIG, 1000);
try {
LogUtil.uploadErrorLog(AppContext.sInstance); LogUtil.uploadErrorLog(AppContext.sInstance);
} catch (Exception e) {
e.printStackTrace();
}
SpUtil.getInstance().setBooleanValue("NOTIFICATION", NotificationManagerCompat.from(this).areNotificationsEnabled()); SpUtil.getInstance().setBooleanValue("NOTIFICATION", NotificationManagerCompat.from(this).areNotificationsEnabled());
} }
@ -229,7 +234,7 @@ public class LauncherActivity extends AppCompatActivity implements View.OnClickL
} else { } else {
checkUidAndToken(); checkUidAndToken();
} }
}else{ } else {
ToastUtil.show(getString(R.string.net_error)); ToastUtil.show(getString(R.string.net_error));
} }
} }

View File

@ -31,7 +31,7 @@ android {
versionName rootProject.ext.android.versionName versionName rootProject.ext.android.versionName
manifestPlaceholders = rootProject.ext.manifestPlaceholders manifestPlaceholders = rootProject.ext.manifestPlaceholders
ndk { ndk {
abiFilters "armeabi-v7a","arm64-v8a" abiFilters "armeabi-v7a","arm64-v8a","x86","x86_64"
} }
} }
buildTypes { buildTypes {

View File

@ -31,7 +31,7 @@ android {
versionName rootProject.ext.android.versionName versionName rootProject.ext.android.versionName
manifestPlaceholders = rootProject.ext.manifestPlaceholders manifestPlaceholders = rootProject.ext.manifestPlaceholders
ndk { ndk {
abiFilters "armeabi-v7a","arm64-v8a" abiFilters "armeabi-v7a","arm64-v8a","x86","x86_64"
} }
} }
aaptOptions { aaptOptions {

View File

@ -53,4 +53,10 @@ allprojects {
task clean(type: Delete) { task clean(type: Delete) {
delete rootProject.buildDir delete rootProject.buildDir
} }
ext {
IS_PUBLISH_LOCAL=true
LIB_VERSION="1.0.6"
AGORA_RTC_SDK= 'io.agora.rtc:agora-special-full:4.2.6.12'
// AGORA_RTC_SDK= "${rootProject.rootDir.absolutePath}/sdk"
// AGORA_RTC_SDK="io.agora.rtc:full-sdk:4.2.6"
}

View File

@ -1,5 +1,6 @@
apply plugin: 'com.android.library' apply plugin: 'com.android.library'
apply plugin: 'img-optimizer' apply plugin: 'img-optimizer'
apply plugin: 'kotlin-android'
android { android {
@ -13,7 +14,7 @@ android {
versionName rootProject.ext.android.versionName versionName rootProject.ext.android.versionName
manifestPlaceholders = rootProject.ext.manifestPlaceholders manifestPlaceholders = rootProject.ext.manifestPlaceholders
ndk { ndk {
abiFilters "armeabi-v7a", "arm64-v8a" abiFilters "armeabi-v7a", "arm64-v8a","x86","x86_64"
} }
javaCompileOptions { javaCompileOptions {
@ -248,6 +249,7 @@ dependencies {
api 'com.github.FlyJingFish:GradientTextView:1.2.4' api 'com.github.FlyJingFish:GradientTextView:1.2.4'
// //
api 'com.github.xiaohaibin:XBanner:androidx_v1.2.6' api 'com.github.xiaohaibin:XBanner:androidx_v1.2.6'
//SDK
//api 'io.agora.rtc:agora-special-full:4.2.6.245'
api 'com.xj.marqueeView:marqueeView:0.1.20'
} }

View File

@ -40,6 +40,7 @@ public class CommonAppConfig {
//是否为插件包模式 //是否为插件包模式
public static final boolean IS_PLUGIN_MODEL = getMetaDataBoolean("IS_PLUGIN_MODEL"); public static final boolean IS_PLUGIN_MODEL = getMetaDataBoolean("IS_PLUGIN_MODEL");
public static final String BUILD_TIME = getMetaDataString("BUILD_TIME"); public static final String BUILD_TIME = getMetaDataString("BUILD_TIME");
public static final boolean IS_SW_RELEASE = getMetaDataBoolean("SW_RELEASE_MODEL");
//外部sd卡 //外部sd卡
public static final String DCMI_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath(); public static final String DCMI_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
@ -79,7 +80,29 @@ public class CommonAppConfig {
public static boolean isGetNewWrap = false;//是否获取到新的包裹礼物 public static boolean isGetNewWrap = false;//是否获取到新的包裹礼物
public static int alert_time = 1; public static int alert_time = 1;
public static int alert_end_time = 1; public static int alert_end_time = 1;
public static String SWToken = ""; //声网Token
public static final String SWChannelPrefix = "g";
//测试服
public static final String SWAPPId_debug = "4cf0376582d742ac8a96778b25b1079e";
//正式服
public static final String SWAPPId = "d4a5879524d74c20a7bdd667b0f2ca21";
public static String getSwAppId() {
if (IS_SW_RELEASE) {
return SWAPPId;
} else {
return SWAPPId_debug;
}
}
/**
* 获取通道
*
* @return
*/
public static String getChannelName() {
return SWChannelPrefix + getInstance().getUid();
}
private CommonAppConfig() { private CommonAppConfig() {

View File

@ -269,7 +269,9 @@ public class Constants {
public static final String LIVE_PK_RANDOM_START="RankingStartRandomPK"; public static final String LIVE_PK_RANDOM_START="RankingStartRandomPK";
public static final int LIVE_SDK_KSY = 0;//金山推流 public static final int LIVE_SDK_KSY = 0;//金山推流
public static final int LIVE_SDK_TX = 1;//腾讯推流 public static final int LIVE_SDK_TX = 1;//腾讯推流
public static final int LIVE_SDK_SW = 2;//声网
public static final String LIVE_SDK_IS_SW = "liveSdkIsSw"; //是否是聲網
public static final int LINK_MIC_TYPE_NORMAL = 0;//观众与主播连麦 public static final int LINK_MIC_TYPE_NORMAL = 0;//观众与主播连麦
public static final int LINK_MIC_TYPE_ANCHOR = 1;//主播与主播连麦 public static final int LINK_MIC_TYPE_ANCHOR = 1;//主播与主播连麦

View File

@ -435,7 +435,7 @@ public class WebViewActivity extends AbsActivity {
LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class); LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class);
new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() { new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() {
@Override @Override
public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk) { public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk,boolean isSw) {
if (liveBean == null) { if (liveBean == null) {
return; return;
} }
@ -451,7 +451,7 @@ public class WebViewActivity extends AbsActivity {
} }
EventBus.getDefault().post(new LiveRoomChangeEvent(liveBean, liveType, Integer.parseInt(liveTypeVal))); EventBus.getDefault().post(new LiveRoomChangeEvent(liveBean, liveType, Integer.parseInt(liveTypeVal)));
} else { } else {
RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk)); RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk),isSw);
} }
finish(); finish();
} }

View File

@ -40,12 +40,15 @@ public class CustomDrawerPopupAdapter extends RecyclerView.Adapter {
private final int RIGHTS_INTERESTS = 4; private final int RIGHTS_INTERESTS = 4;
private final int RECOMMEND = 5; private final int RECOMMEND = 5;
private String liveId; private String liveId;
private boolean mIs_shengwang;
private List<AnchorRecommendItemModel> list = new ArrayList<>(); private List<AnchorRecommendItemModel> list = new ArrayList<>();
private List<CustomSidebarInfoModel> infoModels = new ArrayList<>(); private List<CustomSidebarInfoModel> infoModels = new ArrayList<>();
public CustomDrawerPopupAdapter(Context mContext) { public CustomDrawerPopupAdapter(Context mContext,boolean mIs_shengwang) {
this.mContext = mContext; this.mContext = mContext;
this.mIs_shengwang = mIs_shengwang;
} }
@ -114,6 +117,7 @@ public class CustomDrawerPopupAdapter extends RecyclerView.Adapter {
map.put("num", "9"); map.put("num", "9");
map.put("live_recommend", "sidebar"); map.put("live_recommend", "sidebar");
map.put("refresh", "1"); map.put("refresh", "1");
map.put(" is_shengwang", mIs_shengwang?"1":"0");
//推荐位 //推荐位
MainNetManager.get((Activity) mContext) MainNetManager.get((Activity) mContext)
.anchorRecommend(map, new com.yunbao.common.http.base.HttpCallback<AnchorRecommendModel>() { .anchorRecommend(map, new com.yunbao.common.http.base.HttpCallback<AnchorRecommendModel>() {

View File

@ -2,6 +2,7 @@ package com.yunbao.common.bean;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import com.yunbao.common.BuildConfig;
public class CheckLiveModel extends BaseModel { public class CheckLiveModel extends BaseModel {
@ -13,6 +14,16 @@ public class CheckLiveModel extends BaseModel {
private String typeMsg; private String typeMsg;
@SerializedName("live_sdk") @SerializedName("live_sdk")
private String liveSdk; private String liveSdk;
@SerializedName("is_shengwang")
private String isShengwang;
public String getIsShengwang() {
return isShengwang;
}
public void setIsShengwang(String isShengwang) {
this.isShengwang = isShengwang;
}
public static CheckLiveModel objectFromData(String str) { public static CheckLiveModel objectFromData(String str) {

View File

@ -2,6 +2,8 @@ package com.yunbao.common.bean;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import com.yunbao.common.BuildConfig;
import com.yunbao.common.utils.StringUtil;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -59,6 +61,9 @@ public class ConfigBean extends BaseModel {
private String txPlayUgcLicenceUrl;//腾讯短视频鉴权 private String txPlayUgcLicenceUrl;//腾讯短视频鉴权
private String txVideoUgcKey; private String txVideoUgcKey;
private String google_isup; private String google_isup;
private String sud_game_speech;
@SerializedName("is_return_user")//是否需要弹窗0否1是 @SerializedName("is_return_user")//是否需要弹窗0否1是
private String isReturnUser=""; private String isReturnUser="";
@SerializedName("popup_img_url")//弹窗图片地址 @SerializedName("popup_img_url")//弹窗图片地址
@ -182,6 +187,20 @@ public class ConfigBean extends BaseModel {
'}'; '}';
} }
public boolean isSw(){
return getSud_game_speech().equals("1");
}
@JSONField(name = "sud_game_speech")
public String getSud_game_speech() {
return sud_game_speech;
}
public void setSud_game_speech(String sud_game_speech) {
this.sud_game_speech = sud_game_speech;
}
@JSONField(name = "apk_ver") @JSONField(name = "apk_ver")
public String getVersion() { public String getVersion() {
return version; return version;

View File

@ -114,6 +114,17 @@ public class EnterRoomInfoModel extends BaseModel {
@SerializedName("gift_wall_lighten_total") @SerializedName("gift_wall_lighten_total")
private String giftWallLightenTotal; private String giftWallLightenTotal;
@SerializedName("connection_info")
private LivePkMicModel connectionInfo;
public LivePkMicModel getConnectionInfo() {
return connectionInfo;
}
public void setConnectionInfo(LivePkMicModel connectionInfo) {
this.connectionInfo = connectionInfo;
}
public String getGiftWallLightenNumber() { public String getGiftWallLightenNumber() {
return giftWallLightenNumber; return giftWallLightenNumber;
} }

View File

@ -41,6 +41,7 @@ public class EnterRoomNewModel extends BaseModel {
private SudGameDateModel sudGameDateModel; private SudGameDateModel sudGameDateModel;
@SerializedName("quick_gift_remaining_quantity") @SerializedName("quick_gift_remaining_quantity")
private int quickGiftRemainingQuantity;//剩余的小PD礼物数量 private int quickGiftRemainingQuantity;//剩余的小PD礼物数量
@SerializedName("if_viewing_duration_complete") @SerializedName("if_viewing_duration_complete")
private int ifViewingDurationComplete;//通过观看时间获取小PD礼物的次数 private int ifViewingDurationComplete;//通过观看时间获取小PD礼物的次数
@SerializedName("sendMoneyLongStatus") @SerializedName("sendMoneyLongStatus")

View File

@ -0,0 +1,36 @@
package com.yunbao.common.bean;
import com.google.gson.annotations.SerializedName;
public class LivePkMicModel extends BaseModel {
@SerializedName("pkuid")
private String pkuid;
@SerializedName("pkuname")
private String pkuname;
@SerializedName("pkuimg")
private String pkuimg;
public String getPkuid() {
return pkuid;
}
public void setPkuid(String pkuid) {
this.pkuid = pkuid;
}
public String getPkuname() {
return pkuname;
}
public void setPkuname(String pkuname) {
this.pkuname = pkuname;
}
public String getPkuimg() {
return pkuimg;
}
public void setPkuimg(String pkuimg) {
this.pkuimg = pkuimg;
}
}

View File

@ -2,7 +2,6 @@ package com.yunbao.common.bean;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import com.yunbao.common.CommonAppConfig; import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.manager.IMLoginManager;
import com.yunbao.common.utils.StringUtil; import com.yunbao.common.utils.StringUtil;
import java.text.ParseException; import java.text.ParseException;
@ -22,6 +21,8 @@ public class OpenAdModel extends BaseModel {
public static final int SHOW_ONE = 3;//3. 仅弹出一次 public static final int SHOW_ONE = 3;//3. 仅弹出一次
@SerializedName("id") @SerializedName("id")
private int id; private int id;
@SerializedName("popup_name")
private String name;
@SerializedName("popup_location") @SerializedName("popup_location")
private int type = TYPE_HOME; private int type = TYPE_HOME;
@SerializedName("activity_url") @SerializedName("activity_url")
@ -35,24 +36,27 @@ public class OpenAdModel extends BaseModel {
@SerializedName("popup_model") @SerializedName("popup_model")
private int model = MODEL_SQUARE; private int model = MODEL_SQUARE;
@SerializedName("start_show_time") @SerializedName("start_show_time")
private String startTime;//活动开始时间 private String startTime;//活动开始时间 1
@SerializedName("end_show_time") @SerializedName("end_show_time")
private String endTime;//活动结束时间 private String endTime;//活动结束时间 5
@SerializedName("popup_permission") @SerializedName("popup_permission")
private int permission; private int permission;
@SerializedName("popup_frequency") @SerializedName("popup_frequency")
private int showModel = SHOW_DEF;//显示模式1杀死程序后弹出 2指定时间内本机时间 31. 仅弹出一次 private int showModel = SHOW_DEF;//显示模式1杀死程序后弹出 2指定时间内本机时间 31. 仅弹出一次
@SerializedName("popup_frequency_time") @SerializedName("popup_frequency_time")
private String section = "0";// SHOW_DEF = 2 private String section = "0";// SHOW_DEF = 2 1
@SerializedName("popup_sort")
private int popupSort = 1;//弹框类型 1.图片 2.H5
@SerializedName("sort")
private int sort = 0;
public OpenAdModel() { public OpenAdModel() {
} }
public static OpenAdModel createTestData() { public static OpenAdModel createTestData() {
OpenAdModel model = new OpenAdModel(); OpenAdModel model = new OpenAdModel();
model.id=3; model.id = 3;
model.type=1; model.type = 1;
model.url = "/h5/GuildTournament/20230821/rank.html"; model.url = "/h5/GuildTournament/20230821/rank.html";
model.imageUrl = "https://ceshi.yaoulive.com/data/upload/20230913/1694589490.png"; model.imageUrl = "https://ceshi.yaoulive.com/data/upload/20230913/1694589490.png";
model.showTime = 10; model.showTime = 10;
@ -66,6 +70,30 @@ public class OpenAdModel extends BaseModel {
return model; return model;
} }
public int getPopupSort() {
return popupSort;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public void setPopupSort(int popupSort) {
this.popupSort = popupSort;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getShowModel() { public int getShowModel() {
return showModel; return showModel;
} }
@ -91,12 +119,13 @@ public class OpenAdModel extends BaseModel {
} }
public String getUrl() { public String getUrl() {
if (!url.startsWith("http://") || !url.startsWith("https://")) { if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = CommonAppConfig.HOST + url; url = CommonAppConfig.HOST + (url.startsWith("/") ? url : "/" + url);
} }
return url + "?t=" + System.currentTimeMillis() / 1000; return url;
} }
public String getOriginalUrl(){
public String getOriginalUrl() {
return url; return url;
} }
@ -198,6 +227,7 @@ public class OpenAdModel extends BaseModel {
public String toString() { public String toString() {
return "OpenAdModel{" + return "OpenAdModel{" +
"id=" + id + "id=" + id +
", name='" + name + '\'' +
", type=" + type + ", type=" + type +
", url='" + url + '\'' + ", url='" + url + '\'' +
", imageUrl='" + imageUrl + '\'' + ", imageUrl='" + imageUrl + '\'' +
@ -206,7 +236,10 @@ public class OpenAdModel extends BaseModel {
", model=" + model + ", model=" + model +
", startTime='" + startTime + '\'' + ", startTime='" + startTime + '\'' +
", endTime='" + endTime + '\'' + ", endTime='" + endTime + '\'' +
", permission='" + permission + '\'' + ", permission=" + permission +
", showModel=" + showModel +
", section='" + section + '\'' +
", sort=" + popupSort +
'}'; '}';
} }
} }

View File

@ -0,0 +1,23 @@
package com.yunbao.common.bean;
/**
* 声网token
*/
public class SwTokenModel extends BaseModel {
private String token;
public SwTokenModel() {
}
public SwTokenModel(String token) {
this.token = token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}

View File

@ -20,6 +20,7 @@ import com.google.gson.Gson;
import com.lxj.xpopup.XPopup; import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView; import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.enums.PopupPosition; import com.lxj.xpopup.enums.PopupPosition;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.R; import com.yunbao.common.R;
import com.yunbao.common.bean.CreateSudRoomModel; import com.yunbao.common.bean.CreateSudRoomModel;
import com.yunbao.common.bean.CustomSidebarChildModel; import com.yunbao.common.bean.CustomSidebarChildModel;
@ -153,8 +154,6 @@ public class CreateSudGamePopup extends BottomPopupView {
.asCustom(new SudGameListSelectPopup(getContext(), 4, customSidebarChildModels, interactionID)) .asCustom(new SudGameListSelectPopup(getContext(), 4, customSidebarChildModels, interactionID))
.show(); .show();
} }
} }
}); });
ViewClicksAntiShake.clicksAntiShake(findViewById(R.id.room_back), ViewClicksAntiShake.clicksAntiShake(findViewById(R.id.room_back),
@ -282,7 +281,11 @@ public class CreateSudGamePopup extends BottomPopupView {
public void onSuccess(CreateSudRoomModel data) { public void onSuccess(CreateSudRoomModel data) {
if (isHome) { if (isHome) {
dialog.dismiss(); dialog.dismiss();
RouteUtil.forwardSudGameActivity(new Gson().toJson(data)); if(CommonAppConfig.getInstance().getConfig().isSw()){
RouteUtil.forwardSwSudGameActivity(new Gson().toJson(data),true,isHome);
}else{
RouteUtil.forwardRySudGameActivity(new Gson().toJson(data),true,isHome);
}
} else { } else {
Bus.get().post(new LiveSudGamePopupShowOrHideEvent().setType(0).setCreateSudRoomModel(data)); Bus.get().post(new LiveSudGamePopupShowOrHideEvent().setType(0).setCreateSudRoomModel(data));

View File

@ -21,13 +21,14 @@ import com.yunbao.common.utils.AppManager;
import com.yunbao.common.utils.ToastUtil; import com.yunbao.common.utils.ToastUtil;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
public class DebugDialog { public class DebugDialog {
RecyclerView recyclerView; RecyclerView recyclerView;
HashMap<String, View> params; LinkedHashMap<String, View> params;
DebugDialogAdapter adapter; DebugDialogAdapter adapter;
private static DebugDialog debugDialog; private static DebugDialog debugDialog;
Context mContext; Context mContext;
@ -70,7 +71,7 @@ public class DebugDialog {
this.runnable = runnable; this.runnable = runnable;
if (params == null) { if (params == null) {
Log.i("debug弹窗", "DebugDialog: 初始化参数"); Log.i("debug弹窗", "DebugDialog: 初始化参数");
params = new HashMap<>(); params = new LinkedHashMap<>();
} }
init(); init();
} }
@ -103,6 +104,7 @@ public class DebugDialog {
} }
public void show() { public void show() {
if (recyclerView != null) return;
if (showPattern == ShowPattern.CURRENT_ACTIVITY) { if (showPattern == ShowPattern.CURRENT_ACTIVITY) {
createView(); createView();
return; return;
@ -138,7 +140,7 @@ public class DebugDialog {
EasyFloat.updateFloat("debug"); EasyFloat.updateFloat("debug");
} }
}); });
params.put("debug弹窗", textView); params.put("发包时间:" + CommonAppConfig.BUILD_TIME, textView);
params.put("发包时间:" + CommonAppConfig.BUILD_TIME, buildTime); params.put("发包时间:" + CommonAppConfig.BUILD_TIME, buildTime);
adapter.setParamMap(params); adapter.setParamMap(params);

View File

@ -1,7 +1,11 @@
package com.yunbao.common.dialog; package com.yunbao.common.dialog;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@ -9,12 +13,21 @@ import com.lxj.xpopup.XPopup;
import com.yunbao.common.R; import com.yunbao.common.R;
import com.yunbao.common.activity.WebViewActivity; import com.yunbao.common.activity.WebViewActivity;
import com.yunbao.common.bean.OpenAdModel; import com.yunbao.common.bean.OpenAdModel;
import com.yunbao.common.event.JavascriptInterfaceEvent;
import com.yunbao.common.glide.ImgLoader; import com.yunbao.common.glide.ImgLoader;
import com.yunbao.common.interfaces.OnItemClickListener; import com.yunbao.common.interfaces.OnItemClickListener;
import com.yunbao.common.manager.IMLoginManager;
import com.yunbao.common.utils.DpUtil;
import com.yunbao.common.utils.JavascriptInterfaceUtils;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.ScreenDimenUtil;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class OpenAdBottomDialogPopup extends AbsDialogPopupWindow { public class OpenAdBottomDialogPopup extends AbsDialogPopupWindow {
private ImageView mImageView;
private ImageView mClose; private ImageView mClose;
private LinearLayout contentLayout;
private OpenAdModel model; private OpenAdModel model;
private OnItemClickListener<OpenAdModel> mListener; private OnItemClickListener<OpenAdModel> mListener;
@ -27,6 +40,11 @@ public class OpenAdBottomDialogPopup extends AbsDialogPopupWindow {
@Override @Override
public void buildDialog(XPopup.Builder builder) { public void buildDialog(XPopup.Builder builder) {
builder.animationDuration(0); builder.animationDuration(0);
builder.hasShadowBg(true);
if(model.getPopupSort()==2){
builder.dismissOnTouchOutside(false);
builder.dismissOnBackPressed(false);
}
} }
@Override @Override
@ -51,8 +69,63 @@ public class OpenAdBottomDialogPopup extends AbsDialogPopupWindow {
@Override @Override
protected void onCreate() { protected void onCreate() {
super.onCreate(); super.onCreate();
mImageView = findViewById(R.id.img); contentLayout = findViewById(R.id.content_layout);
mClose = findViewById(R.id.close); mClose = findViewById(R.id.close);
if (model.getPopupSort() == 1) {
setImage();
} else {
setWeb();
}
mClose.setOnClickListener(v -> dismiss());
if (model.getShowTime() > 0) {
mClose.postDelayed(this::dismiss, model.getShowTime());
}
}
private void setWeb() {
WebView mWebView = new WebView(mContext);
mWebView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
mWebView.addJavascriptInterface(JavascriptInterfaceUtils.getInstance().setmContext((Activity) mContext, mWebView).setPageClose(true).setLiveZhuangBana(false), "androidObject");
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); // 是否允许JS打开新窗口
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
String appCachePath = mContext.getCacheDir().getAbsolutePath();
// mWebView.getSettings().setAppCachePath(appCachePath);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setUseWideViewPort(true); // 关键点
mWebView.getSettings().setAllowFileAccess(true); // 允许访问文件
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
L.e("H5-------->" + url);
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
}
});
String url=model.getUrl();
if(url.contains("?")){
url+="&uid="+ IMLoginManager.get(mContext).getUserInfo().getId()+"&token="+IMLoginManager.get(mContext).getUserInfo().getToken();
}else{
url+="?uid="+ IMLoginManager.get(mContext).getUserInfo().getId()+"&token="+IMLoginManager.get(mContext).getUserInfo().getToken();
}
mWebView.loadUrl(url);
contentLayout.addView(mWebView);
}
private void setImage() {
int width = ScreenDimenUtil.getInstance().getScreenWdith();
int height = (int) (width * 1.4);
ImageView mImageView = new ImageView(mContext);
mImageView.setLayoutParams(new LinearLayout.LayoutParams(width, height));
mImageView.setOnClickListener(v -> { mImageView.setOnClickListener(v -> {
WebViewActivity.forward(mContext, model.getUrl(), model.getType() != OpenAdModel.TYPE_HOME); WebViewActivity.forward(mContext, model.getUrl(), model.getType() != OpenAdModel.TYPE_HOME);
if (mListener != null) { if (mListener != null) {
@ -61,10 +134,12 @@ public class OpenAdBottomDialogPopup extends AbsDialogPopupWindow {
} }
dismiss(); dismiss();
}); });
mClose.setOnClickListener(v -> dismiss());
ImgLoader.display(mContext, model.getImageUrl(), mImageView); ImgLoader.display(mContext, model.getImageUrl(), mImageView);
if (model.getShowTime() > 0) { contentLayout.addView(mImageView);
mClose.postDelayed(this::dismiss, model.getShowTime());
} }
@Subscribe(threadMode = ThreadMode.MAIN)
public void onJavascriptInterfaceEvent(JavascriptInterfaceEvent event) {
} }
} }

View File

@ -1,24 +1,44 @@
package com.yunbao.common.dialog; package com.yunbao.common.dialog;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.graphics.Color;
import android.util.Log; import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.lxj.xpopup.XPopup; import com.lxj.xpopup.XPopup;
import com.lzf.easyfloat.enums.ShowPattern;
import com.yunbao.common.R; import com.yunbao.common.R;
import com.yunbao.common.activity.WebViewActivity; import com.yunbao.common.activity.WebViewActivity;
import com.yunbao.common.bean.OpenAdModel; import com.yunbao.common.bean.OpenAdModel;
import com.yunbao.common.event.JavascriptInterfaceEvent;
import com.yunbao.common.glide.ImgLoader; import com.yunbao.common.glide.ImgLoader;
import com.yunbao.common.interfaces.OnItemClickListener; import com.yunbao.common.interfaces.OnItemClickListener;
import com.yunbao.common.manager.IMLoginManager;
import com.yunbao.common.utils.DpUtil; import com.yunbao.common.utils.DpUtil;
import com.yunbao.common.utils.JavascriptInterfaceUtils;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.RouteUtil; import com.yunbao.common.utils.RouteUtil;
import com.yunbao.common.utils.ScreenDimenUtil; import com.yunbao.common.utils.ScreenDimenUtil;
import com.yunbao.common.utils.ToastUtil;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class OpenAdCenterDialogPopup extends AbsDialogFullScreenPopupWindow { public class OpenAdCenterDialogPopup extends AbsDialogFullScreenPopupWindow {
private ImageView mImageView; private ImageView mImageView;
private LinearLayout contentLayout;
private ImageView mClose; private ImageView mClose;
private OpenAdModel model; private OpenAdModel model;
private OnItemClickListener<OpenAdModel> mListener; private OnItemClickListener<OpenAdModel> mListener;
@ -39,7 +59,8 @@ public class OpenAdCenterDialogPopup extends AbsDialogFullScreenPopupWindow {
@Override @Override
public void buildDialog(XPopup.Builder builder) { public void buildDialog(XPopup.Builder builder) {
builder.hasShadowBg(false); builder.hasShadowBg(true);
builder.shadowBgColor(Color.parseColor("#80000000"));
builder.animationDuration(0); builder.animationDuration(0);
} }
@ -61,12 +82,103 @@ public class OpenAdCenterDialogPopup extends AbsDialogFullScreenPopupWindow {
@Override @Override
protected void onCreate() { protected void onCreate() {
super.onCreate(); super.onCreate();
Log.e("-----弹窗-----", "onCreate: 创建弹窗" ); Log.e("-----弹窗-----", "onCreate: 创建弹窗");
mImageView = findViewById(R.id.img); contentLayout = findViewById(R.id.content_layout);
mClose = findViewById(R.id.close); mClose = findViewById(R.id.close);
contentLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
boolean isShow = false;
@Override
public void onGlobalLayout() {
if (isShow)
return;
isShow = true;
int width = contentLayout.getWidth() - DpUtil.dp2px(20);
int height = (int) (width * 1.5);
if (model.getModel() == OpenAdModel.MODEL_SQUARE) {
height = (int) (width * 1.2);
}
Log.i("-----弹窗-----", "高度:" + height + " 宽度:" + width + " 屏幕宽度: " + ScreenDimenUtil.getInstance().getScreenWdith());
/*DebugDialog.getInstance(new DebugDialog.DebugDialogRunnable() {
@Override
public void run(DebugDialog dialog) {
dialog.setShowPattern(ShowPattern.ALL_TIME);
dialog.show();
int width = contentLayout.getWidth() - DpUtil.dp2px(10);
int height = (int) (width * 1.5);
if (model.getModel() == OpenAdModel.MODEL_SQUARE) {
height = (int) (width * 1.2);
}
Log.i("-----弹窗-----", "弹框debug高宽 高度:" + height + " 宽度:" + width);
dialog.setParams(model.getName() + "弹框高宽", "高度:" + height + " 宽度:" + width);
}
});*/
if (model.getPopupSort() == 1) {
setImage(model, width, height);
findViewById(R.id.layout).setOnClickListener(v -> dismiss()); findViewById(R.id.layout).setOnClickListener(v -> dismiss());
} else {
setWeb(model, width, height);
}
mClose.setOnClickListener(v -> dismiss());
if (model.getShowTime() > 0) {
mClose.postDelayed(OpenAdCenterDialogPopup.this::dismiss, model.getShowTime());
}
}
});
}
private void setWeb(OpenAdModel model, int width, int height) {
WebView mWebView = new WebView(mContext);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
params.gravity = Gravity.CENTER;
mWebView.setLayoutParams(params);
mWebView.addJavascriptInterface(JavascriptInterfaceUtils.getInstance().setmContext((Activity) mContext, mWebView).setPageClose(true).setLiveZhuangBana(false), "androidObject");
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); // 是否允许JS打开新窗口
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
String appCachePath = mContext.getCacheDir().getAbsolutePath();
// mWebView.getSettings().setAppCachePath(appCachePath);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setUseWideViewPort(true); // 关键点
mWebView.getSettings().setAllowFileAccess(true); // 允许访问文件
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
L.e("H5-------->" + url);
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
}
});
String url = model.getUrl();
if (url.contains("?")) {
url += "&uid=" + IMLoginManager.get(mContext).getUserInfo().getId() + "&token=" + IMLoginManager.get(mContext).getUserInfo().getToken();
} else {
url += "?uid=" + IMLoginManager.get(mContext).getUserInfo().getId() + "&token=" + IMLoginManager.get(mContext).getUserInfo().getToken();
}
Log.i("-----弹窗-----", "setWeb: " + url);
mWebView.loadUrl(url);
contentLayout.addView(mWebView);
}
private void setImage(OpenAdModel model, int width, int height) {
mImageView = new ImageView(mContext);
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
params.gravity = Gravity.CENTER;
mImageView.setLayoutParams(params);
mImageView.setOnClickListener(v -> { mImageView.setOnClickListener(v -> {
if("home_page_banner_battle".equals(model.getOriginalUrl())){ if ("home_page_banner_battle".equals(model.getOriginalUrl())) {
RouteUtil.forwardBattlePass(); RouteUtil.forwardBattlePass();
dismiss(); dismiss();
return; return;
@ -78,19 +190,12 @@ public class OpenAdCenterDialogPopup extends AbsDialogFullScreenPopupWindow {
} }
dismiss(); dismiss();
}); });
mClose.setOnClickListener(v -> dismiss());
ImgLoader.display(mContext, model.getImageUrl(), mImageView); ImgLoader.display(mContext, model.getImageUrl(), mImageView);
int width = ScreenDimenUtil.getInstance().getScreenWdith() - DpUtil.dp2px(40); contentLayout.addView(mImageView);
int height = (int) (width * 1.4);
if (model.getModel() == OpenAdModel.MODEL_SQUARE) {
height = width;
}
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) mImageView.getLayoutParams();
params.width = width;
params.height = height;
mImageView.setLayoutParams(params);
if (model.getShowTime() > 0) {
mClose.postDelayed(this::dismiss, model.getShowTime());
} }
@Subscribe(threadMode = ThreadMode.MAIN)
public void onJavascriptInterfaceEvent(JavascriptInterfaceEvent event) {
} }
} }

View File

@ -53,6 +53,15 @@ public class SudGameSocketImEvent extends BaseModel {
private String method; private String method;
@SerializedName("equipment") @SerializedName("equipment")
private String equipment; private String equipment;
private String time;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getAction() { public String getAction() {
return action; return action;

View File

@ -768,7 +768,7 @@ public class LiveHttpUtil {
* @param file 封面图片文件 * @param file 封面图片文件
* @param callback * @param callback
*/ */
public static void newcreateRoom(String title, int liveClassId, int type, int typeVal, File file, int clarityType, HttpCallback callback) { public static void newcreateRoom(String title, int liveClassId, int type, int typeVal, File file, int clarityType,boolean isSw, HttpCallback callback) {
PostRequest<JsonBean> request = HttpClient.getInstance().post("Live.createRoom2", LiveHttpConsts.CREATE_ROOM) PostRequest<JsonBean> request = HttpClient.getInstance().post("Live.createRoom2", LiveHttpConsts.CREATE_ROOM)
.params("title", title) .params("title", title)
@ -777,6 +777,7 @@ public class LiveHttpUtil {
.params("landscape", "2") .params("landscape", "2")
.params("class_type", "0") .params("class_type", "0")
.params("type_val", typeVal) .params("type_val", typeVal)
.params("is_shengwang",isSw?1:0)
.params("clarityType", clarityType); .params("clarityType", clarityType);
if (file != null) { if (file != null) {
request.params("file", file); request.params("file", file);
@ -821,6 +822,15 @@ public class LiveHttpUtil {
.execute(callback); .execute(callback);
} }
/**
* 获取是否是声网开播
* @param callback
*/
public static void getIsSw(HttpCallback callback) {
HttpClient.getInstance().get("Tx.setRtcFirm", "Tx.setRtcFirm")
.execute(callback);
}
/** /**
* 腾讯sdk 跟主播连麦时获取主播的低延时流 * 腾讯sdk 跟主播连麦时获取主播的低延时流
*/ */

View File

@ -84,6 +84,7 @@ import com.yunbao.common.bean.StarChallengeStatusModel;
import com.yunbao.common.bean.SudGameUserModel; import com.yunbao.common.bean.SudGameUserModel;
import com.yunbao.common.bean.SudRoomListModel; import com.yunbao.common.bean.SudRoomListModel;
import com.yunbao.common.bean.SudgameCodeModel; import com.yunbao.common.bean.SudgameCodeModel;
import com.yunbao.common.bean.SwTokenModel;
import com.yunbao.common.bean.UserAreaBean; import com.yunbao.common.bean.UserAreaBean;
import com.yunbao.common.bean.UserAvatarSelectBean; import com.yunbao.common.bean.UserAvatarSelectBean;
import com.yunbao.common.bean.UserBean; import com.yunbao.common.bean.UserBean;
@ -230,7 +231,7 @@ public interface PDLiveApi {
); );
/** /**
* 关注主播 * 关注主播···································································
* *
* @param liveuid * @param liveuid
* @return * @return
@ -1376,5 +1377,6 @@ public interface PDLiveApi {
@Query("to_uid")String toUid, @Query("to_uid")String toUid,
@Query("payload")String payload @Query("payload")String payload
); );
@GET("/api/public/?service=Tx.getShengwangToken")
Observable<ResponseModel<SwTokenModel>> getSwToken();
} }

View File

@ -84,6 +84,7 @@ import com.yunbao.common.bean.StarChallengeStatusModel;
import com.yunbao.common.bean.SudGameUserModel; import com.yunbao.common.bean.SudGameUserModel;
import com.yunbao.common.bean.SudRoomListModel; import com.yunbao.common.bean.SudRoomListModel;
import com.yunbao.common.bean.SudgameCodeModel; import com.yunbao.common.bean.SudgameCodeModel;
import com.yunbao.common.bean.SwTokenModel;
import com.yunbao.common.bean.UserAreaBean; import com.yunbao.common.bean.UserAreaBean;
import com.yunbao.common.bean.UserAvatarSelectBean; import com.yunbao.common.bean.UserAvatarSelectBean;
import com.yunbao.common.bean.UserBean; import com.yunbao.common.bean.UserBean;
@ -3949,6 +3950,30 @@ public class LiveNetManager {
} }
public void getSwToken( HttpCallback<SwTokenModel> callback) {
API.get().pdLiveApi(mContext)
.getSwToken()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<ResponseModel<SwTokenModel>>() {
@Override
public void accept(ResponseModel<SwTokenModel> listResponseModel) throws Exception {
if (callback != null) {
callback.onSuccess(listResponseModel.getData().getInfo());
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
if (callback != null) {
callback.onError(mContext.getString(R.string.net_error));
}
}
}).isDisposed();
}
/** /**
* 直播间取消网络请求 * 直播间取消网络请求
*/ */

View File

@ -96,27 +96,27 @@ public class MainNetManager {
}).isDisposed(); }).isDisposed();
} }
/** // /**
* 猜你喜欢 // * 猜你喜欢
* // *
* @param num 请求数量 // * @param num 请求数量
* @return // * @return
*/ // */
public void anchorRecommend(String num, HttpCallback<AnchorRecommendModel> httpCallback) { // public void anchorRecommend(String num, String is_shengwang,HttpCallback<AnchorRecommendModel> httpCallback) {
API.get().pdLiveApi(mContext).anchorRecommend(num) // API.get().pdLiveApi(mContext).anchorRecommend(num,is_shengwang)
.subscribeOn(Schedulers.io()) // .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) // .observeOn(AndroidSchedulers.mainThread())
.subscribe(anchorRecommendModelResponseModel -> { // .subscribe(anchorRecommendModelResponseModel -> {
if (httpCallback != null) { // if (httpCallback != null) {
AnchorRecommendModel model = anchorRecommendModelResponseModel.getData().getInfo(); // AnchorRecommendModel model = anchorRecommendModelResponseModel.getData().getInfo();
httpCallback.onSuccess(model); // httpCallback.onSuccess(model);
} // }
}, throwable -> { // }, throwable -> {
if (httpCallback != null) { // if (httpCallback != null) {
httpCallback.onError(throwable.getMessage()); // httpCallback.onError(throwable.getMessage());
} // }
}).isDisposed(); // }).isDisposed();
} // }
public void anchorRecommend(Map<String, Object> map, HttpCallback<AnchorRecommendModel> httpCallback) { public void anchorRecommend(Map<String, Object> map, HttpCallback<AnchorRecommendModel> httpCallback) {
API.get().pdLiveApi(mContext).anchorRecommend(map) API.get().pdLiveApi(mContext).anchorRecommend(map)
@ -140,11 +140,12 @@ public class MainNetManager {
* @param num 请求数量 * @param num 请求数量
* @return * @return
*/ */
public void anchorRecommendType(String num, HttpCallback<AnchorRecommendModel> httpCallback) { public void anchorRecommendType(String num, String is_shengwang,HttpCallback<AnchorRecommendModel> httpCallback) {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("num", num); map.put("num", num);
map.put("live_recommend", "slide"); map.put("live_recommend", "slide");
map.put("type", "1"); map.put("type", "1");
map.put(" is_shengwang", is_shengwang);
API.get().pdLiveApi(mContext).anchorRecommend(map) API.get().pdLiveApi(mContext).anchorRecommend(map)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())

View File

@ -1,25 +1,34 @@
package com.yunbao.common.manager; package com.yunbao.common.manager;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.util.Log; import android.util.Log;
import com.lzf.easyfloat.enums.ShowPattern;
import com.yunbao.common.CommonAppContext; import com.yunbao.common.CommonAppContext;
import com.yunbao.common.bean.OpenAdModel; import com.yunbao.common.bean.OpenAdModel;
import com.yunbao.common.dialog.DebugDialog;
import com.yunbao.common.dialog.OpenAdBottomDialogPopup; import com.yunbao.common.dialog.OpenAdBottomDialogPopup;
import com.yunbao.common.dialog.OpenAdCenterDialogPopup; import com.yunbao.common.dialog.OpenAdCenterDialogPopup;
import com.yunbao.common.http.base.HttpCallback; import com.yunbao.common.http.base.HttpCallback;
import com.yunbao.common.http.live.LiveNetManager; import com.yunbao.common.http.live.LiveNetManager;
import com.yunbao.common.interfaces.OnItemClickListener;
import com.yunbao.common.utils.AppManager;
import com.yunbao.common.utils.SpUtil; import com.yunbao.common.utils.SpUtil;
import com.yunbao.common.utils.StringUtil; import com.yunbao.common.utils.StringUtil;
import com.yunbao.common.utils.ToastUtil; import com.yunbao.common.utils.ToastUtil;
import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
public class OpenAdManager { public class OpenAdManager {
public static final int TYPE_HOME = 1; public static final int TYPE_HOME = 1;
@ -28,19 +37,34 @@ public class OpenAdManager {
private Map<Integer, Boolean> showMap; private Map<Integer, Boolean> showMap;
private List<OpenAdModel> list = null; private List<OpenAdModel> list = null;
private Handler handler = new Handler(Looper.getMainLooper()); private Handler handler = new Handler(Looper.getMainLooper());
private Map<Integer, AdRunnable> runnableMap = new HashMap<>(); private Map<Integer, AdRunnable> runnableMap = new LinkedHashMap<>();
private Map<AdRunnable, Integer> waitRunnableMap = new LinkedHashMap<>();//等待运行的弹窗
private int showType; private int showType;
private WeakReference<AdRunnable> runNowRunnable;
private static final boolean IS_QUEUE_SHOW = true;//是否按队列显示弹窗true就会等待上一个弹窗关闭后弹出false就按原逻辑顺序直接弹出
private OpenAdManager() { private OpenAdManager() {
showMap = new HashMap<>(); showMap = new HashMap<>();
init(false); init(false);
} }
public void reset() { public void close() {
dismiss(); dismiss();
clear();
}
public void clear() {
runnableMap.clear(); runnableMap.clear();
showMap.clear(); showMap.clear();
list.clear(); list.clear();
waitRunnableMap.clear();
list = null;
runNowRunnable = null;
}
public void reset() {
Log.i(TAG, "reset: ");
next();
} }
private static final class MInstanceHolder { private static final class MInstanceHolder {
@ -55,13 +79,14 @@ public class OpenAdManager {
if (list != null && list.isEmpty()) { if (list != null && list.isEmpty()) {
return; return;
} }
Context context = CommonAppContext.getTopActivity(); Context context = AppManager.getInstance().getMainActivity();
if (context == null) { if (context == null) {
context = CommonAppContext.sInstance; context = CommonAppContext.sInstance;
} }
if (context == null) { if (context == null) {
return; return;
} }
LiveNetManager.get(context).activityPopup(new HttpCallback<List<OpenAdModel>>() { LiveNetManager.get(context).activityPopup(new HttpCallback<List<OpenAdModel>>() {
@Override @Override
public void onSuccess(List<OpenAdModel> data) { public void onSuccess(List<OpenAdModel> data) {
@ -70,21 +95,34 @@ public class OpenAdManager {
list = new ArrayList<>(); list = new ArrayList<>();
return; return;
} }
Collections.sort(data, new AdListComparator());
list = data; list = data;
if (isShow) { if (isShow) {
if (showType == 0) {
show(TYPE_HOME, false); show(TYPE_HOME, false);
} else {
show(showType, false);
}
} }
} }
@Override @Override
public void onError(String error) { public void onError(String error) {
System.err.println("弹框列表:" + error); Log.e(TAG, "弹框列表:" + error);
} }
}); });
} }
private static long showTime=0; private static long showTime = 0;
private OnItemClickListener<String> onItemClickListener=new OnItemClickListener<String>() {
@Override
public void onItemClick(String bean, int position) {
}
};
public synchronized void show(int type, boolean isGuard) { public synchronized void show(int type, boolean isGuard) {
showType = type;
if(true){ if(true){
//潘多拉不需要彈窗 //潘多拉不需要彈窗
return; return;
@ -93,16 +131,32 @@ public class OpenAdManager {
init(true); init(true);
return; return;
} }
if(System.currentTimeMillis()-showTime<100){ Log.i(TAG, "show: 调用显示 " + type + " " + isGuard);
if (System.currentTimeMillis() - showTime < 100) {
return; return;
} }
showTime=System.currentTimeMillis(); /*DebugDialog.getInstance(new DebugDialog.DebugDialogRunnable() {
showType = type; @Override
public void run(DebugDialog dialog) {
dialog.setShowPattern(ShowPattern.ALL_TIME);
dialog.show();
onItemClickListener = new OnItemClickListener<String>() {
@Override
public void onItemClick(String bean, int position) {
dialog.setParams(bean, "剩余:" + position);
}
};
}
});*/
showTime = System.currentTimeMillis();
waitRunnableMap.clear();
runnableMap.clear();
runNowRunnable = null;
for (OpenAdModel model : list) { for (OpenAdModel model : list) {
if (model.getType() == type) { if (model.getType() == type) {
if (type == OpenAdModel.TYPE_LIVE && !model.userIsPermission(isGuard)) { /* if (type == OpenAdModel.TYPE_LIVE && !model.userIsPermission(isGuard)) {
continue; continue;
} }*/
if (model.getShowModel() == OpenAdModel.SHOW_ONE) { if (model.getShowModel() == OpenAdModel.SHOW_ONE) {
if (SpUtil.getInstance().getBooleanValue("open_ad_popup_" + model.getId())) { if (SpUtil.getInstance().getBooleanValue("open_ad_popup_" + model.getId())) {
continue; continue;
@ -126,13 +180,22 @@ public class OpenAdManager {
if (!isShow(model)) { if (!isShow(model)) {
Log.i(TAG, "show: " + model); Log.i(TAG, "show: " + model);
if (IS_QUEUE_SHOW) {
waitRunnableMap.put(new AdRunnable(model), model.getDelayShowTime());
} else {
handler.postDelayed(new AdRunnable(model), model.getDelayShowTime()); handler.postDelayed(new AdRunnable(model), model.getDelayShowTime());
}
} else { } else {
Log.i(TAG, "notshow: " + model); Log.i(TAG, "notshow: " + model);
} }
} }
} }
Log.i(TAG, "show: 循环完毕调用next");
if (IS_QUEUE_SHOW) {
onItemClickListener.onItemClick("接口返回需要展示的弹窗数:", waitRunnableMap.size());
next();
}
Log.i(TAG, "------------------------------"); Log.i(TAG, "------------------------------");
} }
@ -148,6 +211,9 @@ public class OpenAdManager {
} }
} }
runnableMap.clear(); runnableMap.clear();
if (runNowRunnable != null && runNowRunnable.get() != null) {
handler.removeCallbacks(runNowRunnable.get());
}
} }
private synchronized boolean isShow(OpenAdModel type) { private synchronized boolean isShow(OpenAdModel type) {
@ -157,11 +223,45 @@ public class OpenAdManager {
return false; return false;
} }
int getNowType() {
Activity lastActivity = AppManager.getInstance().getLastActivity();
if (lastActivity == null) {
return -1;
}
if (AppManager.getInstance().isLiveActivity()) {
return TYPE_LIVE;
} else if (AppManager.getInstance().isMainActivity()) {
return TYPE_HOME;
}
return -2;
}
void next() {
Log.i(TAG, "next: 剩余数" + waitRunnableMap.size());
if (waitRunnableMap.isEmpty()) return;
for (AdRunnable next : waitRunnableMap.keySet()) {
Log.i(TAG, "next: " + next.model);
if (next.model.getType() == getNowType()) {
Integer i = waitRunnableMap.get(next);
if (i == null) {
i = 0;
}
onItemClickListener.onItemClick("当前加载id:" + next.model.getId() + " " + next.model.getName() + " 延迟展示时间:" + i, (waitRunnableMap.size() - 1));
handler.postDelayed(next, i);
return;
}
}
}
private class AdRunnable implements Runnable { private class AdRunnable implements Runnable {
OpenAdModel model; OpenAdModel model;
AdRunnable runnable;
public AdRunnable(OpenAdModel model) { public AdRunnable(OpenAdModel model) {
this.model = model; this.model = model;
this.runnable = this;
runNowRunnable = new WeakReference<>(this);
runnableMap.put(model.getId(), this); runnableMap.put(model.getId(), this);
} }
@ -174,37 +274,101 @@ public class OpenAdManager {
Log.i(TAG, "run: " + model); Log.i(TAG, "run: " + model);
if (model == null) { if (model == null) {
ToastUtil.showDebug("model为空"); ToastUtil.showDebug("model为空");
if (onItemClickListener != null) {
onItemClickListener.onItemClick("", -2);
}
return; return;
} }
if (!model.isInTime()) { if (!model.isInTime()) {
ToastUtil.showDebug("不在展示时间内:" + model.getStartTime() + "|" + model.getEndTime()); ToastUtil.showDebug("不在展示时间内:" + model.getStartTime() + "|" + model.getEndTime());
if (onItemClickListener != null) {
onItemClickListener.onItemClick("", -2);
}
return; return;
} }
if (isShow(model)) { if (isShow(model)) {
ToastUtil.showDebug(model.getId() + "|model展示过了"); ToastUtil.showDebug(model.getId() + "|model展示过了");
if (onItemClickListener != null) {
onItemClickListener.onItemClick("", -2);
}
return; return;
} }
if (model.getType() != showType) { if (model.getType() != showType) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick("", -2);
}
return; return;
} }
if(isShow(model)){ if (isShow(model)) {
Log.i(TAG,"展示过:"+model); Log.i(TAG, "展示过:" + model);
if (onItemClickListener != null) {
onItemClickListener.onItemClick("", -2);
}
return; return;
} }
if (model.getType() == OpenAdModel.TYPE_HOME && !AppManager.getInstance().isMainActivity()) {
Log.i(TAG, "首页类型弹窗,但当前不是首页");
if (onItemClickListener != null) {
onItemClickListener.onItemClick("", -2);
}
dismiss();
return;
}
if (model.getType() == TYPE_LIVE && !AppManager.getInstance().isLiveActivity()) {
Log.i(TAG, "直播类型弹窗,但当前不是直播");
if (onItemClickListener != null) {
onItemClickListener.onItemClick("", -2);
}
dismiss();
return;
}
showMap.put(model.getId(), true); showMap.put(model.getId(), true);
if (model.getShowModel() == OpenAdModel.SHOW_DIY) { if (model.getShowModel() == OpenAdModel.SHOW_DIY) {
String nextTime= String.valueOf(System.currentTimeMillis() + (Long.parseLong(model.getSection()) * 60 * 1000)); String nextTime = String.valueOf(System.currentTimeMillis() + (Long.parseLong(model.getSection()) * 60 * 1000));
SpUtil.setStringValue("open_ad_popup_time_" + model.getId(), nextTime); SpUtil.setStringValue("open_ad_popup_time_" + model.getId(), nextTime);
Log.i(TAG, "run: 下一次展示时间:"+nextTime+" | "+model.getSection()); Log.i(TAG, "run: 下一次展示时间:"+nextTime+" | "+model.getSection());
showMap.remove(model.getId()); showMap.remove(model.getId());
} }
if (model.getModel() == OpenAdModel.MODEL_BOTTOM) { if (model.getModel() == OpenAdModel.MODEL_BOTTOM) {
new OpenAdBottomDialogPopup(CommonAppContext.getTopActivity(), model).setListener((bean, position) -> { new OpenAdBottomDialogPopup(AppManager.getInstance().getLastActivity(), model).setListener((bean, position) -> {
Log.i(TAG, "run: 弹框回调:" + position + " id = " + model.getId());
if (IS_QUEUE_SHOW) {
removeList(bean);
if (position == 0) {
next();
}
}
}).showDialog(); }).showDialog();
} else { } else {
new OpenAdCenterDialogPopup(CommonAppContext.getTopActivity(), model).setListener((bean, position) -> { new OpenAdCenterDialogPopup(AppManager.getInstance().getLastActivity(), model).setListener((bean, position) -> {
Log.i(TAG, "run: 弹框回调:" + position + " id = " + model.getId());
if (IS_QUEUE_SHOW) {
removeList(bean);
if (position == 0) {
next();
}
}
}).showDialog(); }).showDialog();
} }
} }
void removeList(OpenAdModel model) {
Log.i(TAG, "removeList: " + model);
for (AdRunnable next : waitRunnableMap.keySet()) {
if (next.model.getId() == model.getId()) {
waitRunnableMap.remove(next);
return;
}
}
}
}
private class AdListComparator implements Comparator<OpenAdModel> {
@Override
public int compare(OpenAdModel openAdModel, OpenAdModel t1) {
return openAdModel.getSort() - t1.getSort();
}
} }
} }

View File

@ -343,7 +343,7 @@ public class RandomPkManager {
@Override @Override
public void onError(String error) { public void onError(String error) {
ToastUtil.show(WordUtil.isNewZh()?"抱歉!出錯了!":"i \\'m sorry! An error occurred"); //ToastUtil.show(WordUtil.isNewZh()?"抱歉!出錯了!":"i \\'m sorry! An error occurred");
} }
}); });
} }

View File

@ -38,7 +38,7 @@ import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message; import io.rong.imlib.model.Message;
import io.rong.message.TextMessage; import io.rong.message.TextMessage;
public class GameMicManager { public class GameRyMicManager {
MeetingCallback mMeetingCallback = null; MeetingCallback mMeetingCallback = null;
private RCRTCRoom mRtcRoom = null; private RCRTCRoom mRtcRoom = null;
private String mRoomID = ""; private String mRoomID = "";
@ -367,7 +367,7 @@ public class GameMicManager {
RCRTCEngine.getInstance().joinRoom("v" + roomId, roomConfig, new IRCRTCResultDataCallback<RCRTCRoom>() { RCRTCEngine.getInstance().joinRoom("v" + roomId, roomConfig, new IRCRTCResultDataCallback<RCRTCRoom>() {
@Override @Override
public void onSuccess(final RCRTCRoom rcrtcRoom) { public void onSuccess(final RCRTCRoom rcrtcRoom) {
GameMicManager.this.mRtcRoom = rcrtcRoom; GameRyMicManager.this.mRtcRoom = rcrtcRoom;
// 注册房间回调 // 注册房间回调
rcrtcRoom.registerRoomListener(roomEventsListener); rcrtcRoom.registerRoomListener(roomEventsListener);
try { try {

View File

@ -0,0 +1,569 @@
package com.yunbao.common.manager.imrongcloud;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yunbao.common.CommonAppContext;
import com.yunbao.common.bean.IMLoginModel;
import com.yunbao.common.bean.SudGameChatImModel;
import com.yunbao.common.bean.SudGameUserModel;
import com.yunbao.common.event.SudGameSocketImEvent;
import com.yunbao.common.manager.IMLoginManager;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.utils.WordUtil;
import java.util.ArrayList;
import java.util.List;
import cn.rongcloud.rtc.api.RCRTCEngine;
import cn.rongcloud.rtc.api.RCRTCRemoteUser;
import cn.rongcloud.rtc.api.RCRTCRoom;
import cn.rongcloud.rtc.api.RCRTCRoomConfig;
import cn.rongcloud.rtc.api.callback.IRCRTCResultCallback;
import cn.rongcloud.rtc.api.callback.IRCRTCResultDataCallback;
import cn.rongcloud.rtc.api.callback.IRCRTCRoomEventsListener;
import cn.rongcloud.rtc.api.stream.RCRTCInputStream;
import cn.rongcloud.rtc.base.RCRTCParamsType;
import cn.rongcloud.rtc.base.RCRTCRoomType;
import cn.rongcloud.rtc.base.RTCErrorCode;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.IRongCoreCallback;
import io.rong.imlib.IRongCoreEnum;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.chatroom.base.RongChatRoomClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;
public class GameSwMicManager {
MeetingCallback mMeetingCallback = null;
private RCRTCRoom mRtcRoom = null;
private String mRoomID = "";
public void setmRoomID(String mRoomID) {
this.mRoomID = mRoomID;
}
private final IRCRTCRoomEventsListener roomEventsListener = new IRCRTCRoomEventsListener() {
/**
* 房间内用户发布资源
*
* @param rcrtcRemoteUser 远端用户
* @param list 发布的资源
*/
@Override
public void onRemoteUserPublishResource(RCRTCRemoteUser rcrtcRemoteUser, final List<RCRTCInputStream> list) {
// subscribeAVStream();
}
@Override
public void onRemoteUserMuteAudio(RCRTCRemoteUser rcrtcRemoteUser, RCRTCInputStream rcrtcInputStream, boolean b) {
}
@Override
public void onRemoteUserMuteVideo(RCRTCRemoteUser rcrtcRemoteUser, RCRTCInputStream rcrtcInputStream, boolean b) {
}
@Override
public void onRemoteUserUnpublishResource(RCRTCRemoteUser rcrtcRemoteUser, List<RCRTCInputStream> list) {
}
/**
* 用户加入房间
*
* @param rcrtcRemoteUser 远端用户
*/
@Override
public void onUserJoined(final RCRTCRemoteUser rcrtcRemoteUser) {
try {
getView().onUserJoined(rcrtcRemoteUser);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
/**
* 用户离开房间
*
* @param rcrtcRemoteUser 远端用户
*/
@Override
public void onUserLeft(RCRTCRemoteUser rcrtcRemoteUser) {
try {
getView().onUserLeft(rcrtcRemoteUser);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
@Override
public void onUserOffline(RCRTCRemoteUser rcrtcRemoteUser) {
}
@Override
public void onPublishLiveStreams(List<RCRTCInputStream> list) {
}
@Override
public void onUnpublishLiveStreams(List<RCRTCInputStream> list) {
}
/**
* 自己退出房间 例如断网退出等
* @param i 状态码
*/
@Override
public void onLeaveRoom(int i) {
}
};
protected MeetingCallback getView() {
if (mMeetingCallback == null) {
throw new IllegalStateException("view is not attached");
} else {
return mMeetingCallback;
}
}
public void attachView(MeetingCallback callback) {
mMeetingCallback = callback;
}
public void detachView() {
mMeetingCallback = null;
}
/**
* 主动订阅远端用户发布的流
* 视频流需要用户设置用于显示载体的videoview
*/
public void subscribeAVStream() {
if (mRtcRoom == null || mRtcRoom.getRemoteUsers() == null) {
return;
}
final List<RCRTCInputStream> inputStreams = new ArrayList<>();
for (final RCRTCRemoteUser remoteUser : mRtcRoom.getRemoteUsers()) {
if (remoteUser.getStreams().size() == 0) {
continue;
}
inputStreams.addAll(remoteUser.getStreams());
}
if (inputStreams.size() == 0) {
return;
}
mRtcRoom.getLocalUser().subscribeStreams(inputStreams, new IRCRTCResultCallback() {
@Override
public void onSuccess() {
try {
getView().onSubscribeSuccess(inputStreams);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
@Override
public void onFailed(RTCErrorCode errorCode) {
try {
getView().onSubscribeFailed();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
});
}
public void refreshStreams(List<SudGameUserModel> personList) {
final List<RCRTCInputStream> inputStreams = new ArrayList<>();
if(mRtcRoom!=null){
for (SudGameUserModel sudGameUserModel : personList) {
List<RCRTCRemoteUser> rcrtcRemoteUsers = mRtcRoom.getRemoteUsers();
for (RCRTCRemoteUser rcrtcRemoteUser : rcrtcRemoteUsers) {
if (TextUtils.equals(rcrtcRemoteUser.getUserId(), String.valueOf(sudGameUserModel.getId()))) {
for (RCRTCInputStream rcrtcInputStream : rcrtcRemoteUser.getStreams()) {
rcrtcInputStream.mute(sudGameUserModel.getMicStatus() == 3);
}
inputStreams.addAll(rcrtcRemoteUser.getStreams());
}
}
}
if (inputStreams.size() == 0) {
return;
}
mRtcRoom.getLocalUser().subscribeStreams(inputStreams, new IRCRTCResultCallback() {
@Override
public void onSuccess() {
try {
getView().onSubscribeSuccess(inputStreams);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
@Override
public void onFailed(RTCErrorCode errorCode) {
try {
getView().onSubscribeFailed();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
});
}
}
public void refreshStreams(String userID, boolean mute, int position) {
final List<RCRTCInputStream> inputStreams = new ArrayList<>();
List<RCRTCRemoteUser> rcrtcRemoteUsers = mRtcRoom.getRemoteUsers();
for (RCRTCRemoteUser rcrtcRemoteUser : rcrtcRemoteUsers) {
if (TextUtils.equals(rcrtcRemoteUser.getUserId(), String.valueOf(userID))) {
for (RCRTCInputStream rcrtcInputStream : rcrtcRemoteUser.getStreams()) {
rcrtcInputStream.mute(mute);
}
inputStreams.addAll(rcrtcRemoteUser.getStreams());
}
}
if (inputStreams.size() == 0) {
return;
}
mRtcRoom.getLocalUser().subscribeStreams(inputStreams, new IRCRTCResultCallback() {
@Override
public void onSuccess() {
try {
getView().onSubscribeSuccess(userID, mute, position);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
@Override
public void onFailed(RTCErrorCode errorCode) {
try {
getView().onSubscribeFailed(userID);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
});
}
public void unPublishStreams() {
if (mRtcRoom == null) {
return;
}
mRtcRoom.getLocalUser().unpublishStream(RCRTCEngine.getInstance().getDefaultAudioStream(), new IRCRTCResultCallback() {
@Override
public void onSuccess() {
try {
getView().onUnPublishStreamsSuccess();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
@Override
public void onFailed(RTCErrorCode errorCode) {
try {
getView().onUnPublishStreamsFailed();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
});
}
/**
* 发布默认流
*/
public void publishDefaultAVStream() {
if (mRtcRoom == null) {
return;
}
mRtcRoom.getLocalUser().publishStream(RCRTCEngine.getInstance().getDefaultAudioStream(), new IRCRTCResultCallback() {
@Override
public void onSuccess() {
try {
getView().onPublishSuccess();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
@Override
public void onFailed(RTCErrorCode rtcErrorCode) {
try {
getView().onPublishFailed();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
});
}
/**
* 配置rtc sdk
*/
public void config(Context context) {
// RCRTCConfig.Builder configBuilder = RCRTCConfig.Builder.create();
// // 是否硬解码
// configBuilder.enableHardwareDecoder(true);
// // 是否硬编码
// configBuilder.enableHardwareEncoder(true);
//
// // init 需结合 uninit 使用否则有些配置无法重新初始化
// RCRTCEngine.getInstance().unInit();
// RCRTCEngine.getInstance().init(context, configBuilder.build());
// RCRTCVideoStreamConfig.Builder videoConfigBuilder = RCRTCVideoStreamConfig.Builder.create();
// // 设置分辨率
// videoConfigBuilder.setVideoResolution(RCRTCParamsType.RCRTCVideoResolution.RESOLUTION_720_1280);
// // 设置帧率
// videoConfigBuilder.setVideoFps(RCRTCParamsType.RCRTCVideoFps.Fps_30);
// /**
// * 设置最小码率可根据分辨率RCRTCVideoResolution设置
// * {@link RCRTCParamsType.RCRTCVideoResolution)}
// */
// videoConfigBuilder.setMinRate(250);
// /**
// * 设置最大码率可根据分辨率RCRTCVideoResolution设置
// * {@link RCRTCParamsType.RCRTCVideoResolution)}
// */
// videoConfigBuilder.setMaxRate(2200);
// RCRTCEngine.getInstance().getDefaultVideoStream().setVideoConfig(videoConfigBuilder.build());
//打开扬声器
RCRTCEngine.getInstance().enableSpeaker(true);
// 启用耳返功能
RCRTCEngine.getInstance().getDefaultAudioStream().enableEarMonitoring(true);
RCRTCEngine.getInstance().getDefaultAudioStream().setMicrophoneDisable(false);
RCRTCEngine.getInstance().getDefaultAudioStream().setAudioQuality(RCRTCParamsType.AudioQuality.MUSIC_HIGH, RCRTCParamsType.AudioScenario.MUSIC_CHATROOM);
}
public void joinRoom(String roomId, boolean imOff) {
mRoomID = roomId;
if (imOff) {
RCRTCRoomConfig roomConfig = RCRTCRoomConfig.Builder.create()
// 根据实际场景选择音视频直播LIVE_AUDIO_VIDEO 或音频直播LIVE_AUDIO
.setRoomType(RCRTCRoomType.MEETING)
.build();
RCRTCEngine.getInstance().joinRoom("v" + roomId, roomConfig, new IRCRTCResultDataCallback<RCRTCRoom>() {
@Override
public void onSuccess(final RCRTCRoom rcrtcRoom) {
GameSwMicManager.this.mRtcRoom = rcrtcRoom;
// 注册房间回调
rcrtcRoom.registerRoomListener(roomEventsListener);
try {
getView().onJoinRoomSuccess(rcrtcRoom);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
@Override
public void onFailed(RTCErrorCode rtcErrorCode) {
try {
getView().onJoinRoomFailed(rtcErrorCode);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
});
}
RongChatRoomClient.getInstance().joinChatRoom("v" + roomId, -1, new IRongCoreCallback.OperationCallback() {
@Override
public void onSuccess() {
Log.i("tx", "加入成功");
enterRoom();
}
@Override
public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {
Log.i("tx", "加入" + "失败" + coreErrorCode);
if (WordUtil.isNewZh()) {
ToastUtil.show("網絡不佳無法連接,請重新進入");
} else {
ToastUtil.show("The network is not connected, please re-enter");
}
}
});
}
public void leaveRoom() {
RCRTCEngine.getInstance().leaveRoom(new IRCRTCResultCallback() {
@Override
public void onFailed(RTCErrorCode rtcErrorCode) {
}
@Override
public void onSuccess() {
}
});
RongChatRoomClient.getInstance().quitChatRoom("v" + mRoomID, new IRongCoreCallback.OperationCallback() {
@Override
public void onSuccess() {
Log.i("tx", "退出成功");
}
@Override
public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {
Log.i("tx", "退出" + "" + coreErrorCode);
}
});
}
String lastTime = "";
/**
* 处理游戏房Im消息
*/
public void processingMessage(SudGameSocketImEvent socketImModel) {
List<SudGameSocketImEvent.MsgDTO> msgDTOS = socketImModel.getMsg();
if (msgDTOS.isEmpty()) return;
SudGameSocketImEvent.MsgDTO msgDTO = msgDTOS.get(0);
if(lastTime.equals(msgDTO.getTime())){
return;
}
lastTime = msgDTO.getTime();
//正常文字消息
if (TextUtils.equals(msgDTO.getMethod(), "SendMsg")) {
getView().insertItem(new SudGameChatImModel().setWelcomMessage(false).setNickname(msgDTO.getUname()).setTextMessage(msgDTO.getCt()));
} else if (TextUtils.equals(msgDTO.getMethod(), "welcomMessage")) {
// 欢迎用户名进入房间 Welcome (username) to the room
StringBuffer stringBuffer = new StringBuffer();
if (WordUtil.isNewZh()) {
stringBuffer.append("歡迎 ").append(msgDTO.getCt()).append(" 進入房間");
} else {
stringBuffer.append("Welcome ").append(msgDTO.getCt()).append(" to enter the room");
}
getView().insertItem(new SudGameChatImModel().setWelcomMessage(true).setNickname(msgDTO.getCt()).setTextMessage(stringBuffer.toString()));
} else if (TextUtils.equals(msgDTO.getMethod(), "sudGameRoomVoiceList")) {
List<SudGameUserModel> personList = new Gson().fromJson(msgDTO.getCt(), new TypeToken<List<SudGameUserModel>>() {
}.getType());
getView().refreshSudGameUserList(personList);
refreshStreams(personList);
}
}
private void sendChatMessage(String textMessage, String method) {
IMLoginModel loginModel = IMLoginManager.get(CommonAppContext.sInstance.getApplicationContext()).getUserInfo();
SudGameSocketImEvent sudGameSocketImEvent = new SudGameSocketImEvent();
sudGameSocketImEvent.setRetcode("000000");
sudGameSocketImEvent.setRetmsg("ok");
SudGameSocketImEvent.MsgDTO msgDTO = new SudGameSocketImEvent.MsgDTO();
msgDTO.setAction("0")
.setCt(textMessage)
.setEquipment("app")
.setUid(String.valueOf(loginModel.getId()))
.setMethod(method)
.setUname(loginModel.getUserNicename())
.setRoomnum(mRoomID);
List<SudGameSocketImEvent.MsgDTO> msgDTOS = new ArrayList<>();
msgDTOS.add(msgDTO);
sudGameSocketImEvent.setMsg(msgDTOS);
Conversation.ConversationType conversationType = Conversation.ConversationType.CHATROOM;
TextMessage messageContent = TextMessage.obtain(new Gson().toJson(sudGameSocketImEvent));
Message message = Message.obtain("v" + mRoomID, conversationType, messageContent);
RongcloudIMManager.sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() {
@Override
public void onAttached(Message message) {
}
@Override
public void onSuccess(Message message) {
Log.i("tx", "发送成功");
String contentJson = ((TextMessage) message.getContent()).getContent();
Log.e("wewe", contentJson);
SudGameSocketImEvent sudGameSocketImEvent = new Gson().fromJson(contentJson, SudGameSocketImEvent.class);
sudGameSocketImEvent.getMsg().get(0).setTime("11");
processingMessage(sudGameSocketImEvent);
}
@Override
public void onError(Message message, RongIMClient.ErrorCode errorCode) {
Log.i("tx", "发送成功" + errorCode.toString());
}
});
}
/**
* 发送聊天信息
*
* @param textMessage
*/
public void sendMessage(String textMessage) {
sendChatMessage(textMessage, "SendMsg");
}
/**
* 进房间
*/
public void enterRoom() {
IMLoginModel loginModel = IMLoginManager.get(CommonAppContext.sInstance.getApplicationContext()).getUserInfo();
sendChatMessage(loginModel.getUserNicename(), "welcomMessage");
}
/**
* activity相关回调
*/
public interface MeetingCallback {
void onJoinRoomSuccess(RCRTCRoom rcrtcRoom);
void onJoinRoomFailed(RTCErrorCode rtcErrorCode);
void onPublishSuccess();
void onPublishFailed();
void onUnPublishStreamsSuccess();
void onUnPublishStreamsFailed();
void onSubscribeSuccess(List<RCRTCInputStream> inputStreamList);
void onSubscribeFailed();
void onSubscribeSuccess(String userID, boolean mute, int position);
void onSubscribeFailed(String userID);
void onUserJoined(RCRTCRemoteUser rcrtcRemoteUser);
void onUserLeft(RCRTCRemoteUser rcrtcRemoteUser);
void insertItem(SudGameChatImModel sudGameChatImModel);
void refreshSudGameUserList(List<SudGameUserModel> personList);
}
}

View File

@ -101,7 +101,7 @@ public class MessageChatCardItemProvider extends BaseMessageItemProvider<Message
LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class); LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class);
new LiveRoomCheckLivePresenter(AppManager.getInstance().getLastActivity(), liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() { new LiveRoomCheckLivePresenter(AppManager.getInstance().getLastActivity(), liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() {
@Override @Override
public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk) { public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk,boolean isSw) {
if (liveBean == null) { if (liveBean == null) {
return; return;
} }
@ -116,7 +116,7 @@ public class MessageChatCardItemProvider extends BaseMessageItemProvider<Message
activity.finish(); activity.finish();
} }
} else { } else {
RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk)); RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk),isSw);
} }
} }

View File

@ -4,6 +4,7 @@ import android.app.Activity;
import android.util.Log; import android.util.Log;
import com.yunbao.common.BuildConfig; import com.yunbao.common.BuildConfig;
import com.yunbao.common.manager.OpenAdManager;
import java.util.Stack; import java.util.Stack;
@ -51,6 +52,24 @@ public class AppManager {
public void clear() { public void clear() {
activityStack.clear(); activityStack.clear();
OpenAdManager.getInstance().clear();
}
public boolean isMainActivity() {
Activity lastActivity = getLastActivity();
if (lastActivity == null) {
return false;
}
return lastActivity.getClass().getSimpleName().contains("MainActivity");
}
//TODO 首页类型没展示完进直播间会不展示直播间的
public boolean isLiveActivity() {
Activity lastActivity = getLastActivity();
if (lastActivity == null) {
return false;
}
return lastActivity.getClass().getSimpleName().contains("LiveAudienceActivity");
} }
public static class SingleApp { public static class SingleApp {

View File

@ -522,6 +522,9 @@ public class DialogUitl {
if(!isShowCancelButton){ if(!isShowCancelButton){
btnCancel.setVisibility(View.GONE); btnCancel.setVisibility(View.GONE);
} }
if(!isShowCancelButton){
btnCancel.setVisibility(View.GONE);
}
View.OnClickListener listener = new View.OnClickListener() { View.OnClickListener listener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {

View File

@ -285,7 +285,7 @@ public class JavascriptInterfaceUtils {
liveBean.setGiftId(giftId); liveBean.setGiftId(giftId);
new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() { new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() {
@Override @Override
public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk) { public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk,boolean isSw) {
if (!"".endsWith(Constants.mStream)) { if (!"".endsWith(Constants.mStream)) {
@ -295,7 +295,7 @@ public class JavascriptInterfaceUtils {
} }
EventBus.getDefault().post(new LiveRoomChangeEvent(liveBean, liveType, Integer.parseInt(liveTypeVal)).setLiveEnd(true)); EventBus.getDefault().post(new LiveRoomChangeEvent(liveBean, liveType, Integer.parseInt(liveTypeVal)).setLiveEnd(true));
} else { } else {
RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk)); RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk),isSw);
} }
androidGoBack(); androidGoBack();
} }

View File

@ -12,10 +12,18 @@ public class L {
private final static String TAG = "log--->"; private final static String TAG = "log--->";
private final static String TAG_SW = "log--->TAG_SW";
public static void e(String s) { public static void e(String s) {
e(TAG, s); e(TAG, s);
} }
public static void eSw(String s) {
if (sDeBug) {
Log.e(TAG_SW, s);
}
}
public static void e(String tag, String s) { public static void e(String tag, String s) {
if (sDeBug) { if (sDeBug) {
Log.e(tag, s); Log.e(tag, s);

View File

@ -33,6 +33,7 @@ public class LiveRoomCheckLivePresenter {
private LiveBean mLiveBean; private LiveBean mLiveBean;
private ActionListener mActionListener; private ActionListener mActionListener;
private int mLiveSdk; private int mLiveSdk;
private boolean isSw;
//搜索页面不提示密码 //搜索页面不提示密码
public static boolean isRoom = false; public static boolean isRoom = false;
@ -50,7 +51,7 @@ public class LiveRoomCheckLivePresenter {
@Override @Override
public void forwardNormalRoom(CheckLiveModel model) { public void forwardNormalRoom(CheckLiveModel model) {
if (actionListener != null) { if (actionListener != null) {
actionListener.onLiveRoomChanged(liveUid, stream, model.getType(), model.getTypeVal(), model.getLiveSdk()); actionListener.onLiveRoomChanged(liveUid, stream, model.getType(), model.getTypeVal(), model.getLiveSdk(),model.getIsShengwang().equals("1"));
} }
} }
@ -74,7 +75,7 @@ public class LiveRoomCheckLivePresenter {
if (model.getTypeMsg().equalsIgnoreCase(password)) { if (model.getTypeMsg().equalsIgnoreCase(password)) {
dialog.dismiss(); dialog.dismiss();
if (actionListener != null) { if (actionListener != null) {
actionListener.onLiveRoomChanged(liveUid, stream, model.getType(), model.getTypeVal(), model.getLiveSdk()); actionListener.onLiveRoomChanged(liveUid, stream, model.getType(), model.getTypeVal(), model.getLiveSdk(),model.getIsShengwang().equals("1"));
} }
} else { } else {
ToastUtil.show(mContext.getString(R.string.live_password_error)); ToastUtil.show(mContext.getString(R.string.live_password_error));
@ -93,7 +94,7 @@ public class LiveRoomCheckLivePresenter {
public void onSuccess(int code, String msg, String[] info) { public void onSuccess(int code, String msg, String[] info) {
if (code == 0) { if (code == 0) {
if (actionListener != null) { if (actionListener != null) {
actionListener.onLiveRoomChanged(liveUid, stream, model.getType(), model.getTypeVal(), model.getLiveSdk()); actionListener.onLiveRoomChanged(liveUid, stream, model.getType(), model.getTypeVal(), model.getLiveSdk(),model.getIsShengwang().equals("1"));
} }
} else { } else {
ToastUtil.show(msg); ToastUtil.show(msg);
@ -139,6 +140,7 @@ public class LiveRoomCheckLivePresenter {
mLiveTypeMsg = obj.getString("type_msg"); mLiveTypeMsg = obj.getString("type_msg");
if (CommonAppConfig.LIVE_SDK_CHANGED) { if (CommonAppConfig.LIVE_SDK_CHANGED) {
mLiveSdk = obj.getIntValue("live_sdk"); mLiveSdk = obj.getIntValue("live_sdk");
isSw= obj.getString("is_shengwang").equals("1");
} else { } else {
mLiveSdk = CommonAppConfig.LIVE_SDK_USED; mLiveSdk = CommonAppConfig.LIVE_SDK_USED;
} }
@ -263,17 +265,16 @@ public class LiveRoomCheckLivePresenter {
*/ */
private void enterLiveRoom() { private void enterLiveRoom() {
if (mActionListener != null) { if (mActionListener != null) {
mActionListener.onLiveRoomChanged(mLiveBean, mLiveType, mLiveTypeVal, mLiveSdk); mActionListener.onLiveRoomChanged(mLiveBean, mLiveType, mLiveTypeVal, mLiveSdk,isSw);
} }
} }
public interface ActionListener { public interface ActionListener {
void onLiveRoomChanged(LiveBean liveBean, int liveType, int liveTypeVal, int liveSdk); void onLiveRoomChanged(LiveBean liveBean, int liveType, int liveTypeVal, int liveSdk,boolean isSw);
} }
public interface NewActionListener { public interface NewActionListener {
void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk); void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk,boolean isSw);
void onCheckError(String contextError); void onCheckError(String contextError);
} }

View File

@ -63,6 +63,10 @@ public class RouteUtil {
public static final String PATH_FEEDBACK_ACTIVITY = "/main/FeedbackActivity"; public static final String PATH_FEEDBACK_ACTIVITY = "/main/FeedbackActivity";
public static final String PATH_FEEDBACK_EDIT_ACTIVITY = "/main/FeedbackEditActivity"; public static final String PATH_FEEDBACK_EDIT_ACTIVITY = "/main/FeedbackEditActivity";
public static final String PATH_SudSwGameActivity = "/live/SudSwGameActivity";
public static final String PATH_SudRyGameActivity = "/live/SudRyGameActivity";
public static void forwardVideoPlayNewActivity(ActiveBean bean) { public static void forwardVideoPlayNewActivity(ActiveBean bean) {
ARouter.getInstance().build(PATH_VIDEO_NEW_PLAY) ARouter.getInstance().build(PATH_VIDEO_NEW_PLAY)
.withParcelable("ActiveBean", bean) .withParcelable("ActiveBean", bean)
@ -100,9 +104,20 @@ public class RouteUtil {
.navigation(); .navigation();
} }
public static void forwardSudGameActivity(String CreateSudRoom) {
ARouter.getInstance().build(PATH_SudGameActivity) public static void forwardSwSudGameActivity(String CreateSudRoom, boolean isAn, boolean isHome) {
ARouter.getInstance().build(PATH_SudSwGameActivity)
.withString("CreateSudRoom", CreateSudRoom) .withString("CreateSudRoom", CreateSudRoom)
.withBoolean("CreateIsAn", isAn)
.withBoolean("CreateIsHome", isHome)
.navigation();
}
public static void forwardRySudGameActivity(String CreateSudRoom, boolean isAn, boolean isHome) {
ARouter.getInstance().build(PATH_SudRyGameActivity)
.withString("CreateSudRoom", CreateSudRoom)
.withBoolean("CreateIsAn", isAn)
.withBoolean("CreateIsHome", isHome)
.navigation(); .navigation();
} }
@ -289,7 +304,7 @@ public class RouteUtil {
/** /**
* 打开直播页面 * 打开直播页面
*/ */
public static void forwardLiveAudienceActivity(LiveBean mLiveBean, int mLiveType, int mLiveSDK, int mLiveTypeVal) { public static void forwardLiveAudienceActivity(LiveBean mLiveBean, int mLiveType, int mLiveSDK, int mLiveTypeVal, boolean isSw) {
if (MicStatusManager.getInstance().isMic(mLiveBean.getUid())) { if (MicStatusManager.getInstance().isMic(mLiveBean.getUid())) {
MicStatusManager.getInstance().showDownMicDialog(CommonAppContext.activityWeakReference.get()); MicStatusManager.getInstance().showDownMicDialog(CommonAppContext.activityWeakReference.get());
return; return;
@ -299,7 +314,9 @@ public class RouteUtil {
.withParcelable(Constants.LIVE_BEAN, mLiveBean) .withParcelable(Constants.LIVE_BEAN, mLiveBean)
.withInt(Constants.LIVE_TYPE, mLiveType) .withInt(Constants.LIVE_TYPE, mLiveType)
.withInt(Constants.LIVE_SDK, mLiveSDK) .withInt(Constants.LIVE_SDK, mLiveSDK)
.withBoolean(Constants.LIVE_SDK_IS_SW, isSw)
.withInt(Constants.LIVE_TYPE_VAL, mLiveTypeVal); .withInt(Constants.LIVE_TYPE_VAL, mLiveTypeVal);
if (mLiveBean.getParams() != null) { if (mLiveBean.getParams() != null) {
for (String key : mLiveBean.getParams().keySet()) { for (String key : mLiveBean.getParams().keySet()) {
postcard.withString(key, mLiveBean.getParams().get(key)); postcard.withString(key, mLiveBean.getParams().get(key));

View File

@ -2,6 +2,7 @@ package com.yunbao.common.views;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.net.Uri; import android.net.Uri;
@ -44,6 +45,7 @@ public class APKUpdateCustomPopup extends CenterPopupView {
private ProgressBar progressBar; private ProgressBar progressBar;
private Activity mContext; private Activity mContext;
private boolean mInside; private boolean mInside;
private DialogInterface.OnDismissListener onDismissListener;
public APKUpdateCustomPopup(@NonNull Activity context, boolean inside) { public APKUpdateCustomPopup(@NonNull Activity context, boolean inside) {
super(context); super(context);
@ -57,6 +59,11 @@ public class APKUpdateCustomPopup extends CenterPopupView {
return R.layout.apk_update_custom_popup; return R.layout.apk_update_custom_popup;
} }
public APKUpdateCustomPopup setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
this.onDismissListener = onDismissListener;
return this;
}
// 执行初始化操作比如findView设置点击或者任何你弹窗内的业务逻辑 // 执行初始化操作比如findView设置点击或者任何你弹窗内的业务逻辑
@Override @Override
protected void onCreate() { protected void onCreate() {
@ -69,6 +76,14 @@ public class APKUpdateCustomPopup extends CenterPopupView {
} }
@Override
protected void onDismiss() {
super.onDismiss();
if (onDismissListener != null) {
onDismissListener.onDismiss(null);
}
}
private void initView() { private void initView() {
if (!mInside) { if (!mInside) {
if (CommonAppConfig.IS_GOOGLE_PLAY == 0 && APKManager.get().getAPKGoogleIsUp() == 1) { if (CommonAppConfig.IS_GOOGLE_PLAY == 0 && APKManager.get().getAPKGoogleIsUp() == 1) {

View File

@ -68,6 +68,16 @@ public abstract class AbsViewHolder implements LifeCycleListener {
} }
} }
public void removeView(){
if (mParentView != null && mContentView != null) {
mParentView.removeView(mContentView);
}
}
public boolean isShow(){
return mParentView.indexOfChild(mContentView)>-1;
}
public void removeFromParent() { public void removeFromParent() {
ViewParent parent = mContentView.getParent(); ViewParent parent = mContentView.getParent();
if (parent != null) { if (parent != null) {

View File

@ -29,6 +29,7 @@ import java.util.List;
public class CustomDrawerPopupView extends DrawerPopupView { public class CustomDrawerPopupView extends DrawerPopupView {
private Context mContext; private Context mContext;
private boolean mIs_shengwang;
private RecyclerView drawerList; private RecyclerView drawerList;
private CustomDrawerPopupAdapter adapter; private CustomDrawerPopupAdapter adapter;
@ -45,9 +46,10 @@ public class CustomDrawerPopupView extends DrawerPopupView {
return this; return this;
} }
public CustomDrawerPopupView(@NonNull Context context) { public CustomDrawerPopupView(@NonNull Context context, boolean is_shengwang) {
super(context); super(context);
mContext = context; mContext = context;
mIs_shengwang = is_shengwang;
} }
@Override @Override
@ -72,7 +74,7 @@ public class CustomDrawerPopupView extends DrawerPopupView {
private void initView() { private void initView() {
drawerList = findViewById(R.id.drawerList); drawerList = findViewById(R.id.drawerList);
adapter = new CustomDrawerPopupAdapter(mContext); adapter = new CustomDrawerPopupAdapter(mContext,mIs_shengwang);
adapter.setList(list).setLiveId(liveId); adapter.setList(list).setLiveId(liveId);
drawerList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)); drawerList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
drawerList.setAdapter(adapter); drawerList.setAdapter(adapter);

View File

@ -14,6 +14,7 @@ import com.alibaba.fastjson.JSON;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.lxj.xpopup.XPopup; import com.lxj.xpopup.XPopup;
import com.makeramen.roundedimageview.RoundedImageView; import com.makeramen.roundedimageview.RoundedImageView;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.R; import com.yunbao.common.R;
import com.yunbao.common.bean.CreateSudRoomModel; import com.yunbao.common.bean.CreateSudRoomModel;
import com.yunbao.common.bean.LiveBean; import com.yunbao.common.bean.LiveBean;
@ -106,8 +107,11 @@ public class SudGameListViewHolder extends RecyclerView.ViewHolder {
createSudRoomModel.setSudGameName(model.getSudGameName()); createSudRoomModel.setSudGameName(model.getSudGameName());
if (isHome) { if (isHome) {
if (TextUtils.equals(model.getLiveUid(), "0")) { if (TextUtils.equals(model.getLiveUid(), "0")) {
RouteUtil.forwardSudGameActivity(new Gson().toJson(createSudRoomModel)); if(CommonAppConfig.getInstance().getConfig().isSw()){
RouteUtil.forwardSwSudGameActivity(new Gson().toJson(createSudRoomModel),true,isHome);
}else{
RouteUtil.forwardRySudGameActivity(new Gson().toJson(createSudRoomModel),true,isHome);
}
} else { } else {
String yes = ""; String yes = "";
if (IMLoginManager.get(itemView.getContext()).getLocaleLanguage() == Locale.SIMPLIFIED_CHINESE) { if (IMLoginManager.get(itemView.getContext()).getLocaleLanguage() == Locale.SIMPLIFIED_CHINESE) {
@ -131,8 +135,8 @@ public class SudGameListViewHolder extends RecyclerView.ViewHolder {
LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class); LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class);
new LiveRoomCheckLivePresenter(itemView.getContext(), liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() { new LiveRoomCheckLivePresenter(itemView.getContext(), liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() {
@Override @Override
public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk) { public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk,boolean isSw) {
RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveSdk), Integer.parseInt(liveTypeVal)); RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveSdk), Integer.parseInt(liveTypeVal),isSw);
new Handler().postDelayed(new Runnable() { new Handler().postDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -155,8 +159,11 @@ public class SudGameListViewHolder extends RecyclerView.ViewHolder {
@Override @Override
public void onCancel() { public void onCancel() {
if(CommonAppConfig.getInstance().getConfig().isSw()){
RouteUtil.forwardSudGameActivity(new Gson().toJson(createSudRoomModel)); RouteUtil.forwardSwSudGameActivity(new Gson().toJson(createSudRoomModel),true,isHome);
}else{
RouteUtil.forwardRySudGameActivity(new Gson().toJson(createSudRoomModel),true,isHome);
}
} }
})).show(); })).show();

View File

@ -5,16 +5,19 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content"> android:layout_height="wrap_content">
<ImageView <LinearLayout
android:id="@+id/img" android:id="@+id/content_layout"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:scaleType="fitXY" android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintEnd_toEndOf="parent"
android:adjustViewBounds="true"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintStart_toStartOf="parent"
app:srcCompat="@mipmap/background_gift_wall" /> app:srcCompat="@mipmap/background_gift_wall">
</LinearLayout>
<ImageView <ImageView
android:id="@+id/close" android:id="@+id/close"
@ -22,7 +25,7 @@
android:layout_height="24dp" android:layout_height="24dp"
android:layout_marginEnd="14dp" android:layout_marginEnd="14dp"
android:layout_marginBottom="12dp" android:layout_marginBottom="12dp"
app:layout_constraintBottom_toTopOf="@+id/img" app:layout_constraintBottom_toTopOf="@+id/content_layout"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="@mipmap/ic_open_ad_close" /> app:srcCompat="@mipmap/ic_open_ad_close" />

View File

@ -6,26 +6,28 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"> android:layout_height="match_parent">
<ImageView <LinearLayout
android:id="@+id/img" android:id="@+id/content_layout"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="12dp" android:layout_marginBottom="12dp"
android:scaleType="fitCenter" android:orientation="vertical"
app:layout_constraintBottom_toTopOf="@+id/close" app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" /> app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</LinearLayout>
<ImageView <ImageView
android:id="@+id/close" android:id="@+id/close"
android:layout_width="24dp" android:layout_width="24dp"
android:layout_height="24dp" android:layout_height="24dp"
android:layout_marginBottom="202dp" android:layout_marginTop="24dp"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="@+id/content_layout"
app:layout_constraintEnd_toEndOf="@+id/img" app:layout_constraintStart_toStartOf="@+id/content_layout"
app:layout_constraintStart_toStartOf="@+id/img" app:layout_constraintTop_toBottomOf="@+id/content_layout"
app:srcCompat="@mipmap/ic_open_ad_close" /> app:srcCompat="@mipmap/ic_open_ad_close" />
</androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>

View File

@ -25,6 +25,12 @@
android:id="@+id/video_view" android:id="@+id/video_view"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" /> android:layout_height="match_parent" />
<FrameLayout
android:id="@+id/videoFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.cardview.widget.CardView> </androidx.cardview.widget.CardView>
</androidx.cardview.widget.CardView> </androidx.cardview.widget.CardView>

View File

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 75 KiB

View File

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

View File

@ -1547,5 +1547,6 @@
<string name="dragon_rule6">2.用戶關注主播並參與活動,將在倒計時五分鐘結束後瓜分活動金豆;</string> <string name="dragon_rule6">2.用戶關注主播並參與活動,將在倒計時五分鐘結束後瓜分活動金豆;</string>
<string name="dragon_rule7">3.此活動的最終解釋權歸PDLIVE所有。</string> <string name="dragon_rule7">3.此活動的最終解釋權歸PDLIVE所有。</string>
<string name="main_type_theater">短劇</string> <string name="main_type_theater">短劇</string>
<string name="pking_over">主播正在PK稍後再試</string>
<string name="guard_buy_tips_1">您將花費%s鑽石為主播開通</string> <string name="guard_buy_tips_1">您將花費%s鑽石為主播開通</string>
</resources> </resources>

View File

@ -1547,5 +1547,6 @@
<string name="dragon_rule6">2.用戶關注主播並參與活動,將在倒計時五分鐘結束後瓜分活動金豆;</string> <string name="dragon_rule6">2.用戶關注主播並參與活動,將在倒計時五分鐘結束後瓜分活動金豆;</string>
<string name="dragon_rule7">3.此活動的最終解釋權歸PDLIVE所有。</string> <string name="dragon_rule7">3.此活動的最終解釋權歸PDLIVE所有。</string>
<string name="main_type_theater">短劇</string> <string name="main_type_theater">短劇</string>
<string name="pking_over">主播正在PK稍後再試</string>
<string name="guard_buy_tips_1">您將花費%s鑽石為主播開通</string> <string name="guard_buy_tips_1">您將花費%s鑽石為主播開通</string>
</resources> </resources>

View File

@ -1545,5 +1545,6 @@
<string name="dragon_rule6">2.用戶關注主播並參與活動,將在倒計時五分鐘結束後瓜分活動金豆;</string> <string name="dragon_rule6">2.用戶關注主播並參與活動,將在倒計時五分鐘結束後瓜分活動金豆;</string>
<string name="dragon_rule7">3.此活動的最終解釋權歸PDLIVE所有。</string> <string name="dragon_rule7">3.此活動的最終解釋權歸PDLIVE所有。</string>
<string name="main_type_theater">短劇</string> <string name="main_type_theater">短劇</string>
<string name="pking_over">主播正在PK稍後再試</string>
<string name="guard_buy_tips_1">您將花費%s鑽石為主播開通</string> <string name="guard_buy_tips_1">您將花費%s鑽石為主播開通</string>
</resources> </resources>

View File

@ -1570,4 +1570,5 @@ Limited ride And limited avatar frame</string>
<string name="dragon_rule6">2.Users who follow the anchor and participate in the activity will divide the gold beans of the activity after the countdown of five minutes ends;</string> <string name="dragon_rule6">2.Users who follow the anchor and participate in the activity will divide the gold beans of the activity after the countdown of five minutes ends;</string>
<string name="dragon_rule7">3.The final interpretation of this activity belongs to PDLIVE.</string> <string name="dragon_rule7">3.The final interpretation of this activity belongs to PDLIVE.</string>
<string name="main_type_theater" >Theater</string> <string name="main_type_theater" >Theater</string>
<string name="pking_over">The anchor is in PK, please try again later</string>
</resources> </resources>

View File

@ -4,25 +4,28 @@ ext {
buildToolsVersion: "29.0.2", buildToolsVersion: "29.0.2",
minSdkVersion : 23, minSdkVersion : 23,
targetSdkVersion : 33, targetSdkVersion : 33,
versionCode : 526, versionCode : 676,
versionName : "6.6.9", versionName : "6.6.9",
namespace : "com.pandoralive.shayu" namespace : "com.pandoralive.shayu"
] ]
manifestPlaceholders = [ manifestPlaceholders = [
// //
serverHost : "https://napi.yaoulive.com", // serverHost : "https://napi.yaoulive.com",
// //
// serverHost : " https://ceshi.yaoulive.com", serverHost : " https://ceshi.yaoulive.com",
buildTime : new Date().format("MM-dd HH:mm", TimeZone.getTimeZone("GMT+8")), buildTime : new Date().format("MM-dd HH:mm", TimeZone.getTimeZone("GMT+8")),
// //
swReleaseModel : false, //true声网正式服 false测试服
baiduAppId : "23774720", baiduAppId : "23774720",
baiduAppKey : "zgCgFhUKEOV7I3ZXDFpTfnRB", baiduAppKey : "zgCgFhUKEOV7I3ZXDFpTfnRB",
baiduAppSecretKey: "nEVSgmuGpU0pjPr6VleEGGAl0hzGW52S", baiduAppSecretKey: "nEVSgmuGpU0pjPr6VleEGGAl0hzGW52S",
// true表示谷歌支付 false // true表示谷歌支付 false
// isGooglePlay : false, // isGooglePlay : false,
// true表示谷歌支付 false 0 1 2 // true表示谷歌支付 false 0 (isPluginModel-> true) 1 2 3 samsung包
isGooglePlay : 0, isGooglePlay : 0,
// //

View File

@ -24,6 +24,6 @@ android.nonTransitiveRClass=false
systemProp.http.proxyHost=127.0.0.1 systemProp.http.proxyHost=127.0.0.1
systemProp.https.proxyHost=127.0.0.1 systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=10809 systemProp.https.proxyPort=7890
systemProp.http.proxyPort=10809 systemProp.http.proxyPort=7890
#android.enableR8.fullMode=true #android.enableR8.fullMode=true

4
lib_faceunity/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/build
/src/main/assets/makeup
/src/main/assets/sticker
authpack.java

View File

@ -0,0 +1,80 @@
apply plugin: 'com.android.library'
apply plugin: 'maven-publish'
apply plugin: 'kotlin-android'
android {
namespace "com.yunbao.swfaceunity"
compileSdkVersion 31
buildToolsVersion "30.0.3"
defaultConfig {
minSdkVersion 21
targetSdkVersion 31
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
if (new File("$AGORA_RTC_SDK").exists()) {
api fileTree(dir: "${AGORA_RTC_SDK}", include: ['*.jar', '*.aar'])
} else {
api "$AGORA_RTC_SDK"
}
api project(path: ':FaceUnity')
}
// Because the components are created only during the afterEvaluate phase, you must
// configure your publications using the afterEvaluate() lifecycle method.
afterEvaluate {
publishing {
publications {
// Creates a Maven publication called "release".
release(MavenPublication) {
// Applies the component for the release build variant.
from components.release
// You can then customize attributes of the publication as shown below.
groupId = 'com.github.AgoraIO-Community.BeautyAPI'
artifactId = 'FaceUnity'
version = "$LIB_VERSION"
}
// Creates a Maven publication called debug.
debug(MavenPublication) {
// Applies the component for the debug build variant.
from components.debug
groupId = 'com.github.AgoraIO-Community.BeautyAPI'
artifactId = 'FaceUnity'
version = "$LIB_VERSION"
}
}
if(IS_PUBLISH_LOCAL){
repositories {
maven {
url = "file://${rootProject.projectDir.path}/maven"
println("maven publish to ${url}")
}
}
}
}
}

View File

21
lib_faceunity/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:tools="http://schemas.android.com/tools"
>
<uses-sdk tools:overrideLibrary="io.agora.beautyapi.faceunity" />
</manifest>

View File

@ -0,0 +1,179 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity
import android.content.Context
import android.view.View
import com.faceunity.core.faceunity.FURenderKit
import io.agora.base.VideoFrame
import io.agora.rtc2.Constants
import io.agora.rtc2.RtcEngine
const val VERSION = "1.0.6"
enum class CaptureMode{
Agora, // 使用声网内部的祼数据接口进行处理
Custom // 自定义模式需要自己调用onFrame接口将原始视频帧传给BeautyAPI做处理
}
interface IEventCallback{
/**
* 统计数据回调每处理完一帧后会回调一次
*
* @param stats 美颜统计数据
*/
fun onBeautyStats(stats: BeautyStats)
}
data class BeautyStats(
val minCostMs:Long, // 统计区间内的最小值
val maxCostMs: Long, // 统计区间内的最大值
val averageCostMs: Long // 统计区间内的平均值
)
enum class MirrorMode {
// 没有镜像正常画面的定义:前置拍到画面和手机看到画面是左右不一致的,后置拍到画面和手机看到画面是左右一致的
MIRROR_LOCAL_REMOTE, //本地远端都镜像,前置默认,本地和远端贴纸都正常
MIRROR_LOCAL_ONLY, // 仅本地镜像,远端不镜像,,远端贴纸正常,本地贴纸镜像。用于打电话场景,电商直播场景(保证电商直播后面的告示牌文字是正的);这种模式因为本地远端是反的,所以肯定有一边的文字贴纸方向会是反的
MIRROR_REMOTE_ONLY, // 仅远端镜像,本地不镜像,远端贴纸正常,本地贴纸镜像
MIRROR_NONE // 本地远端都不镜像,后置默认,本地和远端贴纸都正常
}
data class CameraConfig(
val frontMirror: MirrorMode = MirrorMode.MIRROR_LOCAL_REMOTE, // 前置默认镜像:本地远端都镜像
val backMirror: MirrorMode = MirrorMode.MIRROR_NONE // 后置默认镜像:本地远端都不镜像
)
data class Config(
val context: Context, // Android Context 上下文
val rtcEngine: RtcEngine, // 声网Rtc引擎
val fuRenderKit: FURenderKit, // 美颜SDK处理句柄
val eventCallback: IEventCallback? = null, // 事件回调
val captureMode: CaptureMode = CaptureMode.Agora, // 处理模式
val statsDuration: Long = 1000, // 统计区间
val statsEnable: Boolean = false, // 是否开启统计
val cameraConfig: CameraConfig = CameraConfig() // 摄像头镜像配置
)
enum class ErrorCode(val value: Int) {
ERROR_OK(0), // 一切正常
ERROR_HAS_NOT_INITIALIZED(101), // 没有调用Initialize或调用失败情况下调用了其他API
ERROR_HAS_INITIALIZED(102), // 已经Initialize成功后再次调用报错
ERROR_HAS_RELEASED(103), // 已经调用release销毁后还调用其他API
ERROR_PROCESS_NOT_CUSTOM(104), // 非Custom处理模式下调用onFrame接口从外部传入视频帧
ERROR_VIEW_TYPE_ERROR(105), // 当调用setupLocalVideo时view类型错误时返回
ERROR_FRAME_SKIPPED(106), // 当处理帧忽略时在onFrame返回
}
enum class BeautyPreset {
CUSTOM, // 不使用推荐的美颜参数
DEFAULT // 默认的
}
fun createFaceUnityBeautyAPI(): FaceUnityBeautyAPI = FaceUnityBeautyAPIImpl()
interface FaceUnityBeautyAPI {
/**
* 初始化API
*
* @param config 配置参数
* @return 见ErrorCode
*/
fun initialize(config: Config): Int
/**
* 开启/关闭美颜
*
* @param enable true开启; false: 关闭
* @return 见ErrorCode
*/
fun enable(enable: Boolean): Int
/**
* 本地视图渲染由内部来处理镜像问题
*
* @param view SurfaceView或TextureView
* @param renderMode 渲染缩放模式
* @return 见ErrorCode
*/
fun setupLocalVideo(view: View, renderMode: Int = Constants.RENDER_MODE_HIDDEN): Int
/**
* 当ProcessMode==Custom时由外部传入原始视频帧
*
* @param videoFrame 原始视频帧
* @return 见ErrorCode
*/
fun onFrame(videoFrame: VideoFrame): Int
/**
* 声网提供的美颜最佳默认参数
*
* @return 见ErrorCode
*/
fun setBeautyPreset(preset: BeautyPreset = BeautyPreset.DEFAULT): Int
/**
* 更新摄像头配置
*/
fun updateCameraConfig(config: CameraConfig): Int
/**
* 是否是前置摄像头
* PS只在美颜处理中才能知道准确的值否则会一直是true
*/
fun isFrontCamera(): Boolean
/**
* 获取镜像状态
*
* @return 镜像状态true: 镜像false非镜像
*/
fun getMirrorApplied(): Boolean
/**
* 在处理线程里执行操作
*
* @param run 操作run
*/
fun runOnProcessThread(run: ()->Unit)
/**
* 私参配置用于不对外api的调用多用于测试
*/
fun setParameters(key: String, value: String)
/**
* 释放资源一旦释放后这个实例将无法使用
*
* @return 见ErrorCode
*/
fun release(): Int
}

View File

@ -0,0 +1,818 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity
import android.graphics.Matrix
import android.opengl.GLES11Ext
import android.opengl.GLES20
import android.view.SurfaceView
import android.view.TextureView
import android.view.View
import com.faceunity.core.entity.FUBundleData
import com.faceunity.core.entity.FURenderInputData
import com.faceunity.core.enumeration.CameraFacingEnum
import com.faceunity.core.enumeration.FUInputBufferEnum
import com.faceunity.core.enumeration.FUInputTextureEnum
import com.faceunity.core.enumeration.FUTransformMatrixEnum
import com.faceunity.core.faceunity.FUAIKit
import com.faceunity.core.faceunity.FURenderKit
import com.faceunity.core.model.facebeauty.FaceBeauty
import com.faceunity.core.model.facebeauty.FaceBeautyFilterEnum
import io.agora.base.TextureBufferHelper
import io.agora.base.VideoFrame
import io.agora.base.VideoFrame.I420Buffer
import io.agora.base.VideoFrame.SourceType
import io.agora.base.VideoFrame.TextureBuffer
import io.agora.base.internal.video.EglBase
import io.agora.base.internal.video.YuvHelper
import io.agora.beautyapi.faceunity.utils.FuDeviceUtils
import io.agora.beautyapi.faceunity.utils.LogUtils
import io.agora.beautyapi.faceunity.utils.StatsHelper
import io.agora.beautyapi.faceunity.utils.egl.GLFrameBuffer
import io.agora.beautyapi.faceunity.utils.egl.TextureProcessHelper
import io.agora.rtc2.Constants
import io.agora.rtc2.gl.EglBaseProvider
import io.agora.rtc2.video.IVideoFrameObserver
import io.agora.rtc2.video.VideoCanvas
import java.io.File
import java.nio.ByteBuffer
import java.util.Collections
import java.util.concurrent.Callable
class FaceUnityBeautyAPIImpl : FaceUnityBeautyAPI, IVideoFrameObserver {
private val TAG = "FaceUnityBeautyAPIImpl"
private val reportId = "scenarioAPI"
private val reportCategory = "beauty_android_$VERSION"
private var beautyMode = 0 // 0: 自动根据buffer类型切换1固定使用OES纹理2固定使用i4203: 单纹理模式
private var enableTextureAsync = true // 是否开启纹理+异步缓存处理不支持在预览中实时切换。对于GPU性能好的手机可以减小美颜处理耗时对于中端机开启后效果也不明显。
private var textureBufferHelper: TextureBufferHelper? = null
private var wrapTextureBufferHelper: TextureBufferHelper? = null
private var byteBuffer: ByteBuffer? = null
private var byteArray: ByteArray? = null
private var config: Config? = null
private var enable: Boolean = false
private var enableChange: Boolean = false
private var isReleased: Boolean = false
private var captureMirror = false
private var renderMirror = false
private val identityMatrix = Matrix()
private var mTextureProcessHelper: TextureProcessHelper? = null
private var statsHelper: StatsHelper? = null
private var skipFrame = 0
private enum class ProcessSourceType{
UNKNOWN,
TEXTURE_OES_ASYNC,
TEXTURE_2D_ASYNC,
TEXTURE_OES,
TEXTURE_2D,
I420
}
private var currProcessSourceType = ProcessSourceType.UNKNOWN
private var deviceLevel = FuDeviceUtils.DEVICEINFO_UNKNOWN
private var isFrontCamera = true
private var cameraConfig = CameraConfig()
private var localVideoRenderMode = Constants.RENDER_MODE_HIDDEN
private val pendingProcessRunList = Collections.synchronizedList(mutableListOf<()->Unit>())
private val transformGLFrameBuffer = GLFrameBuffer()
override fun initialize(config: Config): Int {
if (this.config != null) {
LogUtils.e(TAG, "initialize >> The beauty api has been initialized!")
return ErrorCode.ERROR_HAS_INITIALIZED.value
}
this.config = config
this.cameraConfig = config.cameraConfig
if (config.captureMode == CaptureMode.Agora) {
config.rtcEngine.registerVideoFrameObserver(this)
}
statsHelper = StatsHelper(config.statsDuration){
this.config?.eventCallback?.onBeautyStats(it)
}
LogUtils.i(TAG, "initialize >> config = $config")
LogUtils.i(TAG, "initialize >> beauty api version=$VERSION, beauty sdk version=${FURenderKit.getInstance().getVersion()}")
// config face beauty
if (deviceLevel == FuDeviceUtils.DEVICEINFO_UNKNOWN) {
deviceLevel = FuDeviceUtils.judgeDeviceLevel(config.context)
FUAIKit.getInstance().faceProcessorSetFaceLandmarkQuality(deviceLevel)
if (deviceLevel > FuDeviceUtils.DEVICE_LEVEL_MID) {
FUAIKit.getInstance().fuFaceProcessorSetDetectSmallFace(true)
}
}
LogUtils.i(TAG, "initialize >> FuDeviceUtils deviceLevel=$deviceLevel")
config.rtcEngine.sendCustomReportMessage(reportId, reportCategory, "initialize", "config=$config, deviceLevel=$deviceLevel", 0)
return ErrorCode.ERROR_OK.value
}
override fun enable(enable: Boolean): Int {
LogUtils.i(TAG, "enable >> enable = $enable")
if (config == null) {
LogUtils.e(TAG, "enable >> The beauty api has not been initialized!")
return ErrorCode.ERROR_HAS_NOT_INITIALIZED.value
}
if (isReleased) {
LogUtils.e(TAG, "enable >> The beauty api has been released!")
return ErrorCode.ERROR_HAS_RELEASED.value
}
if(config?.captureMode == CaptureMode.Custom){
skipFrame = 2
LogUtils.i(TAG, "enable >> skipFrame = $skipFrame")
}
config?.rtcEngine?.sendCustomReportMessage(reportId, reportCategory, "enable", "enable=$enable", 0)
if(this.enable != enable){
this.enable = enable
enableChange = true
LogUtils.i(TAG, "enable >> enableChange")
}
return ErrorCode.ERROR_OK.value
}
override fun setupLocalVideo(view: View, renderMode: Int): Int {
val rtcEngine = config?.rtcEngine
if(rtcEngine == null){
LogUtils.e(TAG, "setupLocalVideo >> The beauty api has not been initialized!")
return ErrorCode.ERROR_HAS_NOT_INITIALIZED.value
}
LogUtils.i(TAG, "setupLocalVideo >> view=$view, renderMode=$renderMode")
localVideoRenderMode = renderMode
rtcEngine.sendCustomReportMessage(reportId, reportCategory, "enable", "view=$view, renderMode=$renderMode", 0)
if (view is TextureView || view is SurfaceView) {
val canvas = VideoCanvas(view, renderMode, 0)
canvas.mirrorMode = Constants.VIDEO_MIRROR_MODE_DISABLED
rtcEngine.setupLocalVideo(canvas)
return ErrorCode.ERROR_OK.value
}
return ErrorCode.ERROR_VIEW_TYPE_ERROR.value
}
override fun onFrame(videoFrame: VideoFrame): Int {
val conf = config
if(conf == null){
LogUtils.e(TAG, "onFrame >> The beauty api has not been initialized!")
return ErrorCode.ERROR_HAS_NOT_INITIALIZED.value
}
if (isReleased) {
LogUtils.e(TAG, "onFrame >> The beauty api has been released!")
return ErrorCode.ERROR_HAS_RELEASED.value
}
if (conf.captureMode != CaptureMode.Custom) {
LogUtils.e(TAG, "onFrame >> The capture mode is not Custom!")
return ErrorCode.ERROR_PROCESS_NOT_CUSTOM.value
}
if (processBeauty(videoFrame)) {
return ErrorCode.ERROR_OK.value
}
LogUtils.i(TAG, "onFrame >> Skip Frame.")
return ErrorCode.ERROR_FRAME_SKIPPED.value
}
override fun updateCameraConfig(config: CameraConfig): Int {
LogUtils.i(TAG, "updateCameraConfig >> oldCameraConfig=$cameraConfig, newCameraConfig=$config")
cameraConfig = CameraConfig(config.frontMirror, config.backMirror)
this.config?.rtcEngine?.sendCustomReportMessage(reportId, reportCategory, "updateCameraConfig", "config=$config", 0)
return ErrorCode.ERROR_OK.value
}
override fun runOnProcessThread(run: () -> Unit) {
if (config == null) {
LogUtils.e(TAG, "runOnProcessThread >> The beauty api has not been initialized!")
return
}
if (isReleased) {
LogUtils.e(TAG, "runOnProcessThread >> The beauty api has been released!")
return
}
if (textureBufferHelper?.handler?.looper?.thread == Thread.currentThread()) {
run.invoke()
} else if (textureBufferHelper != null) {
textureBufferHelper?.handler?.post(run)
} else {
pendingProcessRunList.add(run)
}
}
override fun isFrontCamera() = isFrontCamera
override fun setParameters(key: String, value: String) {
when(key){
"beauty_mode" -> beautyMode = value.toInt()
"enableTextureAsync" -> enableTextureAsync = value.toBoolean()
}
}
override fun setBeautyPreset(preset: BeautyPreset): Int {
val conf = config
if(conf == null){
LogUtils.e(TAG, "setBeautyPreset >> The beauty api has not been initialized!")
return ErrorCode.ERROR_HAS_NOT_INITIALIZED.value
}
if (isReleased) {
LogUtils.e(TAG, "setBeautyPreset >> The beauty api has been released!")
return ErrorCode.ERROR_HAS_RELEASED.value
}
LogUtils.i(TAG, "setBeautyPreset >> preset = $preset")
config?.rtcEngine?.sendCustomReportMessage(reportId, reportCategory, "enable", "preset=$preset", 0)
val recommendFaceBeauty = FaceBeauty(FUBundleData("graphics" + File.separator + "face_beautification.bundle"))
if (preset == BeautyPreset.DEFAULT) {
recommendFaceBeauty.filterName = FaceBeautyFilterEnum.FENNEN_1
recommendFaceBeauty.filterIntensity = 0.7
// 美牙
recommendFaceBeauty.toothIntensity = 0.3
// 亮眼
recommendFaceBeauty.eyeBrightIntensity = 0.3
// 大眼
recommendFaceBeauty.eyeEnlargingIntensity = 0.5
// 红润
recommendFaceBeauty.redIntensity = 0.5 * 2
// 美白
recommendFaceBeauty.colorIntensity = 0.75 * 2
// 磨皮
recommendFaceBeauty.blurIntensity = 0.75 * 6
if (deviceLevel > FuDeviceUtils.DEVICE_LEVEL_MID) {
val score = FUAIKit.getInstance().getFaceProcessorGetConfidenceScore(0)
if (score > 0.95) {
recommendFaceBeauty.blurType = 3
recommendFaceBeauty.enableBlurUseMask = true
} else {
recommendFaceBeauty.blurType = 2
recommendFaceBeauty.enableBlurUseMask = false
}
} else {
recommendFaceBeauty.blurType = 2
recommendFaceBeauty.enableBlurUseMask = false
}
// 嘴型
recommendFaceBeauty.mouthIntensity = 0.3
// 瘦鼻
recommendFaceBeauty.noseIntensity = 0.1
// 额头
recommendFaceBeauty.forHeadIntensity = 0.3
// 下巴
recommendFaceBeauty.chinIntensity = 0.0
// 瘦脸
recommendFaceBeauty.cheekThinningIntensity = 0.3
// 窄脸
recommendFaceBeauty.cheekNarrowIntensity = 0.0
// 小脸
recommendFaceBeauty.cheekSmallIntensity = 0.0
// v脸
recommendFaceBeauty.cheekVIntensity = 0.0
}
conf.fuRenderKit.faceBeauty = recommendFaceBeauty
return ErrorCode.ERROR_OK.value
}
override fun release(): Int {
val conf = config
val fuRenderer = conf?.fuRenderKit
if(fuRenderer == null){
LogUtils.e(TAG, "release >> The beauty api has not been initialized!")
return ErrorCode.ERROR_HAS_NOT_INITIALIZED.value
}
if (isReleased) {
LogUtils.e(TAG, "setBeautyPreset >> The beauty api has been released!")
return ErrorCode.ERROR_HAS_RELEASED.value
}
LogUtils.i(TAG, "release")
if (conf.captureMode == CaptureMode.Agora) {
conf.rtcEngine.registerVideoFrameObserver(null)
}
conf.rtcEngine.sendCustomReportMessage(reportId, reportCategory, "release", "", 0)
isReleased = true
textureBufferHelper?.let {
textureBufferHelper = null
it.handler.removeCallbacksAndMessages(null)
it.invoke {
fuRenderer.release()
mTextureProcessHelper?.release()
mTextureProcessHelper = null
transformGLFrameBuffer.release()
null
}
// it.handler.looper.quit()
it.dispose()
}
wrapTextureBufferHelper?.let {
wrapTextureBufferHelper = null
it.dispose()
}
statsHelper?.reset()
statsHelper = null
pendingProcessRunList.clear()
return ErrorCode.ERROR_OK.value
}
private fun processBeauty(videoFrame: VideoFrame): Boolean {
if (isReleased) {
LogUtils.e(TAG, "processBeauty >> The beauty api has been released!")
return false
}
val cMirror =
if (isFrontCamera) {
when (cameraConfig.frontMirror) {
MirrorMode.MIRROR_LOCAL_REMOTE -> true
MirrorMode.MIRROR_LOCAL_ONLY -> false
MirrorMode.MIRROR_REMOTE_ONLY -> true
MirrorMode.MIRROR_NONE -> false
}
} else {
when (cameraConfig.backMirror) {
MirrorMode.MIRROR_LOCAL_REMOTE -> true
MirrorMode.MIRROR_LOCAL_ONLY -> false
MirrorMode.MIRROR_REMOTE_ONLY -> true
MirrorMode.MIRROR_NONE -> false
}
}
val rMirror =
if (isFrontCamera) {
when (cameraConfig.frontMirror) {
MirrorMode.MIRROR_LOCAL_REMOTE -> false
MirrorMode.MIRROR_LOCAL_ONLY -> true
MirrorMode.MIRROR_REMOTE_ONLY -> true
MirrorMode.MIRROR_NONE -> false
}
} else {
when (cameraConfig.backMirror) {
MirrorMode.MIRROR_LOCAL_REMOTE -> false
MirrorMode.MIRROR_LOCAL_ONLY -> true
MirrorMode.MIRROR_REMOTE_ONLY -> true
MirrorMode.MIRROR_NONE -> false
}
}
if (captureMirror != cMirror || renderMirror != rMirror) {
LogUtils.w(TAG, "processBeauty >> enable=$enable, captureMirror=$captureMirror->$cMirror, renderMirror=$renderMirror->$rMirror")
captureMirror = cMirror
if(renderMirror != rMirror){
renderMirror = rMirror
config?.rtcEngine?.setLocalRenderMode(
localVideoRenderMode,
if(renderMirror) Constants.VIDEO_MIRROR_MODE_ENABLED else Constants.VIDEO_MIRROR_MODE_DISABLED
)
}
textureBufferHelper?.invoke {
mTextureProcessHelper?.reset()
}
skipFrame = 2
return false
}
val oldIsFrontCamera = isFrontCamera
isFrontCamera = videoFrame.sourceType == SourceType.kFrontCamera
if(oldIsFrontCamera != isFrontCamera){
LogUtils.w(TAG, "processBeauty >> oldIsFrontCamera=$oldIsFrontCamera, isFrontCamera=$isFrontCamera")
return false
}
if(enableChange){
enableChange = false
textureBufferHelper?.invoke {
mTextureProcessHelper?.reset()
}
return false
}
if(!enable){
return true
}
if (textureBufferHelper == null) {
textureBufferHelper = TextureBufferHelper.create(
"FURender",
EglBaseProvider.instance().rootEglBase.eglBaseContext
)
textureBufferHelper?.invoke {
synchronized(pendingProcessRunList){
val iterator = pendingProcessRunList.iterator()
while (iterator.hasNext()){
iterator.next().invoke()
iterator.remove()
}
}
}
LogUtils.i(TAG, "processBeauty >> create texture buffer, beautyMode=$beautyMode")
}
if (wrapTextureBufferHelper == null) {
wrapTextureBufferHelper = TextureBufferHelper.create(
"FURenderWrap",
EglBaseProvider.instance().rootEglBase.eglBaseContext
)
LogUtils.i(TAG, "processBeauty >> create texture buffer wrap, beautyMode=$beautyMode")
}
val startTime = System.currentTimeMillis()
val processTexId = when (beautyMode) {
2 -> processBeautySingleBuffer(videoFrame)
3 -> {
if (enableTextureAsync) {
processBeautySingleTextureAsync(videoFrame)
} else {
processBeautySingleTexture(videoFrame)
}
}
else -> processBeautyAuto(videoFrame)
}
if(config?.statsEnable == true){
val costTime = System.currentTimeMillis() - startTime
statsHelper?.once(costTime)
}
if (processTexId <= 0) {
LogUtils.w(TAG, "processBeauty >> processTexId <= 0")
return false
}
if(skipFrame > 0){
skipFrame --
LogUtils.w(TAG, "processBeauty >> skipFrame=$skipFrame")
return false
}
val processBuffer: TextureBuffer = wrapTextureBufferHelper?.wrapTextureBuffer(
videoFrame.rotatedWidth,
videoFrame.rotatedHeight,
TextureBuffer.Type.RGB,
processTexId,
identityMatrix
) ?: return false
videoFrame.replaceBuffer(processBuffer, 0, videoFrame.timestampNs)
return true
}
private fun processBeautyAuto(videoFrame: VideoFrame): Int {
val buffer = videoFrame.buffer
return if (buffer is TextureBuffer) {
if (enableTextureAsync) {
processBeautySingleTextureAsync(videoFrame)
} else {
processBeautySingleTexture(videoFrame)
}
} else {
processBeautySingleBuffer(videoFrame)
}
}
private fun processBeautySingleTextureAsync(videoFrame: VideoFrame): Int {
val texBufferHelper = wrapTextureBufferHelper ?: return -1
val textureBuffer = videoFrame.buffer as? TextureBuffer ?: return -1
when(textureBuffer.type){
TextureBuffer.Type.OES -> {
if(currProcessSourceType != ProcessSourceType.TEXTURE_OES_ASYNC){
LogUtils.i(TAG, "processBeauty >> process source type change old=$currProcessSourceType, new=${ProcessSourceType.TEXTURE_OES_ASYNC}")
if (currProcessSourceType != ProcessSourceType.UNKNOWN) {
skipFrame = 3
}
currProcessSourceType = ProcessSourceType.TEXTURE_OES_ASYNC
return -1
}
}
else -> {
if(currProcessSourceType != ProcessSourceType.TEXTURE_2D_ASYNC){
LogUtils.i(TAG, "processBeauty >> process source type change old=$currProcessSourceType, new=${ProcessSourceType.TEXTURE_2D_ASYNC}")
if (currProcessSourceType != ProcessSourceType.UNKNOWN) {
skipFrame = 3
}
currProcessSourceType = ProcessSourceType.TEXTURE_2D_ASYNC
skipFrame = 6
return -1
}
}
}
if(mTextureProcessHelper == null) {
mTextureProcessHelper = TextureProcessHelper()
mTextureProcessHelper?.setFilter { frame ->
val fuRenderKit = config?.fuRenderKit ?: return@setFilter -1
val input = FURenderInputData(frame.width, frame.height)
input.texture = FURenderInputData.FUTexture(
FUInputTextureEnum.FU_ADM_FLAG_COMMON_TEXTURE,
frame.textureId
)
val isFront = frame.isFrontCamera
input.renderConfig.let {
if (isFront) {
it.cameraFacing = CameraFacingEnum.CAMERA_FRONT
it.inputBufferMatrix = FUTransformMatrixEnum.CCROT0
it.inputTextureMatrix = FUTransformMatrixEnum.CCROT0
it.outputMatrix = FUTransformMatrixEnum.CCROT0_FLIPVERTICAL
it.deviceOrientation = 270
} else {
it.cameraFacing = CameraFacingEnum.CAMERA_BACK
it.inputBufferMatrix = FUTransformMatrixEnum.CCROT0
it.inputTextureMatrix = FUTransformMatrixEnum.CCROT0
it.outputMatrix = FUTransformMatrixEnum.CCROT0_FLIPVERTICAL
it.deviceOrientation = 270
}
}
if (isReleased) {
return@setFilter -1
}
val ret = textureBufferHelper?.invoke {
synchronized(EglBase.lock){
return@invoke fuRenderKit.renderWithInput(input).texture?.texId ?: -1
}
}
return@setFilter ret ?: -1
}
}
return texBufferHelper.invoke {
if(isReleased){
return@invoke -1
}
return@invoke mTextureProcessHelper?.process(
textureBuffer.textureId,
when (textureBuffer.type) {
TextureBuffer.Type.OES -> GLES11Ext.GL_TEXTURE_EXTERNAL_OES
else -> GLES20.GL_TEXTURE_2D
},
textureBuffer.width,
textureBuffer.height,
videoFrame.rotation,
textureBuffer.transformMatrixArray,
isFrontCamera,
(isFrontCamera && !captureMirror) || (!isFrontCamera && captureMirror)
)?: -1
}
}
private fun processBeautySingleTexture(videoFrame: VideoFrame): Int {
val texBufferHelper = wrapTextureBufferHelper ?: return -1
val textureBuffer = videoFrame.buffer as? TextureBuffer ?: return -1
when(textureBuffer.type){
TextureBuffer.Type.OES -> {
if(currProcessSourceType != ProcessSourceType.TEXTURE_OES){
LogUtils.i(TAG, "processBeauty >> process source type change old=$currProcessSourceType, new=${ProcessSourceType.TEXTURE_OES}")
if (currProcessSourceType != ProcessSourceType.UNKNOWN) {
skipFrame = 3
}
currProcessSourceType = ProcessSourceType.TEXTURE_OES
return -1
}
}
else -> {
if(currProcessSourceType != ProcessSourceType.TEXTURE_2D){
LogUtils.i(TAG, "processBeauty >> process source type change old=$currProcessSourceType, new=${ProcessSourceType.TEXTURE_2D}")
if (currProcessSourceType != ProcessSourceType.UNKNOWN) {
skipFrame = 3
}
currProcessSourceType = ProcessSourceType.TEXTURE_2D
skipFrame = 6
return -1
}
}
}
val width = videoFrame.rotatedWidth
val height = videoFrame.rotatedHeight
val isFront = videoFrame.sourceType == SourceType.kFrontCamera
val rotation = videoFrame.rotation
return texBufferHelper.invoke {
val fuRenderKit = config?.fuRenderKit ?: return@invoke -1
transformGLFrameBuffer.setSize(width, height)
transformGLFrameBuffer.resetTransform()
transformGLFrameBuffer.setTexMatrix(textureBuffer.transformMatrixArray)
transformGLFrameBuffer.setRotation(rotation)
var flipH = isFront
if((isFrontCamera && !captureMirror) || (!isFrontCamera && captureMirror)){
flipH = !flipH
}
transformGLFrameBuffer.setFlipH(flipH)
val transformTexId = transformGLFrameBuffer.process(
textureBuffer.textureId, when (textureBuffer.type) {
TextureBuffer.Type.OES -> GLES11Ext.GL_TEXTURE_EXTERNAL_OES
else -> GLES20.GL_TEXTURE_2D
}
)
val input = FURenderInputData(width, height)
input.texture = FURenderInputData.FUTexture(
FUInputTextureEnum.FU_ADM_FLAG_COMMON_TEXTURE,
transformTexId
)
input.renderConfig.let {
if (isFront) {
it.cameraFacing = CameraFacingEnum.CAMERA_FRONT
it.inputBufferMatrix = FUTransformMatrixEnum.CCROT0
it.inputTextureMatrix = FUTransformMatrixEnum.CCROT0
it.outputMatrix = FUTransformMatrixEnum.CCROT0_FLIPVERTICAL
it.deviceOrientation = 270
} else {
it.cameraFacing = CameraFacingEnum.CAMERA_BACK
it.inputBufferMatrix = FUTransformMatrixEnum.CCROT0
it.inputTextureMatrix = FUTransformMatrixEnum.CCROT0
it.outputMatrix = FUTransformMatrixEnum.CCROT0_FLIPVERTICAL
it.deviceOrientation = 270
}
}
if (isReleased) {
return@invoke -1
}
synchronized(EglBase.lock){
return@invoke fuRenderKit.renderWithInput(input).texture?.texId ?: -1
}
}
}
private fun processBeautySingleBuffer(videoFrame: VideoFrame): Int {
val texBufferHelper = textureBufferHelper ?: return -1
if(currProcessSourceType != ProcessSourceType.I420){
LogUtils.i(TAG, "processBeauty >> process source type change old=$currProcessSourceType, new=${ProcessSourceType.I420}")
if (currProcessSourceType != ProcessSourceType.UNKNOWN) {
skipFrame = 3
}
currProcessSourceType = ProcessSourceType.I420
return -1
}
val bufferArray = getNV21Buffer(videoFrame) ?: return -1
val buffer = videoFrame.buffer
val width = buffer.width
val height = buffer.height
val isFront = videoFrame.sourceType == SourceType.kFrontCamera
val mirror = (isFrontCamera && !captureMirror) || (!isFrontCamera && captureMirror)
val rotation = videoFrame.rotation
return texBufferHelper.invoke(Callable {
if(isReleased){
return@Callable -1
}
val fuRenderKit = config?.fuRenderKit ?: return@Callable -1
val input = FURenderInputData(width, height)
input.imageBuffer = FURenderInputData.FUImageBuffer(
FUInputBufferEnum.FU_FORMAT_NV21_BUFFER,
bufferArray
)
input.renderConfig.let {
if (isFront) {
it.cameraFacing = CameraFacingEnum.CAMERA_FRONT
it.inputBufferMatrix = if(mirror) {
when (rotation) {
0 -> FUTransformMatrixEnum.CCROT0
180 -> FUTransformMatrixEnum.CCROT180
else -> FUTransformMatrixEnum.CCROT90
}
} else {
when (rotation) {
0 -> FUTransformMatrixEnum.CCROT0_FLIPHORIZONTAL
180 -> FUTransformMatrixEnum.CCROT0_FLIPVERTICAL
else -> FUTransformMatrixEnum.CCROT90_FLIPHORIZONTAL
}
}
it.inputTextureMatrix = if(mirror) {
when (rotation) {
0 -> FUTransformMatrixEnum.CCROT0
180 -> FUTransformMatrixEnum.CCROT180
else -> FUTransformMatrixEnum.CCROT90
}
} else {
when (rotation) {
0 -> FUTransformMatrixEnum.CCROT0_FLIPHORIZONTAL
180 -> FUTransformMatrixEnum.CCROT0_FLIPVERTICAL
else -> FUTransformMatrixEnum.CCROT90_FLIPHORIZONTAL
}
}
it.deviceOrientation = when(rotation){
0 -> 270
180 -> 90
else -> 0
}
it.outputMatrix = FUTransformMatrixEnum.CCROT0
} else {
it.cameraFacing = CameraFacingEnum.CAMERA_BACK
it.inputBufferMatrix = if(mirror) {
when (rotation) {
0 -> FUTransformMatrixEnum.CCROT0_FLIPHORIZONTAL
180 -> FUTransformMatrixEnum.CCROT0_FLIPVERTICAL
else -> FUTransformMatrixEnum.CCROT90_FLIPVERTICAL
}
} else {
when (rotation) {
0 -> FUTransformMatrixEnum.CCROT0
180 -> FUTransformMatrixEnum.CCROT180
else -> FUTransformMatrixEnum.CCROT270
}
}
it.inputTextureMatrix = if(mirror) {
when (rotation) {
0 -> FUTransformMatrixEnum.CCROT0_FLIPHORIZONTAL
180 -> FUTransformMatrixEnum.CCROT0_FLIPVERTICAL
else -> FUTransformMatrixEnum.CCROT90_FLIPVERTICAL
}
} else {
when (rotation) {
0 -> FUTransformMatrixEnum.CCROT0
180 -> FUTransformMatrixEnum.CCROT180
else -> FUTransformMatrixEnum.CCROT270
}
}
it.deviceOrientation = when(rotation){
0 -> 270
180 -> 90
else -> 0
}
it.outputMatrix = FUTransformMatrixEnum.CCROT0
}
}
mTextureProcessHelper?.let {
if(it.size() > 0){
it.reset()
return@Callable -1
}
}
synchronized(EglBase.lock){
return@Callable fuRenderKit.renderWithInput(input).texture?.texId ?: -1
}
})
}
private fun getNV21Buffer(videoFrame: VideoFrame): ByteArray? {
val buffer = videoFrame.buffer
val width = buffer.width
val height = buffer.height
val size = (width * height * 3.0f / 2.0f + 0.5f).toInt()
if (byteBuffer == null || byteBuffer?.capacity() != size || byteArray == null || byteArray?.size != size) {
byteBuffer?.clear()
byteBuffer = ByteBuffer.allocateDirect(size)
byteArray = ByteArray(size)
return null
}
val outArray = byteArray ?: return null
val outBuffer = byteBuffer ?: return null
val i420Buffer = buffer as? I420Buffer ?: buffer.toI420()
YuvHelper.I420ToNV12(
i420Buffer.dataY, i420Buffer.strideY,
i420Buffer.dataV, i420Buffer.strideV,
i420Buffer.dataU, i420Buffer.strideU,
outBuffer, width, height
)
outBuffer.position(0)
outBuffer.get(outArray)
if(buffer !is I420Buffer){
i420Buffer.release()
}
return outArray
}
// IVideoFrameObserver implements
override fun onCaptureVideoFrame(sourceType: Int, videoFrame: VideoFrame?): Boolean {
videoFrame ?: return false
return processBeauty(videoFrame)
}
override fun onPreEncodeVideoFrame(sourceType: Int, videoFrame: VideoFrame?) = false
override fun onMediaPlayerVideoFrame(videoFrame: VideoFrame?, mediaPlayerId: Int) = false
override fun onRenderVideoFrame(
channelId: String?,
uid: Int,
videoFrame: VideoFrame?
) = false
override fun getVideoFrameProcessMode() = IVideoFrameObserver.PROCESS_MODE_READ_WRITE
override fun getVideoFormatPreference() = IVideoFrameObserver.VIDEO_PIXEL_DEFAULT
override fun getRotationApplied() = false
override fun getMirrorApplied() = captureMirror && !enable
override fun getObservedFramePosition() = IVideoFrameObserver.POSITION_POST_CAPTURER
}

View File

@ -1,4 +1,4 @@
package com.yunbao.common.views.weight; package io.agora.beautyapi.faceunity.agora;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
@ -7,6 +7,7 @@ import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import android.view.Gravity; import android.view.Gravity;
import android.view.View; import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
import androidx.cardview.widget.CardView; import androidx.cardview.widget.CardView;
@ -19,6 +20,8 @@ import com.lzf.easyfloat.interfaces.OnInvokeView;
import com.tencent.rtmp.ITXLivePlayListener; import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLivePlayer; import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView; import com.tencent.rtmp.ui.TXCloudVideoView;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.Constants;
import com.yunbao.common.R; import com.yunbao.common.R;
import com.yunbao.common.bean.LiveBean; import com.yunbao.common.bean.LiveBean;
import com.yunbao.common.dialog.HintDialog; import com.yunbao.common.dialog.HintDialog;
@ -26,10 +29,12 @@ import com.yunbao.common.http.HttpCallback;
import com.yunbao.common.http.HttpClient; import com.yunbao.common.http.HttpClient;
import com.yunbao.common.manager.IMLoginManager; import com.yunbao.common.manager.IMLoginManager;
import com.yunbao.common.utils.DpUtil; import com.yunbao.common.utils.DpUtil;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.RouteUtil; import com.yunbao.common.utils.RouteUtil;
import com.yunbao.common.views.floatingview.APPEasyFloat; import com.yunbao.common.views.floatingview.APPEasyFloat;
import com.yunbao.common.views.floatingview.FloatingMagnetView; import com.yunbao.common.views.floatingview.FloatingMagnetView;
import com.yunbao.common.views.floatingview.MagnetViewListener; import com.yunbao.common.views.floatingview.MagnetViewListener;
import com.yunbao.common.views.weight.ViewClicksAntiShake;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function1; import kotlin.jvm.functions.Function1;
@ -45,17 +50,19 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
private String url; private String url;
private LiveBean mLiveBean; private LiveBean mLiveBean;
private int mLiveType; private int mLiveType;
private int mLiveSDK; private boolean mLiveSDK;
private int mLiveTypeVal; private int mLiveTypeVal;
private FloatCallbacks.Builder builder; private FloatCallbacks.Builder builder;
private String TAG = "LiveFloatView"; private String TAG = "LiveFloatView";
private TXLivePlayer mPlayer; private TXLivePlayer mPlayer;
private FrameLayout videoFrameLayout;
private TXCloudVideoView videoView;
private SWAuManager swAuManager;
public static LiveFloatView getInstance() { public static LiveFloatView getInstance() {
if (instance == null) { if (instance == null) {
instance = new LiveFloatView(); instance = new LiveFloatView();
} }
return instance; return instance;
} }
@ -79,7 +86,17 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
cardParams.height = DpUtil.dp2px(224); cardParams.height = DpUtil.dp2px(224);
cardParams.width = DpUtil.dp2px(126); cardParams.width = DpUtil.dp2px(126);
} }
TXCloudVideoView videoView = magnetView.findViewById(R.id.video_view); if(mLiveSDK){
L.eSw("mLiveSDK == Constants.LIVE_S2222222222222222");
videoFrameLayout = magnetView.findViewById(R.id.videoFrameLayout);
swAuManager = SWAuManager.get();
swAuManager.setAudienceContainer(videoFrameLayout);
swAuManager.initRtcEngine( mContext);
swAuManager.setupRemoteVideo(Integer.parseInt(mLiveBean.getUid()));
//进入主播房间
swAuManager.joinRoom(CommonAppConfig.getInstance().getUid(), CommonAppConfig.SWToken,mLiveBean.getUid(), SWAuManager.getChannelName(mLiveBean.getUid()));
}else{
videoView = magnetView.findViewById(R.id.video_view);
mPlayer = new TXLivePlayer(mContext); mPlayer = new TXLivePlayer(mContext);
mPlayer.setPlayerView(videoView); mPlayer.setPlayerView(videoView);
mPlayer.startPlay(url, TXLivePlayer.PLAY_TYPE_LIVE_FLV); mPlayer.startPlay(url, TXLivePlayer.PLAY_TYPE_LIVE_FLV);
@ -99,19 +116,23 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
} }
layout.setLayoutParams(cardParams); layout.setLayoutParams(cardParams);
} }
} }
@Override @Override
public void onNetStatus(Bundle bundle) { public void onNetStatus(Bundle bundle) {
} }
}); });
}
ViewClicksAntiShake.clicksAntiShake(magnetView.findViewById(R.id.btn_close), new ViewClicksAntiShake.ViewClicksCallBack() { ViewClicksAntiShake.clicksAntiShake(magnetView.findViewById(R.id.btn_close), new ViewClicksAntiShake.ViewClicksCallBack() {
@Override @Override
public void onViewClicks() { public void onViewClicks() {
if(mLiveSDK){
SWAuManager.get().exitChannelAll();
}else{
mPlayer.stopPlay(true); mPlayer.stopPlay(true);
}
APPEasyFloat.getInstance().dismiss(mContext); APPEasyFloat.getInstance().dismiss(mContext);
if (IMLoginManager.get(mContext).isHint2() && !((FragmentActivity) mContext).getSupportFragmentManager().isDestroyed()) { if (IMLoginManager.get(mContext).isHint2() && !((FragmentActivity) mContext).getSupportFragmentManager().isDestroyed()) {
HintDialog fragment = new HintDialog(); HintDialog fragment = new HintDialog();
@ -122,15 +143,22 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
} }
} }
}); });
if(mLiveSDK){
ViewClicksAntiShake.clicksAntiShake(videoFrameLayout, () -> {
SWAuManager.get().exitChannelAll();
APPEasyFloat.getInstance().dismiss(mContext);
new Handler().post(liveCheck);
});
}else{
ViewClicksAntiShake.clicksAntiShake(videoView, () -> { ViewClicksAntiShake.clicksAntiShake(videoView, () -> {
mPlayer.stopPlay(true); mPlayer.stopPlay(true);
APPEasyFloat.getInstance().dismiss(mContext); APPEasyFloat.getInstance().dismiss(mContext);
new Handler().post(liveCheck); new Handler().post(liveCheck);
}); });
} }
}
@Override @Override
public void onRemove() { public void onRemove() {
// //
@ -138,9 +166,14 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
@Override @Override
public void dismiss() { public void dismiss() {
if(mLiveSDK){
SWAuManager.get().exitChannelAll();
}else{
if (mPlayer != null) if (mPlayer != null)
mPlayer.stopPlay(true); mPlayer.stopPlay(true);
} }
}
}) })
.show(mContext); .show(mContext);
@ -161,7 +194,7 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
.show(); .show();
} }
public LiveFloatView cacheLiveData(LiveBean mLiveBean, int mLiveType, int mLiveSDK, int mLiveTypeVal) { public LiveFloatView cacheLiveData(LiveBean mLiveBean, int mLiveType, boolean mLiveSDK, int mLiveTypeVal) {
this.mLiveBean = mLiveBean; this.mLiveBean = mLiveBean;
this.mLiveType = mLiveType; this.mLiveType = mLiveType;
this.mLiveSDK = mLiveSDK; this.mLiveSDK = mLiveSDK;
@ -202,7 +235,8 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
@Override @Override
public void invoke(View view) { public void invoke(View view) {
TXCloudVideoView videoView = view.findViewById(R.id.video_view); videoFrameLayout = view.findViewById(R.id.videoFrameLayout);
L.eSw("invoke(View view) invoke(View view) invoke(View view) invoke(View view) ");
CardView layout = view.findViewById(R.id.layout); CardView layout = view.findViewById(R.id.layout);
RelativeLayout.LayoutParams cardParams = (RelativeLayout.LayoutParams) layout.getLayoutParams(); RelativeLayout.LayoutParams cardParams = (RelativeLayout.LayoutParams) layout.getLayoutParams();
if (mLiveBean.getLandscape() == 1) { if (mLiveBean.getLandscape() == 1) {
@ -213,6 +247,16 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
cardParams.width = DpUtil.dp2px(126); cardParams.width = DpUtil.dp2px(126);
} }
layout.setLayoutParams(cardParams); layout.setLayoutParams(cardParams);
if(mLiveSDK){
L.eSw("mLiveSDK == Constants.LIVE_SDK_SW mLive1111111");
swAuManager = SWAuManager.get();
swAuManager.setAudienceContainer(videoFrameLayout);
swAuManager.initRtcEngine( mContext);
swAuManager.setupRemoteVideo(Integer.parseInt(mLiveBean.getUid()));
//进入主播房间
swAuManager.joinRoom(CommonAppConfig.getInstance().getUid(), CommonAppConfig.SWToken, mLiveBean.getUid(),SWAuManager.getChannelName(mLiveBean.getUid()));
}else{
TXCloudVideoView videoView = view.findViewById(R.id.video_view);
mPlayer = new TXLivePlayer(mContext); mPlayer = new TXLivePlayer(mContext);
mPlayer.setPlayerView(videoView); mPlayer.setPlayerView(videoView);
mPlayer.startPlay(url, TXLivePlayer.PLAY_TYPE_LIVE_FLV); mPlayer.startPlay(url, TXLivePlayer.PLAY_TYPE_LIVE_FLV);
@ -240,12 +284,17 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
} }
}); });
}
ViewClicksAntiShake.clicksAntiShake(view.findViewById(R.id.btn_close), new ViewClicksAntiShake.ViewClicksCallBack() { ViewClicksAntiShake.clicksAntiShake(view.findViewById(R.id.btn_close), new ViewClicksAntiShake.ViewClicksCallBack() {
@Override @Override
public void onViewClicks() { public void onViewClicks() {
if(mLiveSDK){
SWAuManager.get().exitChannelAll();
}else{
mPlayer.stopPlay(true); mPlayer.stopPlay(true);
}
EasyFloat.dismiss("LiveFloatView", true); EasyFloat.dismiss("LiveFloatView", true);
if (IMLoginManager.get(mContext).isHint2() && !((FragmentActivity) mContext).getSupportFragmentManager().isDestroyed()) { if (IMLoginManager.get(mContext).isHint2() && !((FragmentActivity) mContext).getSupportFragmentManager().isDestroyed()) {
HintDialog fragment = new HintDialog(); HintDialog fragment = new HintDialog();
@ -257,8 +306,11 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
} }
}); });
ViewClicksAntiShake.clicksAntiShake(view, () -> { ViewClicksAntiShake.clicksAntiShake(view, () -> {
if(mLiveSDK){
SWAuManager.get().exitChannelAll();
}else{
mPlayer.stopPlay(true); mPlayer.stopPlay(true);
}
new Handler().post(liveCheck); new Handler().post(liveCheck);
@ -289,7 +341,7 @@ public class LiveFloatView implements Function1<FloatCallbacks.Builder, Unit> {
public void onSuccess(int code, String msg, String[] info) { public void onSuccess(int code, String msg, String[] info) {
if (code == 0) { if (code == 0) {
RouteUtil.forwardLiveAudienceActivity(mLiveBean, mLiveType, mLiveSDK, mLiveTypeVal); RouteUtil.forwardLiveAudienceActivity(mLiveBean, mLiveType, mLiveSDK ? Constants.LIVE_SDK_SW:Constants.LIVE_SDK_TX, mLiveTypeVal,mLiveSDK);
} else { } else {
//判断是否有直播悬浮窗有直接关闭 //判断是否有直播悬浮窗有直接关闭

View File

@ -0,0 +1,429 @@
package io.agora.beautyapi.faceunity.agora;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.FrameLayout;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.CommonAppContext;
import com.yunbao.common.bean.BaseModel;
import com.yunbao.common.bean.LiveBean;
import com.yunbao.common.bean.UserBean;
import com.yunbao.common.http.API;
import com.yunbao.common.http.ResponseModel;
import com.yunbao.common.manager.MicUserManager;
import com.yunbao.common.manager.MicedUserManager;
import com.yunbao.common.manager.base.BaseCacheManager;
import com.yunbao.common.manager.imrongcloud.RongcloudIMManager;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.StringUtil;
import com.yunbao.common.utils.ToastUtil;
import java.util.List;
import io.agora.rtc2.ChannelMediaOptions;
import io.agora.rtc2.Constants;
import io.agora.rtc2.IRtcEngineEventHandler;
import io.agora.rtc2.RtcConnection;
import io.agora.rtc2.RtcEngineConfig;
import io.agora.rtc2.RtcEngineEx;
import io.agora.rtc2.video.VideoCanvas;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.rong.imkit.IMCenter;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;
/**
* 声网主播管理类
*/
public class SWAuManager extends BaseCacheManager {
private Activity mContext;
public static SWAuManager manager;
private RtcEngineEx mRtcEngine;
private FrameLayout audienceContainer; //主播视图
private FrameLayout pkContainer1; //pk主播视图1
private FrameLayout pkContainer2; //pk主播视图2
private FrameLayout pkContainer3; //pk主播视图3
private FrameLayout linkUserContainer;//连麦用户视图
private int liveMicUid;
private SwListener swListener;
public void setSwListener(SwListener swListener) {
this.swListener = swListener;
}
public SWAuManager(Context context) {
super(context);
}
/**
* 获取单列
*
* @return
*/
public static SWAuManager get() {
if (null == manager) {
manager = new SWAuManager(CommonAppContext.sInstance.getBaseContext());
}
return manager;
}
IRtcEngineEventHandler mEventHandler = new IRtcEngineEventHandler() {
@Override
public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
super.onJoinChannelSuccess(channel, uid, elapsed);
L.eSw("加入房间成功 channel" + channel + " uid" + uid);
}
@Override
public void onUserJoined(int uid, int elapsed) {
super.onUserJoined(uid, elapsed);
L.eSw("用户加入房间成功" + uid);
}
};
/**
* 初始化声网SDK
*/
public void initRtcEngine(Activity mContext) {
this.mContext = mContext;
if(mRtcEngine==null){
try {
// 创建 RtcEngineConfig 对象并进行配置
RtcEngineConfig config = new RtcEngineConfig();
config.mContext = mContext;
config.mAppId = CommonAppConfig.getSwAppId();
config.mEventHandler = mRtcEventHandler;
// 创建并初始化 RtcEngine
mRtcEngine = (RtcEngineEx) RtcEngineEx.create(config);
} catch (Exception e) {
throw new RuntimeException("Check the error.");
}
}
mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING); // 直播模式引擎級別
// 开启本地预览
//mRtcEngine.startPreview();
}
/**
* 初始化声网SDK-语音房
*/
public void initRtcEngineAudio(Activity mContext) {
this.mContext = mContext;
try {
if(mRtcEngine==null){
RtcEngineConfig config = new RtcEngineConfig();
config.mContext = mContext;
config.mAppId = CommonAppConfig.getSwAppId();
config.mEventHandler = mEventHandler;
// 创建并初始化 RtcEngine
mRtcEngine = (RtcEngineEx) RtcEngineEx.create(config);
}
// 创建 RtcEngineConfig 对象并进行配置
mRtcEngine.enableAudio();
mRtcEngine.enableLocalAudio(true);
} catch (Exception e) {
throw new RuntimeException("Check the error.");
}
}
/**
* 创建语音房
*
* @param token
* @param channelName
* @param uid
*/
public void joinAudioRoom(String channelName, String token, int uid) {
L.eSw("加入房间" + channelName + " uid" + uid);
// 直播场景下设置频道场景为 BROADCASTING (直播场景)
mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
// 创建 ChannelMediaOptions 对象并进行配置
ChannelMediaOptions options = new ChannelMediaOptions();
// 根据场景将用户角色设置为 AUDIENCE (观众)
options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE;
mRtcEngine.disableVideo();
options.autoSubscribeAudio = true;
mRtcEngine.joinChannel(token, channelName, uid, options);
}
/**
* 更新主播视图
*
* @param frameLayout
*/
public void updateMyChannelView(FrameLayout frameLayout, int uid) {
mRtcEngine.setupLocalVideo(null);
SurfaceView surfaceView = new SurfaceView(mContext);
surfaceView.setZOrderMediaOverlay(true);
frameLayout.addView(surfaceView);
VideoCanvas videoCanvas = new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid);
mRtcEngine.setupRemoteVideo(videoCanvas);
}
/**
* 加入房间
*/
public void joinRoom(String strUid, String token, String liveUid, String channelName) {
liveMicUid = Integer.parseInt(liveUid);
int uid;
if (StringUtil.isEmpty(strUid)) {
uid = 0;
} else {
uid = Integer.parseInt(strUid);
}
// 创建一个 SurfaceView 对象并将其作为 FrameLayout 的子对象
SurfaceView surfaceView = new SurfaceView(mContext);
audienceContainer.addView(surfaceView);
// 启用视频模块
mRtcEngine.enableVideo();
//走媒体音量和音质有关
mRtcEngine.setAudioProfile(Constants.AUDIO_PROFILE_MUSIC_HIGH_QUALITY);
mRtcEngine.setAudioScenario(Constants.AUDIO_SCENARIO_GAME_STREAMING);
// 创建 ChannelMediaOptions 对象并进行配置
ChannelMediaOptions options = new ChannelMediaOptions();
// 根据场景将用户角色设置为 AUDIENCE (观众)
options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE;
// 直播场景下设置频道场景为 BROADCASTING (直播场景)
options.audienceLatencyLevel = Constants.AUDIENCE_LATENCY_LEVEL_LOW_LATENCY; // 觀眾走極速直播
// 使用临时 Token 加入频道自行指定用户 ID 并确保其在频道内的唯一性
mRtcEngine.joinChannel(token, channelName, uid, options);
}
public void joinExRoomEx(int strUid, String token, String channelName) {
// 创建 ChannelMediaOptions 对象并进行配置
ChannelMediaOptions options = new ChannelMediaOptions();
// 根据场景将用户角色设置为 AUDIENCE (观众)
options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE;
// 直播场景下设置频道场景为 BROADCASTING (直播场景)
options.audienceLatencyLevel = Constants.AUDIENCE_LATENCY_LEVEL_LOW_LATENCY; // 觀眾走極速直播
options.autoSubscribeVideo = true;
options.autoSubscribeAudio = true;
RtcConnection rtcConnection = new RtcConnection();
rtcConnection.channelId = channelName; //對方主播的頻道
rtcConnection.localUid = Integer.parseInt(CommonAppConfig.getInstance().getUid());//自己的ID
mRtcEngine.joinChannelEx(token, rtcConnection, options, new IRtcEngineEventHandler() {
@Override
public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
super.onJoinChannelSuccess(channel, uid, elapsed);
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
L.eSw("onJoinChannelSuccess:" + channel + " uid " + uid + " elapsed: " + elapsed);
SurfaceView surfaceView = new SurfaceView(mContext);
surfaceView.setZOrderMediaOverlay(true);
pkContainer1.addView(surfaceView);
VideoCanvas videoCanvas = new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, strUid);
mRtcEngine.setupRemoteVideoEx(videoCanvas, rtcConnection);
}
});
}
@Override
public void onError(int err) {
super.onError(err);
L.eSw("onError:" + err);
}
});
}
/**
* 与主播连麦
*
* @param isUp true 上麦 false 下麦
*/
public void setMicAn(boolean isUp) {
L.eSw("setMicAn-isUp:" + isUp);
ChannelMediaOptions options = new ChannelMediaOptions();
if (isUp) {
options.publishCameraTrack = false; //控制是否发视频
options.publishMicrophoneTrack = true; //控制是否发音频
options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER; //设置身份为主播
} else {
options.publishCameraTrack = false; //控制是否发视频
options.publishMicrophoneTrack = false; //控制是否发音频
options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE; //设置身份为观众
options.audienceLatencyLevel = Constants.AUDIENCE_LATENCY_LEVEL_LOW_LATENCY;//设置为极速直播观众
}
mRtcEngine.updateChannelMediaOptions(options);
}
public void setMicAudio(int toUid, boolean isEn) {
L.eSw("setMicAudio:toUid" + toUid + "isEn " + isEn);
mRtcEngine.muteRemoteAudioStream(toUid, isEn);
}
/**
* PK-加入对方主播直播间
*
* @param strUid
* @param token
* @param toUid
* @param channelName
*/
public void joinChannelDrEx(FrameLayout frameLayout, String strUid, String token, String toUid, String channelName) {
int tempUid;
if (StringUtil.isEmpty(strUid)) {
tempUid = 0;
} else {
tempUid = Integer.parseInt(strUid);
}
// 创建 ChannelMediaOptions 对象并进行配置
ChannelMediaOptions options = new ChannelMediaOptions();
// 根据场景将用户角色设置为 AUDIENCE (观众)
options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE;
options.autoSubscribeVideo = true;
options.autoSubscribeAudio = true;
options.publishMicrophoneTrack = false;
options.publishCameraTrack = false;
RtcConnection rtcConnection = new RtcConnection();
rtcConnection.channelId = channelName; //對方主播的頻道
rtcConnection.localUid = tempUid;//自己的ID
L.eSw("strUid:" + tempUid + "_token:" + token + "_channelName:" + channelName);
mRtcEngine.joinChannelEx(token, rtcConnection, options, new IRtcEngineEventHandler() {
@Override
public void onJoinChannelSuccess(String channel, int scUid, int elapsed) {
super.onJoinChannelSuccess(channel, scUid, elapsed);
L.eSw("onJoinChannelSuccess:" + channel + " uid " + scUid + " elapsed: " + elapsed);
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
SurfaceView surfaceView = new SurfaceView(mContext);
surfaceView.setZOrderMediaOverlay(true);
frameLayout.addView(surfaceView);
VideoCanvas videoCanvas = new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, Integer.parseInt(toUid));
mRtcEngine.setupRemoteVideoEx(videoCanvas, rtcConnection);
}
});
}
@Override
public void onLeaveChannel(RtcStats stats) {
super.onLeaveChannel(stats);
}
@Override
public void onError(int err) {
super.onError(err);
L.eSw("onError:" + err);
}
});
}
/**
* 退出对方直播间
*
* @param uid 自己的ID
* @param liveUid 对方直播间号
*/
public void exitChannelToUid(int uid, String liveUid) {
RtcConnection rtcConnection = new RtcConnection();
rtcConnection.channelId = getChannelName(liveUid); //對方主播的頻道
rtcConnection.localUid = uid;//自己的ID
mRtcEngine.leaveChannelEx(rtcConnection);
}
/**
* 退出所有的直播间
*/
public void exitChannelAll() {
L.eSw("exitChannelAll exitChannelAll exitChannelAll");
if (mRtcEngine != null) {
mRtcEngine.leaveChannel();
}
}
public static String getChannelName(String liveUid) {
if ( liveUid != null &&liveUid.contains("g")) {
return liveUid;
} else {
return CommonAppConfig.SWChannelPrefix + liveUid;
}
}
//远程监听
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
@Override
// 监听频道内的远端用户获取用户的 uid 信息
public void onUserJoined(int uid, int elapsed) {
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
// 获取 uid 设置远端视频视图
//setupRemoteVideo(uid);
}
});
}
@Override
public void onUserOffline(int uid, int reason) {
super.onUserOffline(uid, reason);
L.eSw("onUserOffline: uid " + uid + " reason" + reason);
if (liveMicUid == uid) {
if (swListener != null) {
swListener.onUserOffline(liveMicUid);
}
}
}
};
//设置对方主播视图
public void setupRemoteVideo(int uid) {
SurfaceView surfaceView = new SurfaceView(mContext);
surfaceView.setZOrderMediaOverlay(true);
audienceContainer.addView(surfaceView);
// SurfaceView 对象传入声网实时互动 SDK设置远端视图
mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
}
public void setAudienceContainer(FrameLayout audienceContainer) {
this.audienceContainer = audienceContainer;
}
public void setPkContainer1(FrameLayout pkContainer1) {
this.pkContainer1 = pkContainer1;
}
public void setPkContainer2(FrameLayout pkContainer2) {
this.pkContainer2 = pkContainer2;
}
public void setPkContainer3(FrameLayout pkContainer3) {
this.pkContainer3 = pkContainer3;
}
public void setLinkUserContainer(FrameLayout linkUserContainer) {
this.linkUserContainer = linkUserContainer;
}
public interface SwListener {
void onUserOffline(int liveUid);
}
public void preloadChannel(List<LiveBean> uids){
for (int i = 0; i <uids.size(); i++) {
int code = mRtcEngine.preloadChannel(CommonAppConfig.SWToken,getChannelName(uids.get(i).getUid()),Integer.parseInt(CommonAppConfig.getInstance().getUid()));
L.eSw("设置秒开数据 uid"+uids.get(i).getUid()+" --- userName:"+uids.get(i).getUserNiceName()+" code "+code);
}
}
}

View File

@ -0,0 +1,529 @@
package io.agora.beautyapi.faceunity.agora;
import android.app.Activity;
import android.content.Context;
import android.view.SurfaceView;
import android.widget.FrameLayout;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.CommonAppContext;
import com.yunbao.common.bean.SwTokenModel;
import com.yunbao.common.http.base.HttpCallback;
import com.yunbao.common.http.live.LiveNetManager;
import com.yunbao.common.manager.IMLoginManager;
import com.yunbao.common.manager.base.BaseCacheManager;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.StringUtil;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.faceunity.utils.FURenderer;
import java.util.ArrayList;
import java.util.List;
import io.agora.beautyapi.faceunity.BeautyPreset;
import io.agora.beautyapi.faceunity.CameraConfig;
import io.agora.beautyapi.faceunity.CaptureMode;
import io.agora.beautyapi.faceunity.Config;
import io.agora.beautyapi.faceunity.FaceUnityBeautyAPI;
import io.agora.beautyapi.faceunity.FaceUnityBeautyAPIKt;
import io.agora.beautyapi.faceunity.MirrorMode;
import io.agora.rtc2.ChannelMediaOptions;
import io.agora.rtc2.Constants;
import io.agora.rtc2.IRtcEngineEventHandler;
import io.agora.rtc2.RtcConnection;
import io.agora.rtc2.RtcEngineConfig;
import io.agora.rtc2.RtcEngineEx;
import io.agora.rtc2.video.ContentInspectConfig;
import io.agora.rtc2.video.VideoCanvas;
import io.agora.rtc2.video.VideoEncoderConfiguration;
/**
* 声网主播管理类
*/
public class SWManager extends BaseCacheManager {
private Activity mContext;
public static SWManager manager;
private RtcEngineEx mRtcEngine;
private final FaceUnityBeautyAPI faceUnityBeautyAPI = FaceUnityBeautyAPIKt.createFaceUnityBeautyAPI();
private int uid;
private VideoEncoderConfiguration cfg;
private FrameLayout anchorContainer; //主播视图
private FrameLayout pkContainer; //pk主播视图1
private FrameLayout linkUserContainer;//连麦用户视图
private onRtcEngineListener onRtcEngineListener;
private List<String> drPkUserInfo = new ArrayList<>();
private onDrPkJoinSuccessListener onDrPkJoinSuccessListener;
public void setOnDrPkJoinSuccessListener(SWManager.onDrPkJoinSuccessListener onDrPkJoinSuccessListener) {
this.onDrPkJoinSuccessListener = onDrPkJoinSuccessListener;
}
public void setOnRtcEngineListener(SWManager.onRtcEngineListener onRtcEngineListener) {
this.onRtcEngineListener = onRtcEngineListener;
}
public SWManager(Context context) {
super(context);
}
/**
* 获取单列
*
* @return
*/
public static SWManager get() {
if (null == manager) {
manager = new SWManager(CommonAppContext.sInstance.getBaseContext());
}
return manager;
}
/**
* 初始化声网SDK
*/
public void initRtcEngine(Activity mContext, String strUid) {
this.mContext = mContext;
if (StringUtil.isEmpty(strUid)) {
uid = 0;
} else {
uid = Integer.parseInt(strUid);
}
try {
if (mRtcEngine == null) {
// 创建 RtcEngineConfig 对象并进行配置
RtcEngineConfig config = new RtcEngineConfig();
config.mContext = mContext;
config.mAppId = CommonAppConfig.getSwAppId();
config.mEventHandler = mRtcEventHandler;
// 创建并初始化 RtcEngine
mRtcEngine = (RtcEngineEx) RtcEngineEx.create(config);
}
} catch (Exception e) {
throw new RuntimeException("Check the error.");
}
mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
// 启用视频模块
mRtcEngine.enableVideo();
// 开启本地预览
mRtcEngine.startPreview();
cfg = new VideoEncoderConfiguration();
//设置默认分辨率
VideoEncoderConfiguration.VideoDimensions videoDimensions = new VideoEncoderConfiguration.VideoDimensions();
videoDimensions.width = 720;
videoDimensions.height = 1280;
cfg.dimensions = videoDimensions;
cfg.frameRate = 20;
cfg.bitrate = 0;
//镜像
cfg.mirrorMode = VideoEncoderConfiguration.MIRROR_MODE_TYPE.MIRROR_MODE_ENABLED;
//设置竖屏
cfg.orientationMode = VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT;
mRtcEngine.setVideoEncoderConfiguration(cfg);
// 创建一个 SurfaceView 对象并将其作为 FrameLayout 的子对象
SurfaceView surfaceView = new SurfaceView(mContext);
anchorContainer.addView(surfaceView);
Config config = new Config(mContext, mRtcEngine, FURenderer.INSTANCE.mFURenderKit, null, CaptureMode.Agora, 0, false, new CameraConfig(MirrorMode.MIRROR_NONE, MirrorMode.MIRROR_NONE));
faceUnityBeautyAPI.initialize(config);
faceUnityBeautyAPI.setBeautyPreset(BeautyPreset.CUSTOM);
//FaceUnityBeautyManage.getInstance().mFURenderKit.setFaceBeauty();
// 设置视图
faceUnityBeautyAPI.setupLocalVideo(surfaceView, Constants.RENDER_MODE_HIDDEN);
//faceUnityBeautyAPI.updateCameraConfig(new CameraConfig(MirrorMode.MIRROR_NONE,MirrorMode.MIRROR_NONE));
//mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
setEnableBeauty(true); //默认开启美颜
setContentInspect(); //开启视频截图上传
}
public void setEnableBeauty(boolean flag) {
if (faceUnityBeautyAPI != null) {
faceUnityBeautyAPI.enable(flag);
}
}
/**
* 设置清晰度
* 单人直播:720x1280
* 2人连麦PK:360x640
* 3人连麦PK:左侧主播 360x640,右侧两个主播 360x320
* 4人连麦PK:360X320
*
* @param selectClarity
*/
public void setDrPkNumClarity(int selectClarity) {
if (cfg != null && mRtcEngine != null) {
VideoEncoderConfiguration.VideoDimensions videoDimensions = new VideoEncoderConfiguration.VideoDimensions();
switch (selectClarity) {
case 1:
videoDimensions.width = 720;
videoDimensions.height = 1280;
cfg.dimensions = videoDimensions;
break;
case 2:
case 3:
videoDimensions.width = 360;
videoDimensions.height = 640;
cfg.dimensions = videoDimensions;
break;
case 4:
videoDimensions.width = 360;
videoDimensions.height = 320;
cfg.dimensions = videoDimensions;
break;
}
mRtcEngine.setVideoEncoderConfiguration(cfg);
}
}
/**
* 设置镜像模式
*/
public void setMirrorMode() {
if (cfg != null && mRtcEngine != null) {
L.eSw("setMirrorMode设置镜像" + cfg.mirrorMode);
if (cfg.mirrorMode == VideoEncoderConfiguration.MIRROR_MODE_TYPE.MIRROR_MODE_ENABLED) {
cfg.mirrorMode = VideoEncoderConfiguration.MIRROR_MODE_TYPE.MIRROR_MODE_DISABLED; //取消镜像
} else {
cfg.mirrorMode = VideoEncoderConfiguration.MIRROR_MODE_TYPE.MIRROR_MODE_ENABLED; //设置镜像
}
mRtcEngine.setVideoEncoderConfiguration(cfg);
SurfaceView surfaceView = new SurfaceView(mContext);
anchorContainer.addView(surfaceView);
mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
}
}
public void setContentInspect() {
ContentInspectConfig config = new ContentInspectConfig();
config.extraInfo = "YourExtraInfo";
config.moduleCount = 1;
// 功能模块的类型为视频截图上传
config.modules[0].type = ContentInspectConfig.CONTENT_INSPECT_TYPE_SUPERVISE;
// 视频截图上传的频率为 2 秒一次
config.modules[0].interval = 2;
mRtcEngine.enableContentInspect(true, config);
}
/**
* 设置前後攝像頭
*/
public void switchCamera() {
if (mRtcEngine != null) {
mRtcEngine.switchCamera();
}
}
/**
* 创建直播间
*/
public void createChannel(String token, String channelName) {
ChannelMediaOptions options = new ChannelMediaOptions();
// 设置角色 BROADCASTER (主播) AUDIENCE (观众)
options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER;
options.publishCameraTrack = true;
options.publishMicrophoneTrack = true;
mRtcEngine.setAudioProfile(Constants.AUDIO_PROFILE_MUSIC_HIGH_QUALITY);
mRtcEngine.setAudioScenario(Constants.AUDIO_SCENARIO_GAME_STREAMING);
// 加入频道
mRtcEngine.joinChannel(token, channelName, uid, options);
}
/**
* 更新主播视图
*
* @param frameLayout
*/
public void updateMyChannelView(FrameLayout frameLayout) {
mRtcEngine.setupLocalVideo(null);
SurfaceView surfaceView = new SurfaceView(mContext);
surfaceView.setZOrderMediaOverlay(true);
frameLayout.addView(surfaceView);
VideoCanvas videoCanvas = new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid);
mRtcEngine.setupLocalVideo(videoCanvas);
}
/**
* PK-加入对方主播直播间
*
* @param strUid
* @param token
* @param toUid
* @param channelName
*/
public void joinChannelEx(String strUid, String token, String toUid, String channelName) {
int tempUid;
if (StringUtil.isEmpty(strUid)) {
tempUid = 0;
} else {
tempUid = Integer.parseInt(strUid);
}
// 创建 ChannelMediaOptions 对象并进行配置
ChannelMediaOptions options = new ChannelMediaOptions();
// 根据场景将用户角色设置为 AUDIENCE (观众)
options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE;
options.autoSubscribeVideo = true;
options.autoSubscribeAudio = true;
options.publishMicrophoneTrack = false;
options.publishCameraTrack = false;
RtcConnection rtcConnection = new RtcConnection();
rtcConnection.channelId = channelName; //對方主播的頻道
rtcConnection.localUid = tempUid;//自己的ID
L.eSw("strUid:" + tempUid + "_token:" + token + "_channelName:" + channelName);
mRtcEngine.joinChannelEx(token, rtcConnection, options, new IRtcEngineEventHandler() {
@Override
public void onJoinChannelSuccess(String channel, int scUid, int elapsed) {
super.onJoinChannelSuccess(channel, scUid, elapsed);
L.eSw("onJoinChannelSuccess:" + channel + " uid " + scUid + " elapsed: " + elapsed);
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
SurfaceView surfaceView = new SurfaceView(mContext);
surfaceView.setZOrderMediaOverlay(true);
pkContainer.addView(surfaceView);
VideoCanvas videoCanvas = new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, Integer.parseInt(toUid));
mRtcEngine.setupRemoteVideoEx(videoCanvas, rtcConnection);
}
});
}
@Override
public void onLeaveChannel(RtcStats stats) {
super.onLeaveChannel(stats);
}
@Override
public void onError(int err) {
super.onError(err);
L.eSw("onError:" + err);
}
@Override
public void onVideoSizeChanged(Constants.VideoSourceType source, int uid, int width, int height, int rotation) {
super.onVideoSizeChanged(source, uid, width, height, rotation);
L.eSw("uid:" + uid + "\nwidth:" + width + "\nheight:" + height);
}
});
}
/**
* PK-加入对方主播直播间
*
* @param strUid
* @param token
* @param toUid
* @param channelName
*/
public void joinChannelDrEx(FrameLayout frameLayout, String strUid, String token, String toUid, String channelName, int position) {
int tempUid;
if (StringUtil.isEmpty(strUid)) {
tempUid = 0;
} else {
tempUid = Integer.parseInt(strUid);
}
// 创建 ChannelMediaOptions 对象并进行配置
ChannelMediaOptions options = new ChannelMediaOptions();
// 根据场景将用户角色设置为 AUDIENCE (观众)
options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE;
options.autoSubscribeVideo = true;
options.autoSubscribeAudio = true;
options.publishMicrophoneTrack = false;
options.publishCameraTrack = false;
RtcConnection rtcConnection = new RtcConnection();
rtcConnection.channelId = channelName; //對方主播的頻道
rtcConnection.localUid = tempUid;//自己的ID
SurfaceView surfaceView = new SurfaceView(mContext);
surfaceView.setZOrderMediaOverlay(true);
frameLayout.addView(surfaceView);
VideoCanvas videoCanvas = new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, Integer.parseInt(toUid));
L.eSw("strUid:" + tempUid + "_token:" + token + "_channelName:" + channelName);
// 用内部通知刷新多人PK的用户信息
mRtcEngine.joinChannelEx(token, rtcConnection, options, new IRtcEngineEventHandler() {
@Override
public void onJoinChannelSuccess(String channel, int scUid, int elapsed) {
super.onJoinChannelSuccess(channel, scUid, elapsed);
L.eSw("onJoinChannelSuccess:" + channel + " uid " + scUid + " elapsed: " + elapsed);
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
mRtcEngine.setupRemoteVideoEx(videoCanvas, rtcConnection);
}
});
}
@Override
public void onLeaveChannel(RtcStats stats) {
super.onLeaveChannel(stats);
}
@Override
public void onError(int err) {
super.onError(err);
L.eSw("onError:" + err);
}
});
}
/**
* 退出对方直播间
*
* @param uid 自己的ID
* @param liveUid 对方直播间号
*/
public void exitChannelToUid(int uid, String liveUid) {
RtcConnection rtcConnection = new RtcConnection();
rtcConnection.channelId = getChannelName(liveUid); //對方主播的頻道
rtcConnection.localUid = uid;//自己的ID
mRtcEngine.leaveChannelEx(rtcConnection);
}
/**
* 退出所有频道
*/
public void exitChannelAll() {
if (mRtcEngine != null) {
mRtcEngine.leaveChannel();
}
}
public void setAnchorContainer(FrameLayout anchorContainer) {
this.anchorContainer = anchorContainer;
}
//远程监听
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
@Override
// 监听频道内的远端用户获取用户的 uid 信息
public void onUserJoined(int uid, int elapsed) {
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
// 获取 uid 设置远端视频视图
//setupRemoteVideo(uid);
}
});
}
@Override
public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
super.onJoinChannelSuccess(channel, uid, elapsed);
L.eSw("onJoinChannelSuccess 加入频道channel" + channel + " uid:" + uid + " elapsed:" + elapsed);
if (onRtcEngineListener != null) {
onRtcEngineListener.onOpenSuccess(channel, uid);
}
}
@Override
public void onUserOffline(int uid, int reason) {
super.onUserOffline(uid, reason);
if (onRtcEngineListener != null) {
//onRtcEngineListener.onOpenSuccess(channel, uid);
}
}
@Override
public void onError(int err) {
super.onError(err);
L.eSw("onError 错误码:" + err);
ToastUtil.show("onError:" + err);
}
@Override
public void onTokenPrivilegeWillExpire(String token) {
super.onTokenPrivilegeWillExpire(token);
L.eSw("onTokenPrivilegeWillExpire_Token 即将失效");
refreshToken();
}
@Override
public void onRequestToken() {
super.onRequestToken();
L.eSw("onRequestToken_Token失效");
refreshToken();
}
@Override
public void onLeaveChannel(RtcStats stats) {
super.onLeaveChannel(stats);
L.eSw("onLeaveChannel退出頻道");
}
@Override
public void onLocalVideoStateChanged(Constants.VideoSourceType source, int state, int error) {
super.onLocalVideoStateChanged(source, state, error);
L.eSw("onLocalVideoStateChanged_source" + source + " state_" + state + " error_" + error);
}
};
private void refreshToken() {
LiveNetManager.get(mContext).getSwToken(new HttpCallback<SwTokenModel>() {
@Override
public void onSuccess(SwTokenModel data) {
if (mRtcEngine != null) {
mRtcEngine.renewToken(data.getToken());
}
L.eSw("refreshToken_重新获取Token成功");
}
@Override
public void onError(String error) {
}
});
}
public interface onRtcEngineListener {
void onOpenSuccess(String channel, int uid);
void onUserOffline(int uid);
}
public void setPkContainer(FrameLayout pkContainer) {
this.pkContainer = pkContainer;
}
public void setLinkUserContainer(FrameLayout linkUserContainer) {
this.linkUserContainer = linkUserContainer;
}
public static String getChannelName(String liveUid) {
if (liveUid.contains("g")) {
return liveUid;
} else {
return CommonAppConfig.SWChannelPrefix + liveUid;
}
}
public interface onDrPkJoinSuccessListener {
void joinSuccess1();
void joinSuccess2();
void joinSuccess3();
void joinSuccess4();
}
}

View File

@ -0,0 +1,607 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity.utils;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class FuDeviceUtils {
public static final String TAG = "FuDeviceUtils";
public static final int DEVICE_LEVEL_HIGH = 2;
public static final int DEVICE_LEVEL_MID = 1;
public static final int DEVICE_LEVEL_LOW = 0;
/**
* The default return value of any method in this class when an
* error occurs or when processing fails (Currently set to -1). Use this to check if
* the information about the device in question was successfully obtained.
*/
public static final int DEVICEINFO_UNKNOWN = -1;
private static final FileFilter CPU_FILTER = new FileFilter() {
@Override
public boolean accept(File pathname) {
String path = pathname.getName();
//regex is slow, so checking char by char.
if (path.startsWith("cpu")) {
for (int i = 3; i < path.length(); i++) {
if (!Character.isDigit(path.charAt(i))) {
return false;
}
}
return true;
}
return false;
}
};
/**
* Calculates the total RAM of the device through Android API or /proc/meminfo.
*
* @param c - Context object for current running activity.
* @return Total RAM that the device has, or DEVICEINFO_UNKNOWN = -1 in the event of an error.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static long getTotalMemory(Context c) {
// memInfo.totalMem not supported in pre-Jelly Bean APIs.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
am.getMemoryInfo(memInfo);
if (memInfo != null) {
return memInfo.totalMem;
} else {
return DEVICEINFO_UNKNOWN;
}
} else {
long totalMem = DEVICEINFO_UNKNOWN;
try {
FileInputStream stream = new FileInputStream("/proc/meminfo");
try {
totalMem = parseFileForValue("MemTotal", stream);
totalMem *= 1024;
} finally {
stream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return totalMem;
}
}
/**
* Method for reading the clock speed of a CPU core on the device. Will read from either
* {@code /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq} or {@code /proc/cpuinfo}.
*
* @return Clock speed of a core on the device, or -1 in the event of an error.
*/
public static int getCPUMaxFreqKHz() {
int maxFreq = DEVICEINFO_UNKNOWN;
try {
for (int i = 0; i < getNumberOfCPUCores(); i++) {
String filename =
"/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq";
File cpuInfoMaxFreqFile = new File(filename);
if (cpuInfoMaxFreqFile.exists() && cpuInfoMaxFreqFile.canRead()) {
byte[] buffer = new byte[128];
FileInputStream stream = new FileInputStream(cpuInfoMaxFreqFile);
try {
stream.read(buffer);
int endIndex = 0;
//Trim the first number out of the byte buffer.
while (Character.isDigit(buffer[endIndex]) && endIndex < buffer.length) {
endIndex++;
}
String str = new String(buffer, 0, endIndex);
Integer freqBound = Integer.parseInt(str);
if (freqBound > maxFreq) {
maxFreq = freqBound;
}
} catch (NumberFormatException e) {
//Fall through and use /proc/cpuinfo.
} finally {
stream.close();
}
}
}
if (maxFreq == DEVICEINFO_UNKNOWN) {
FileInputStream stream = new FileInputStream("/proc/cpuinfo");
try {
int freqBound = parseFileForValue("cpu MHz", stream);
freqBound *= 1024; //MHz -> kHz
if (freqBound > maxFreq) maxFreq = freqBound;
} finally {
stream.close();
}
}
} catch (IOException e) {
maxFreq = DEVICEINFO_UNKNOWN; //Fall through and return unknown.
}
return maxFreq;
}
/**
* Reads the number of CPU cores from the first available information from
* {@code /sys/devices/system/cpu/possible}, {@code /sys/devices/system/cpu/present},
* then {@code /sys/devices/system/cpu/}.
*
* @return Number of CPU cores in the phone, or DEVICEINFO_UKNOWN = -1 in the event of an error.
*/
public static int getNumberOfCPUCores() {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
// Gingerbread doesn't support giving a single application access to both cores, but a
// handful of devices (Atrix 4G and Droid X2 for example) were released with a dual-core
// chipset and Gingerbread; that can let an app in the background run without impacting
// the foreground application. But for our purposes, it makes them single core.
return 1;
}
int cores;
try {
cores = getCoresFromFileInfo("/sys/devices/system/cpu/possible");
if (cores == DEVICEINFO_UNKNOWN) {
cores = getCoresFromFileInfo("/sys/devices/system/cpu/present");
}
if (cores == DEVICEINFO_UNKNOWN) {
cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length;
}
} catch (SecurityException e) {
cores = DEVICEINFO_UNKNOWN;
} catch (NullPointerException e) {
cores = DEVICEINFO_UNKNOWN;
}
return cores;
}
/**
* Tries to read file contents from the file location to determine the number of cores on device.
*
* @param fileLocation The location of the file with CPU information
* @return Number of CPU cores in the phone, or DEVICEINFO_UKNOWN = -1 in the event of an error.
*/
private static int getCoresFromFileInfo(String fileLocation) {
InputStream is = null;
try {
is = new FileInputStream(fileLocation);
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
String fileContents = buf.readLine();
buf.close();
return getCoresFromFileString(fileContents);
} catch (IOException e) {
return DEVICEINFO_UNKNOWN;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// Do nothing.
}
}
}
}
/**
* Converts from a CPU core information format to number of cores.
*
* @param str The CPU core information string, in the format of "0-N"
* @return The number of cores represented by this string
*/
private static int getCoresFromFileString(String str) {
if (str == null || !str.matches("0-[\\d]+$")) {
return DEVICEINFO_UNKNOWN;
}
return Integer.valueOf(str.substring(2)) + 1;
}
/**
* Helper method for reading values from system files, using a minimised buffer.
*
* @param textToMatch - Text in the system files to read for.
* @param stream - FileInputStream of the system file being read from.
* @return A numerical value following textToMatch in specified the system file.
* -1 in the event of a failure.
*/
private static int parseFileForValue(String textToMatch, FileInputStream stream) {
byte[] buffer = new byte[1024];
try {
int length = stream.read(buffer);
for (int i = 0; i < length; i++) {
if (buffer[i] == '\n' || i == 0) {
if (buffer[i] == '\n') i++;
for (int j = i; j < length; j++) {
int textIndex = j - i;
//Text doesn't match query at some point.
if (buffer[j] != textToMatch.charAt(textIndex)) {
break;
}
//Text matches query here.
if (textIndex == textToMatch.length() - 1) {
return extractValue(buffer, j);
}
}
}
}
} catch (IOException e) {
//Ignore any exceptions and fall through to return unknown value.
} catch (NumberFormatException e) {
}
return DEVICEINFO_UNKNOWN;
}
/**
* Helper method used by {@link #parseFileForValue(String, FileInputStream) parseFileForValue}. Parses
* the next available number after the match in the file being read and returns it as an integer.
*
* @param index - The index in the buffer array to begin looking.
* @return The next number on that line in the buffer, returned as an int. Returns
* DEVICEINFO_UNKNOWN = -1 in the event that no more numbers exist on the same line.
*/
private static int extractValue(byte[] buffer, int index) {
while (index < buffer.length && buffer[index] != '\n') {
if (Character.isDigit(buffer[index])) {
int start = index;
index++;
while (index < buffer.length && Character.isDigit(buffer[index])) {
index++;
}
String str = new String(buffer, 0, start, index - start);
return Integer.parseInt(str);
}
index++;
}
return DEVICEINFO_UNKNOWN;
}
/**
* 获取当前剩余内存(ram)
*
* @param context
* @return
*/
public static long getAvailMemory(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
am.getMemoryInfo(mi);
return mi.availMem;
}
/**
* 获取厂商信息
*
* @return
*/
public static String getBrand() {
return Build.BRAND;
}
/**
* 获取手机机型
*
* @return
*/
public static String getModel() {
return Build.MODEL;
}
/**
* 获取硬件信息(cpu型号)
*
* @return
*/
public static String getHardWare() {
try {
FileReader fr = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fr);
String text;
String last = "";
while ((text = br.readLine()) != null) {
last = text;
}
//一般机型的cpu型号都会在cpuinfo文件的最后一行
if (last.contains("Hardware")) {
String[] hardWare = last.split(":\\s+", 2);
return hardWare[1];
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Build.HARDWARE;
}
/**
* Level judgement based on current memory and CPU.
*
* @param context - Context object.
* @return
*/
public static int judgeDeviceLevel(Context context) {
int level;
//有一些设备不符合下述的判断规则则走一个机型判断模式
int specialDevice = judgeDeviceLevelInDeviceName();
if (specialDevice >= 0) return specialDevice;
int ramLevel = judgeMemory(context);
int cpuLevel = judgeCPU();
if (ramLevel == 0 || ramLevel == 1 || cpuLevel == 0) {
level = DEVICE_LEVEL_LOW;
} else {
if (cpuLevel > 1) {
level = DEVICE_LEVEL_HIGH;
} else {
level = DEVICE_LEVEL_MID;
}
}
LogUtils.d(TAG,"DeviceLevel: " + level);
return level;
}
/**
* -1 不是特定的高低端机型
* @return
*/
private static int judgeDeviceLevelInDeviceName() {
String currentDeviceName = getDeviceName();
for (String deviceName:upscaleDevice) {
if (deviceName.equals(currentDeviceName)) {
return DEVICE_LEVEL_HIGH;
}
}
for (String deviceName:middleDevice) {
if (deviceName.equals(currentDeviceName)) {
return DEVICE_LEVEL_MID;
}
}
for (String deviceName:lowDevice) {
if (deviceName.equals(currentDeviceName)) {
return DEVICE_LEVEL_LOW;
}
}
return -1;
}
public static final String[] upscaleDevice = {"vivo X6S A","MHA-AL00","VKY-AL00","V1838A"};
public static final String[] lowDevice = {};
public static final String[] middleDevice = {"OPPO R11s","PAR-AL00","MI 8 Lite","ONEPLUS A6000","PRO 6","PRO 7 Plus"};
/**
* 评定内存的等级.
*
* @return
*/
private static int judgeMemory(Context context) {
long ramMB = getTotalMemory(context) / (1024 * 1024);
int level = -1;
if (ramMB <= 2000) { //2G或以下的最低档
level = 0;
} else if (ramMB <= 3000) { //2-3G
level = 1;
} else if (ramMB <= 4000) { //4G档 2018主流中端机
level = 2;
} else if (ramMB <= 6000) { //6G档 高端机
level = 3;
} else { //6G以上 旗舰机配置
level = 4;
}
return level;
}
/**
* 评定CPU等级.按频率和厂商型号综合判断
*
* @return
*/
private static int judgeCPU() {
int level = 0;
String cpuName = getHardWare();
int freqMHz = getCPUMaxFreqKHz() / 1024;
//一个不符合下述规律的高级白名单
//如果可以获取到CPU型号名称 -> 根据不同的名称走不同判定策略
if (!TextUtils.isEmpty(cpuName)) {
if (cpuName.contains("qcom") || cpuName.contains("Qualcomm")) { //高通骁龙
return judgeQualcommCPU(cpuName, freqMHz);
} else if (cpuName.contains("hi") || cpuName.contains("kirin")) { //海思麒麟
return judgeSkinCPU(cpuName, freqMHz);
} else if (cpuName.contains("MT")) {//联发科
return judgeMTCPU(cpuName, freqMHz);
}
}
//cpu型号无法获取的普通规则
if (freqMHz <= 1600) { //1.5G 低端
level = 0;
} else if (freqMHz <= 1950) { //2GHz 低中端
level = 1;
} else if (freqMHz <= 2500) { //2.2 2.3g 中高端
level = 2;
} else { //高端
level = 3;
}
return level;
}
/**
* 联发科芯片等级判定
*
* @return
*/
private static int judgeMTCPU(String cpuName, int freqMHz) {
//P60之前的全是低端机 MT6771V/C
int level = 0;
int mtCPUVersion = getMTCPUVersion(cpuName);
if (mtCPUVersion == -1) {
//读取不出version 按照一个比较严格的方式来筛选出高端机
if (freqMHz <= 1600) { //1.5G 低端
level = 0;
} else if (freqMHz <= 2200) { //2GHz 低中端
level = 1;
} else if (freqMHz <= 2700) { //2.2 2.3g 中高端
level = 2;
} else { //高端
level = 3;
}
} else if (mtCPUVersion < 6771) {
//均为中低端机
if (freqMHz <= 1600) { //1.5G 低端
level = 0;
} else { //2GHz 中端
level = 1;
}
} else {
if (freqMHz <= 1600) { //1.5G 低端
level = 0;
} else if (freqMHz <= 1900) { //2GHz 低中端
level = 1;
} else if (freqMHz <= 2500) { //2.2 2.3g 中高端
level = 2;
} else { //高端
level = 3;
}
}
return level;
}
/**
* 通过联发科CPU型号定义 -> 获取cpu version
*
* @param cpuName
* @return
*/
private static int getMTCPUVersion(String cpuName) {
//截取MT后面的四位数字
int cpuVersion = -1;
if (cpuName.length() > 5) {
String cpuVersionStr = cpuName.substring(2, 6);
try {
cpuVersion = Integer.valueOf(cpuVersionStr);
} catch (NumberFormatException exception) {
exception.printStackTrace();
}
}
return cpuVersion;
}
/**
* 高通骁龙芯片等级判定
*
* @return
*/
private static int judgeQualcommCPU(String cpuName, int freqMHz) {
int level = 0;
//xxxx inc MSM8937 比较老的芯片
//7 8 xxx inc SDM710
if (cpuName.contains("MSM")) {
//老芯片
if (freqMHz <= 1600) { //1.5G 低端
level = 0;
} else { //2GHz 低中端
level = 1;
}
} else {
//新的芯片
if (freqMHz <= 1600) { //1.5G 低端
level = 0;
} else if (freqMHz <= 2000) { //2GHz 低中端
level = 1;
} else if (freqMHz <= 2500) { //2.2 2.3g 中高端
level = 2;
} else { //高端
level = 3;
}
}
return level;
}
/**
* 麒麟芯片等级判定
*
* @param freqMHz
* @return
*/
private static int judgeSkinCPU(String cpuName, int freqMHz) {
//型号 -> kirin710之后 & 最高核心频率
int level = 0;
if (cpuName.startsWith("hi")) {
//这个是海思的芯片中低端
if (freqMHz <= 1600) { //1.5G 低端
level = 0;
} else if (freqMHz <= 2000) { //2GHz 低中端
level = 1;
}
} else {
//这个是海思麒麟的芯片
if (freqMHz <= 1600) { //1.5G 低端
level = 0;
} else if (freqMHz <= 2000) { //2GHz 低中端
level = 1;
} else if (freqMHz <= 2500) { //2.2 2.3g 中高端
level = 2;
} else { //高端
level = 3;
}
}
return level;
}
public static final String Nexus_6P = "Nexus 6P";
/**
* 获取设备名
*
* @return
*/
public static String getDeviceName() {
String deviceName = "";
if (Build.MODEL != null) deviceName = Build.MODEL;
LogUtils.e(TAG,"deviceName: " + deviceName);
return deviceName;
}
}

View File

@ -0,0 +1,57 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity.utils
import io.agora.base.internal.Logging
object LogUtils {
private const val beautyType = "FaceUnity"
@JvmStatic
fun i(tag: String, content: String, vararg args: Any) {
val consoleMessage = "[BeautyAPI][$beautyType] : ${String.format(content, args)}"
Logging.log(Logging.Severity.LS_INFO, tag, consoleMessage)
}
@JvmStatic
fun d(tag: String, content: String, vararg args: Any) {
val consoleMessage = "[BeautyAPI][$beautyType] : ${String.format(content, args)}"
Logging.d(tag, consoleMessage)
}
@JvmStatic
fun w(tag: String, content: String, vararg args: Any){
val consoleMessage = "[BeautyAPI][$beautyType] : ${String.format(content, args)}"
Logging.w(tag, consoleMessage)
}
@JvmStatic
fun e(tag: String, content: String, vararg args: Any){
val consoleMessage = "[BeautyAPI][$beautyType] : ${String.format(content, args)}"
Logging.e(tag, consoleMessage)
}
}

View File

@ -0,0 +1,80 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity.utils
import android.os.Handler
import android.os.Looper
import io.agora.beautyapi.faceunity.BeautyStats
import kotlin.math.max
import kotlin.math.min
class StatsHelper(
private val statsDuration: Long,
private val onStatsChanged: (BeautyStats) -> Unit
) {
private val mMainHandler = Handler(Looper.getMainLooper())
private var mStartTime = 0L
private var mCostList = mutableListOf<Long>()
private var mCostMax = 0L
private var mCostMin = Long.MAX_VALUE
fun once(cost: Long) {
val curr = System.currentTimeMillis()
if (mStartTime == 0L) {
mStartTime = curr
} else if (curr - mStartTime >= statsDuration) {
mStartTime = curr
var total = 0L
mCostList.forEach {
total += it
}
val average = total / mCostList.size
val costMin = mCostMin
val costMax = mCostMax
mMainHandler.post {
onStatsChanged.invoke(BeautyStats(costMin, costMax, average))
}
mCostList.clear()
mCostMax = 0L
mCostMin = Long.MAX_VALUE
}
mCostList.add(cost)
mCostMax = max(mCostMax, cost)
mCostMin = min(mCostMin, cost)
}
fun reset() {
mMainHandler.removeCallbacksAndMessages(null)
mStartTime = 0
mCostList.clear()
mCostMax = 0L
mCostMin = Long.MAX_VALUE
}
}

View File

@ -0,0 +1,210 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity.utils.egl;
import static android.opengl.EGL14.EGL_CONTEXT_CLIENT_VERSION;
import android.opengl.GLDebugHelper;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import io.agora.beautyapi.faceunity.utils.LogUtils;
public class EGLContextHelper {
private static final String DEBUG_TAG = "EGLContextManager";
private final int mRedSize = 8;
private final int mGreenSize = 8;
private final int mBlueSize = 8;
private final int mAlphaSize = 0;
private final int mDepthSize = 16;
private final int mStencilSize = 0;
private final int mRenderType = 4;
public EGLContextHelper(){}
public void initEGL(EGLContext shareContext) throws Exception {
mEGL = (EGL10) GLDebugHelper.wrap(EGLContext.getEGL(),
GLDebugHelper.CONFIG_CHECK_GL_ERROR
| GLDebugHelper.CONFIG_CHECK_THREAD, null);
if (mEGL == null) {
throw new Exception("Couldn't get EGL");
}
mGLDisplay = mEGL.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (mGLDisplay == null) {
throw new Exception("Couldn't get display for GL");
}
int[] curGLVersion = new int[2];
mEGL.eglInitialize(mGLDisplay, curGLVersion);
LogUtils.i(DEBUG_TAG, "GL version = " + curGLVersion[0] + "."
+ curGLVersion[1]);
int[] num_config = new int[1];
if(!mEGL.eglChooseConfig(mGLDisplay, mConfigSpec, null, 1,
num_config)){
throw new IllegalArgumentException("eglChooseConfig failed");
}
int numConfigs = num_config[0];
if (numConfigs <= 0) {
throw new IllegalArgumentException(
"No configs match configSpec");
}
EGLConfig[] configs = new EGLConfig[numConfigs];
if (!mEGL.eglChooseConfig(mGLDisplay, mConfigSpec, configs, numConfigs,
num_config)) {
throw new IllegalArgumentException("eglChooseConfig#2 failed");
}
mGLConfig = chooseConfig(mEGL, mGLDisplay, configs);
if (mGLConfig == null) {
mGLConfig = configs[0];
}
int[] surfaceAttribs = {
EGL10.EGL_WIDTH, 1,
EGL10.EGL_HEIGHT, 1,
EGL10.EGL_NONE
};
mGLSurface = mEGL.eglCreatePbufferSurface(mGLDisplay, mGLConfig, surfaceAttribs);
if (mGLSurface == null) {
throw new Exception("Couldn't create new surface");
}
int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE};
mGLContext = mEGL.eglCreateContext(mGLDisplay, mGLConfig,
shareContext, attrib_list);
if (mGLContext == null) {
throw new Exception("Couldn't create new context");
}
// if (!mEGL.eglMakeCurrent(mGLDisplay, mGLSurface, mGLSurface, mGLContext)) {
// throw new Exception("Failed to eglMakeCurrent");
// }
}
public EGLContext getEGLContext() {
return mGLContext;
}
public EGLDisplay getGLDisplay() {
return mGLDisplay;
}
public EGLConfig getGLConfig() {
return mGLConfig;
}
public EGLSurface getGLSurface() {
return mGLSurface;
}
public EGL10 getEGL() {
return mEGL;
}
EGL10 mEGL;
EGLDisplay mGLDisplay;
EGLConfig mGLConfig;
EGLSurface mGLSurface;
EGLContext mGLContext;
int[] mConfigSpec = new int[]{
EGL10.EGL_RED_SIZE, mRedSize,
EGL10.EGL_GREEN_SIZE, mGreenSize,
EGL10.EGL_BLUE_SIZE, mBlueSize,
EGL10.EGL_ALPHA_SIZE, mAlphaSize,
EGL10.EGL_DEPTH_SIZE, mDepthSize,
EGL10.EGL_STENCIL_SIZE, mStencilSize,
EGL10.EGL_RENDERABLE_TYPE, mRenderType,//egl版本 2.0
EGL10.EGL_NONE};
public void release() {
mEGL.eglMakeCurrent(mGLDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEGL.eglDestroySurface(mGLDisplay, mGLSurface);
mEGL.eglDestroyContext(mGLDisplay, mGLContext);
mEGL.eglTerminate(mGLDisplay);
LogUtils.i(DEBUG_TAG, "GL Cleaned up");
}
public boolean eglMakeCurrent(){
if(mGLContext == EGL10.EGL_NO_CONTEXT){
return false;
}else{
return mEGL.eglMakeCurrent(mGLDisplay, mGLSurface, mGLSurface, mGLContext);
}
}
public boolean eglMakeNoCurrent(){
return mEGL.eglMakeCurrent(mGLDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
}
private EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
EGLConfig[] configs) {
for (EGLConfig config : configs) {
int d = findConfigAttrib(egl, display, config,
EGL10.EGL_DEPTH_SIZE, 0);
int s = findConfigAttrib(egl, display, config,
EGL10.EGL_STENCIL_SIZE, 0);
if ((d >= mDepthSize) && (s >= mStencilSize)) {
int r = findConfigAttrib(egl, display, config,
EGL10.EGL_RED_SIZE, 0);
int g = findConfigAttrib(egl, display, config,
EGL10.EGL_GREEN_SIZE, 0);
int b = findConfigAttrib(egl, display, config,
EGL10.EGL_BLUE_SIZE, 0);
int a = findConfigAttrib(egl, display, config,
EGL10.EGL_ALPHA_SIZE, 0);
if ((r == mRedSize) && (g == mGreenSize)
&& (b == mBlueSize) && (a == mAlphaSize)) {
return config;
}
}
}
return null;
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display,
EGLConfig config, int attribute, int defaultValue) {
int[] value = new int[1];
if (egl.eglGetConfigAttrib(display, config, attribute, value)) {
return value[0];
}
return defaultValue;
}
}

View File

@ -0,0 +1,84 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity.utils.egl;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.GLES30;
public class GLCopyHelper {
private final int bufferCount;
public GLCopyHelper(){
this(1);
}
public GLCopyHelper(int bufferCount){
this.bufferCount = bufferCount;
}
private int[] mDstFrameBuffer;
private int[] mSrcFrameBuffer;
public void copy2DTextureToOesTexture(
int srcTexture,
int dstTexture,
int width, int height,
int index){
if(mDstFrameBuffer == null){
mDstFrameBuffer = new int[bufferCount];
GLES20.glGenFramebuffers(bufferCount, mDstFrameBuffer, 0);
}
if(mSrcFrameBuffer == null){
mSrcFrameBuffer = new int[bufferCount];
GLES20.glGenFramebuffers(bufferCount, mSrcFrameBuffer, 0);
}
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, mSrcFrameBuffer[index]);
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, srcTexture);
GLES30.glFramebufferTexture2D(GLES30.GL_READ_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, srcTexture, 0);
GLES30.glBindFramebuffer(GLES30.GL_DRAW_FRAMEBUFFER, mDstFrameBuffer[index]);
GLES30.glFramebufferTexture2D(GLES30.GL_DRAW_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0, GLES11Ext.GL_TEXTURE_EXTERNAL_OES, dstTexture, 0);
GLES30.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GLES30.GL_COLOR_BUFFER_BIT, GLES30.GL_LINEAR);
GLES30.glBindFramebuffer(GLES30.GL_DRAW_FRAMEBUFFER, 0);
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, 0);
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
}
public void release(){
if(mDstFrameBuffer != null){
GLES20.glDeleteFramebuffers(mDstFrameBuffer.length, mDstFrameBuffer, 0);
mDstFrameBuffer = null;
}
if(mSrcFrameBuffer != null){
GLES20.glDeleteFramebuffers(mSrcFrameBuffer.length, mSrcFrameBuffer, 0);
mSrcFrameBuffer = null;
}
}
}

View File

@ -0,0 +1,205 @@
package io.agora.beautyapi.faceunity.utils.egl;
import android.graphics.Matrix;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import io.agora.base.internal.video.EglBase;
import io.agora.base.internal.video.GlRectDrawer;
import io.agora.base.internal.video.RendererCommon;
public class GLFrameBuffer {
private int mFramebufferId = -1;
private int mTextureId = -1;
private int mWidth, mHeight, mRotation;
private boolean isFlipV, isFlipH, isTextureInner, isTextureChanged, isSizeChanged;
private RendererCommon.GlDrawer drawer;
private float[] mTexMatrix = GLUtils.IDENTITY_MATRIX;
public GLFrameBuffer() {
}
public boolean setSize(int width, int height) {
if (mWidth != width || mHeight != height) {
mWidth = width;
mHeight = height;
isSizeChanged = true;
return true;
}
return false;
}
public void setRotation(int rotation) {
if (mRotation != rotation) {
mRotation = rotation;
}
}
public void setFlipV(boolean flipV) {
if (isFlipV != flipV) {
isFlipV = flipV;
}
}
public void setFlipH(boolean flipH) {
if (isFlipH != flipH) {
isFlipH = flipH;
}
}
public void setTextureId(int textureId){
if(mTextureId != textureId){
deleteTexture();
mTextureId = textureId;
isTextureChanged = true;
}
}
public int getTextureId(){
return mTextureId;
}
public void setTexMatrix(float[] matrix) {
if (matrix != null) {
mTexMatrix = matrix;
} else {
mTexMatrix = GLUtils.IDENTITY_MATRIX;
}
}
public void resetTransform(){
mTexMatrix = GLUtils.IDENTITY_MATRIX;
isFlipH = isFlipV = false;
mRotation = 0;
}
public int process(int textureId, int textureType) {
if (mWidth <= 0 && mHeight <= 0) {
throw new RuntimeException("setSize firstly!");
}
if(mTextureId == -1){
mTextureId = createTexture(mWidth, mHeight);
bindFramebuffer(mTextureId);
isTextureInner = true;
}else if(isTextureInner && isSizeChanged){
GLES20.glDeleteTextures(1, new int[]{mTextureId}, 0);
mTextureId = createTexture(mWidth, mHeight);
bindFramebuffer(mTextureId);
}else if(isTextureChanged){
bindFramebuffer(mTextureId);
}
isTextureChanged = false;
isSizeChanged = false;
if(drawer == null){
drawer = new GlRectDrawer();
}
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFramebufferId);
GLUtils.checkGlError("glBindFramebuffer");
Matrix transform = RendererCommon.convertMatrixToAndroidGraphicsMatrix(mTexMatrix);
transform.preTranslate(0.5f, 0.5f);
transform.preRotate(mRotation, 0.f, 0.f);
transform.preScale(
isFlipH ? -1.f: 1.f,
isFlipV ? -1.f: 1.f
);
transform.preTranslate(-0.5f, -0.5f);
float[] matrix = RendererCommon.convertMatrixFromAndroidGraphicsMatrix(transform);
synchronized (EglBase.lock){
if(textureType == GLES11Ext.GL_TEXTURE_EXTERNAL_OES){
drawer.drawOes(textureId,matrix, mWidth, mHeight, 0, 0, mWidth, mHeight);
}else{
drawer.drawRgb(textureId, matrix, mWidth, mHeight, 0, 0, mWidth, mHeight);
}
}
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, GLES20.GL_NONE);
GLES20.glFinish();
return mTextureId;
}
public void release(){
deleteTexture();
deleteFramebuffer();
if(drawer != null){
drawer.release();
drawer = null;
}
}
private void deleteFramebuffer() {
if (mFramebufferId != -1) {
GLES20.glDeleteFramebuffers(1, new int[]{mFramebufferId}, 0);
mFramebufferId = -1;
}
}
public int createTexture(int width, int height){
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
GLUtils.checkGlError("glGenTextures");
int textureId = textures[0];
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, GLES20.GL_NONE);
return textureId;
}
public void resizeTexture(int textureId, int width, int height) {
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, GLES20.GL_NONE);
}
private void deleteTexture() {
if (isTextureInner && mTextureId != -1) {
GLES20.glDeleteTextures(1, new int[]{mTextureId}, 0);
}
isTextureInner = false;
mTextureId = -1;
}
private void bindFramebuffer(int textureId) {
if(mFramebufferId == -1){
int[] framebuffers = new int[1];
GLES20.glGenFramebuffers(1, framebuffers, 0);
GLUtils.checkGlError("glGenFramebuffers");
mFramebufferId = framebuffers[0];
}
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFramebufferId);
GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER,
GLES20.GL_COLOR_ATTACHMENT0,
GLES20.GL_TEXTURE_2D,
textureId, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, GLES20.GL_NONE);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, GLES20.GL_NONE);
}
}

View File

@ -0,0 +1,180 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity.utils.egl
import android.opengl.GLES20
import android.util.Log
import android.util.Size
import java.util.concurrent.ConcurrentLinkedQueue
class GLTextureBufferQueue(
private val glFrameBuffer: GLFrameBuffer = GLFrameBuffer(),
private val cacheCount: Int = 6,
private val loggable: Boolean = false
) {
private val TAG = "GLTextureBufferQueue"
private var cacheIndex = 0
private val cacheTextureOuts = arrayOfNulls<TextureOut>(cacheCount)
private val textureIdQueue = ConcurrentLinkedQueue<TextureOut>()
fun enqueue(iN: TextureIn): Int {
var size = textureIdQueue.size
if (size < cacheCount) {
var out = cacheTextureOuts[cacheIndex]
val outSize = when (iN.rotation) {
90, 270 -> Size(iN.height, iN.width)
else -> Size(iN.width, iN.height)
}
if (out == null) {
val textureId = glFrameBuffer.createTexture(outSize.width, outSize.height)
out = TextureOut(
0,
textureId,
GLES20.GL_TEXTURE_2D,
outSize.width,
outSize.height,
iN.isFrontCamera,
iN.isMirror,
)
cacheTextureOuts[cacheIndex] = out
} else if (out.width != outSize.width || out.height != outSize.height) {
glFrameBuffer.resizeTexture(out.textureId, outSize.width, outSize.height)
out = TextureOut(
0,
out.textureId,
out.textureType,
outSize.width,
outSize.height,
iN.isFrontCamera,
iN.isMirror,
)
cacheTextureOuts[cacheIndex] = out
} else if(out.isFrontCamera != iN.isFrontCamera){
out = TextureOut(
0,
out.textureId,
out.textureType,
out.width,
out.height,
iN.isFrontCamera,
iN.isMirror,
)
cacheTextureOuts[cacheIndex] = out
}
glFrameBuffer.textureId = out.textureId
glFrameBuffer.setSize(out.width, out.height)
glFrameBuffer.resetTransform()
glFrameBuffer.setRotation(iN.rotation)
if (iN.transform != null) {
glFrameBuffer.setTexMatrix(iN.transform)
var flipH = iN.isFrontCamera
if(iN.isMirror){
flipH = !flipH
}
glFrameBuffer.setFlipH(flipH)
} else {
var flipH = !iN.isFrontCamera
if(iN.isMirror){
flipH = !flipH
}
glFrameBuffer.setFlipH(flipH)
}
glFrameBuffer.setFlipV(iN.flipV)
glFrameBuffer.process(iN.textureId, iN.textureType)
out.index = cacheIndex
out.tag = iN.tag
textureIdQueue.offer(out)
if(loggable){
Log.d(TAG, "TextureIdQueue enqueue index=$cacheIndex, size=$size")
}
cacheIndex = (cacheIndex + 1) % cacheCount
size++
} else {
if(loggable){
Log.e(TAG, "TextureIdQueue is full!!")
}
}
return size
}
fun dequeue(remove: Boolean = true): TextureOut? {
val size = textureIdQueue.size
val poll = if(remove){
textureIdQueue.poll()
}else{
textureIdQueue.peek()
}
if(loggable){
Log.d(TAG, "TextureIdQueue dequeue index=${poll?.index}, size=$size")
}
return poll
}
fun reset() {
cacheIndex = 0
textureIdQueue.clear()
}
fun release() {
cacheIndex = 0
cacheTextureOuts.forEachIndexed { index, textureOut ->
if (textureOut != null) {
GLES20.glDeleteTextures(1, intArrayOf(textureOut.textureId), 0)
cacheTextureOuts[index] = null
}
}
textureIdQueue.clear()
glFrameBuffer.release()
}
data class TextureIn(
val textureId: Int,
val textureType: Int,
val width: Int,
val height: Int,
val rotation: Int,
val flipV: Boolean,
val isFrontCamera: Boolean,
val isMirror: Boolean,
val transform: FloatArray?,
val tag: Any? = null
)
data class TextureOut(
var index: Int = 0,
val textureId: Int,
val textureType: Int,
val width: Int,
val height: Int,
val isFrontCamera: Boolean,
var tag: Any? = null
)
}

View File

@ -0,0 +1,279 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity.utils.egl;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.Matrix;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Objects;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLContext;
import io.agora.beautyapi.faceunity.utils.LogUtils;
public class GLUtils {
private static final String TAG = "GLUtils";
public static final float[] IDENTITY_MATRIX = new float[16];
static {
Matrix.setIdentityM(IDENTITY_MATRIX, 0);
}
private GLUtils() {
}
public static Bitmap getTexture2DImage(int textureID, int width, int height) {
try {
int[] oldFboId = new int[1];
GLES20.glGetIntegerv(GLES20.GL_FRAMEBUFFER_BINDING, IntBuffer.wrap(oldFboId));
int[] framebuffers = new int[1];
GLES20.glGenFramebuffers(1, framebuffers, 0);
int framebufferId = framebuffers[0];
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebufferId);
int[] renderbuffers = new int[1];
GLES20.glGenRenderbuffers(1, renderbuffers, 0);
int renderId = renderbuffers[0];
GLES20.glBindRenderbuffer(GLES20.GL_RENDERBUFFER, renderId);
GLES20.glRenderbufferStorage(GLES20.GL_RENDERBUFFER, GLES20.GL_DEPTH_COMPONENT16, width, height);
GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, textureID, 0);
GLES20.glFramebufferRenderbuffer(GLES20.GL_FRAMEBUFFER, GLES20.GL_DEPTH_ATTACHMENT, GLES20.GL_RENDERBUFFER, renderId);
if (GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER) != GLES20.GL_FRAMEBUFFER_COMPLETE) {
LogUtils.e(TAG, "Framebuffer error");
}
ByteBuffer rgbaBuf = ByteBuffer.allocateDirect(width * height * 4);
rgbaBuf.position(0);
GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, rgbaBuf);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(rgbaBuf);
GLES20.glDeleteRenderbuffers(1, IntBuffer.wrap(framebuffers));
GLES20.glDeleteFramebuffers(1, IntBuffer.allocate(framebufferId));
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, oldFboId[0]);
return bitmap;
} catch (Exception e) {
LogUtils.e(TAG, e.toString());
}
return null;
}
public static Bitmap getTextureOESImage(int textureID, int width, int height) {
try {
int[] oldFboId = new int[1];
GLES20.glGetIntegerv(GLES20.GL_FRAMEBUFFER_BINDING, IntBuffer.wrap(oldFboId));
int[] framebuffers = new int[1];
GLES20.glGenFramebuffers(1, framebuffers, 0);
int framebufferId = framebuffers[0];
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, framebufferId);
int[] renderbuffers = new int[1];
GLES20.glGenRenderbuffers(1, renderbuffers, 0);
int renderId = renderbuffers[0];
GLES20.glBindRenderbuffer(GLES20.GL_RENDERBUFFER, renderId);
GLES20.glRenderbufferStorage(GLES20.GL_RENDERBUFFER, GLES20.GL_DEPTH_COMPONENT16, width, height);
GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureID, 0);
GLES20.glFramebufferRenderbuffer(GLES20.GL_FRAMEBUFFER, GLES20.GL_DEPTH_ATTACHMENT, GLES20.GL_RENDERBUFFER, renderId);
if (GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER) != GLES20.GL_FRAMEBUFFER_COMPLETE) {
LogUtils.e(TAG, "Framebuffer error");
}
ByteBuffer rgbaBuf = ByteBuffer.allocateDirect(width * height * 4);
rgbaBuf.position(0);
GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, rgbaBuf);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(rgbaBuf);
GLES20.glDeleteRenderbuffers(1, IntBuffer.wrap(framebuffers));
GLES20.glDeleteFramebuffers(1, IntBuffer.allocate(framebufferId));
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, oldFboId[0]);
return bitmap;
} catch (Exception e) {
LogUtils.e(TAG, e.toString());
}
return null;
}
public static Bitmap nv21ToBitmap(byte[] nv21, int width, int height) {
Bitmap bitmap = null;
try {
YuvImage image = new YuvImage(nv21, ImageFormat.NV21, width, height, null);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compressToJpeg(new Rect(0, 0, width, height), 80, stream);
bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
private static Bitmap readBitmap(int width, int height) {
ByteBuffer rgbaBuf = ByteBuffer.allocateDirect(width * height * 4);
rgbaBuf.position(0);
GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, rgbaBuf);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(rgbaBuf);
return bitmap;
}
public static float[] createTransformMatrix(int rotation, boolean flipH, boolean flipV) {
float[] renderMVPMatrix = new float[16];
float[] tmp = new float[16];
Matrix.setIdentityM(tmp, 0);
boolean _flipH = flipH;
boolean _flipV = flipV;
if (rotation % 180 != 0) {
_flipH = flipV;
_flipV = flipH;
}
if (_flipH) {
Matrix.rotateM(tmp, 0, tmp, 0, 180, 0, 1f, 0);
}
if (_flipV) {
Matrix.rotateM(tmp, 0, tmp, 0, 180, 1f, 0f, 0);
}
float _rotation = rotation;
if (_rotation != 0) {
if (_flipH != _flipV) {
_rotation *= -1;
}
Matrix.rotateM(tmp, 0, tmp, 0, _rotation, 0, 0, 1);
}
Matrix.setIdentityM(renderMVPMatrix, 0);
Matrix.multiplyMM(renderMVPMatrix, 0, tmp, 0, renderMVPMatrix, 0);
return renderMVPMatrix;
}
public static EGLContext getCurrGLContext() {
EGL10 egl = (EGL10) javax.microedition.khronos.egl.EGLContext.getEGL();
if (egl != null && !Objects.equals(egl.eglGetCurrentContext(), EGL10.EGL_NO_CONTEXT)) {
return egl.eglGetCurrentContext();
}
return null;
}
public static void checkGlError(String op) {
int error = GLES20.glGetError();
if (error != GLES20.GL_NO_ERROR) {
String msg = op + ": glError 0x" + Integer.toHexString(error);
LogUtils.e(TAG, msg);
throw new RuntimeException(msg);
}
}
public static int createProgram(String vertexSource, String fragmentSource) {
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0) {
return 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0) {
return 0;
}
int program = GLES20.glCreateProgram();
checkGlError("glCreateProgram");
if (program == 0) {
LogUtils.e(TAG, "Could not create program");
}
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
LogUtils.e(TAG, "Could not link program: ");
LogUtils.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
return program;
}
public static int loadShader(int shaderType, String source) {
int shader = GLES20.glCreateShader(shaderType);
checkGlError("glCreateShader type=" + shaderType);
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
int[] compiled = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
LogUtils.e(TAG, "Could not compile shader " + shaderType + ":");
LogUtils.e(TAG, " " + GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
return shader;
}
public static int createTexture(int textureTarget, Bitmap bitmap, int minFilter,
int magFilter, int wrapS, int wrapT) {
int[] textureHandle = new int[1];
GLES20.glGenTextures(1, textureHandle, 0);
checkGlError("glGenTextures");
GLES20.glBindTexture(textureTarget, textureHandle[0]);
checkGlError("glBindTexture " + textureHandle[0]);
GLES20.glTexParameterf(textureTarget, GLES20.GL_TEXTURE_MIN_FILTER, minFilter);
GLES20.glTexParameterf(textureTarget, GLES20.GL_TEXTURE_MAG_FILTER, magFilter); //线性插值
GLES20.glTexParameteri(textureTarget, GLES20.GL_TEXTURE_WRAP_S, wrapS);
GLES20.glTexParameteri(textureTarget, GLES20.GL_TEXTURE_WRAP_T, wrapT);
if (bitmap != null) {
android.opengl.GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
}
checkGlError("glTexParameter");
return textureHandle[0];
}
}

View File

@ -0,0 +1,214 @@
/*
* MIT License
*
* Copyright (c) 2023 Agora Community
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.agora.beautyapi.faceunity.utils.egl
import android.opengl.GLES20
import io.agora.beautyapi.faceunity.utils.LogUtils
import java.util.concurrent.Callable
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.Future
import javax.microedition.khronos.egl.EGLContext
class TextureProcessHelper(
private val cacheCount: Int = 2
) {
private val TAG = "TextureProcessHelper"
private val glTextureBufferQueueIn = GLTextureBufferQueue(cacheCount = cacheCount, loggable = true)
private val glTextureBufferQueueOut = GLTextureBufferQueue(cacheCount = cacheCount, loggable = false)
private val glFrameBuffer = GLFrameBuffer()
private val futureQueue = ConcurrentLinkedQueue<Future<Int>>()
private val workerThread = Executors.newSingleThreadExecutor()
private val eglContextHelper =
EGLContextHelper()
private var eglContextBase: EGLContext? = null
private var isReleased = false
private var filter: ((GLTextureBufferQueue.TextureOut) -> Int)? = null
private var isBegin = false
private var frameIndex = 0
fun setFilter(filter: (GLTextureBufferQueue.TextureOut) -> Int) {
this.filter = filter
}
fun process(
texId: Int, texType: Int,
width: Int, height: Int, rotation: Int,
transform: FloatArray,
isFrontCamera: Boolean,
isMirror: Boolean
): Int {
if (isReleased) {
return -1
}
val currGLContext = GLUtils.getCurrGLContext() ?: return -1
if (eglContextBase == null) {
eglContextBase = currGLContext
executeSync {
eglContextHelper.initEGL(eglContextBase)
eglContextHelper.eglMakeCurrent()
}
} else if (eglContextBase != currGLContext) {
eglContextBase = currGLContext
executeSync {
eglContextHelper.release()
eglContextHelper.initEGL(eglContextBase)
eglContextHelper.eglMakeCurrent()
}
}
glTextureBufferQueueIn.enqueue(
GLTextureBufferQueue.TextureIn(
texId,
texType,
width,
height,
rotation,
false,
isFrontCamera,
isMirror,
transform,
frameIndex
)
)
frameIndex ++
if (isReleased) {
return -1
}
futureQueue.offer(workerThread.submit(Callable {
if (isReleased) {
return@Callable -2
}
val frame = glTextureBufferQueueIn.dequeue(false) ?: return@Callable -2
val filterTexId = filter?.invoke(frame) ?: -1
if (filterTexId >= 0) {
glTextureBufferQueueOut.enqueue(
GLTextureBufferQueue.TextureIn(
filterTexId,
GLES20.GL_TEXTURE_2D,
frame.width,
frame.height,
0,
false,
false,
true,
null,
frame.tag
)
)
} else {
glTextureBufferQueueOut.enqueue(
GLTextureBufferQueue.TextureIn(
frame.textureId,
frame.textureType,
frame.width,
frame.height,
0,
false,
false,
true,
null,
frame.tag
)
)
}
glTextureBufferQueueIn.dequeue(true)
return@Callable 0
}))
var ret = 0
if (isBegin || futureQueue.size >= cacheCount) {
isBegin = true
try {
val get = futureQueue.poll()?.get() ?: -1
if (get == 0) {
val dequeue = glTextureBufferQueueOut.dequeue() ?: return -1
glFrameBuffer.setSize(dequeue.width, dequeue.height)
ret = glFrameBuffer.process(dequeue.textureId, dequeue.textureType)
}
}catch (e: Exception){
LogUtils.e(TAG, "process end with exception: $e")
}
}
return ret
}
fun reset(){
if(frameIndex == 0){
return
}
isBegin = false
frameIndex = 0
var future = futureQueue.poll()
while (future != null) {
future.cancel(true)
future = futureQueue.poll()
}
glTextureBufferQueueIn.reset()
// glFrameBuffer.release()
executeSync {
glTextureBufferQueueOut.reset()
}
}
fun size() = futureQueue.size
fun release() {
isReleased = true
filter = null
isBegin = false
frameIndex = 0
var future = futureQueue.poll()
while (future != null) {
future.cancel(true)
future = futureQueue.poll()
}
glTextureBufferQueueIn.release()
glFrameBuffer.release()
executeSync {
glTextureBufferQueueOut.release()
if (eglContextBase != null) {
eglContextHelper.release()
eglContextBase = null
}
}
workerThread.shutdown()
}
fun executeSync(run: () -> Unit) {
val latch = CountDownLatch(1)
workerThread.execute {
run.invoke()
latch.countDown()
}
latch.await()
}
}

View File

@ -1 +1 @@
apply plugin: 'com.android.library' apply plugin: 'img-optimizer' apply plugin: 'kotlin-android' android { namespace "com.yunbao.live" compileSdk rootProject.ext.android.compileSdkVersion aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false packagingOptions { pickFirst "lib/armeabi/libyuvutils.so" pickFirst "lib/arm64-v8a/libyuvutils.so" pickFirst "lib/armeabi-v7a/libyuvutils.so" pickFirst "lib/armeabi/libyuvtools.so" pickFirst "lib/arm64-v8a/libyuvtools.so" pickFirst "lib/armeabi-v7a/libyuvtools.so" exclude "lib/arm64-v8a/libmmcv_api_handgesture.so" exclude "lib/arm64-v8a/libmmcv_api_express.so" exclude "lib/arm64-v8a/libMediaEncoder.so" exclude "lib/arm64-v8a/libarcore_sdk_c.so" exclude "lib/arm64-v8a/libmediadecoder.so" exclude "lib/arm64-v8a/libMediaMuxer.so" exclude "lib/arm64-v8a/libarcore_sdk_jni.so" exclude "lib/arm64-v8a/libMediaUtils.so" exclude "lib/arm64-v8a/libcosmosffmpeg.so" } defaultConfig { minSdkVersion rootProject.ext.android.minSdkVersion targetSdkVersion rootProject.ext.android.targetSdkVersion versionCode rootProject.ext.android.versionCode versionName rootProject.ext.android.versionName manifestPlaceholders = rootProject.ext.manifestPlaceholders ndk { abiFilters "armeabi-v7a", "arm64-v8a" } javaCompileOptions { annotationProcessorOptions { arguments = [AROUTER_MODULE_NAME: project.getName()] } } } aaptOptions { cruncherEnabled = false useNewCruncher = false } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } kotlinOptions { allWarningsAsErrors = true } compileOptions { sourceCompatibility JavaVersion.VERSION_18 targetCompatibility JavaVersion.VERSION_18 } } repositories { flatDir { dirs 'libs', '../libs' } mavenCentral() } dependencies { implementation 'androidx.constraintlayout:constraintlayout:2.0.0' implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar']) implementation (name:'../libs/beautysdk-202202241203',ext:'aar') implementation (name:'../libs/svgaplayer-release-v1.2.1',ext:'aar') //socket.io implementation('io.socket:socket.io-client:1.0.0') { exclude group: 'org.json', module: 'json' } //common api project(path: ':common') api project(path:':FaceUnity')//新娱美颜 api project(':Share')//分享 annotationProcessor rootProject.ext.dependencies["arouter-compiler"] //工具 api rootProject.ext.dependencies["blank-utilcode"] implementation 'com.eightbitlab:blurview:1.6.6' implementation 'com.google.code.gson:gson:2.8.6' implementation "com.getkeepsafe.relinker:relinker:1.4.4" } apply plugin: 'com.android.library' apply plugin: 'img-optimizer' apply plugin: 'kotlin-android' android { namespace "com.yunbao.live" compileSdk rootProject.ext.android.compileSdkVersion aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false packagingOptions { pickFirst "lib/armeabi/libyuvutils.so" pickFirst "lib/arm64-v8a/libyuvutils.so" pickFirst "lib/armeabi-v7a/libyuvutils.so" pickFirst "lib/armeabi/libyuvtools.so" pickFirst "lib/arm64-v8a/libyuvtools.so" pickFirst "lib/armeabi-v7a/libyuvtools.so" exclude "lib/arm64-v8a/libmmcv_api_handgesture.so" exclude "lib/arm64-v8a/libmmcv_api_express.so" exclude "lib/arm64-v8a/libMediaEncoder.so" exclude "lib/arm64-v8a/libarcore_sdk_c.so" exclude "lib/arm64-v8a/libmediadecoder.so" exclude "lib/arm64-v8a/libMediaMuxer.so" exclude "lib/arm64-v8a/libarcore_sdk_jni.so" exclude "lib/arm64-v8a/libMediaUtils.so" exclude "lib/arm64-v8a/libcosmosffmpeg.so" } defaultConfig { minSdkVersion rootProject.ext.android.minSdkVersion targetSdkVersion rootProject.ext.android.targetSdkVersion versionCode rootProject.ext.android.versionCode versionName rootProject.ext.android.versionName manifestPlaceholders = rootProject.ext.manifestPlaceholders ndk { abiFilters "armeabi-v7a", "arm64-v8a","x86","x86_64" } javaCompileOptions { annotationProcessorOptions { arguments = [AROUTER_MODULE_NAME: project.getName()] } } } aaptOptions { cruncherEnabled = false useNewCruncher = false } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } kotlinOptions { allWarningsAsErrors = true } compileOptions { sourceCompatibility JavaVersion.VERSION_18 targetCompatibility JavaVersion.VERSION_18 } } repositories { flatDir { dirs 'libs', '../libs' } mavenCentral() } dependencies { implementation 'androidx.constraintlayout:constraintlayout:2.0.0' implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar']) implementation (name:'../libs/beautysdk-202202241203',ext:'aar') implementation (name:'../libs/svgaplayer-release-v1.2.1',ext:'aar') //socket.io implementation('io.socket:socket.io-client:1.0.0') { exclude group: 'org.json', module: 'json' } //common api project(path:':lib_faceunity')//新娱美颜 api project(':Share')//分享 annotationProcessor rootProject.ext.dependencies["arouter-compiler"] //工具 api rootProject.ext.dependencies["blank-utilcode"] implementation 'com.eightbitlab:blurview:1.6.6' implementation 'com.google.code.gson:gson:2.8.6' implementation "com.getkeepsafe.relinker:relinker:1.4.4" }

View File

@ -84,7 +84,10 @@
android:name=".activity.WebViewActivityMedal" android:name=".activity.WebViewActivityMedal"
android:screenOrientation="portrait" /> android:screenOrientation="portrait" />
<activity <activity
android:name=".activity.SudGameActivity" android:name=".activity.SudSwGameActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activity.SudRyGameActivity"
android:screenOrientation="portrait" /> android:screenOrientation="portrait" />
<activity <activity
android:name=".activity.MedalQuestionWebViewActivity" android:name=".activity.MedalQuestionWebViewActivity"
@ -96,10 +99,15 @@
<activity <activity
android:name=".activity.SystemMessageActivity" android:name=".activity.SystemMessageActivity"
android:screenOrientation="portrait" /> android:screenOrientation="portrait" />
<activity
android:name=".activity.LiveSwAnchorActivity"
android:screenOrientation="portrait" />
<activity <activity
android:name=".activity.LiveRyAnchorActivity" android:name=".activity.LiveRyAnchorActivity"
android:screenOrientation="portrait" /> android:screenOrientation="portrait" />
<uses-library <uses-library
android:name="org.apache.http.legacy" android:name="org.apache.http.legacy"
android:required="false" /> android:required="false" />

View File

@ -83,10 +83,13 @@ import com.yunbao.live.presenter.LiveLinkMicAnchorPresenter;
import com.yunbao.live.presenter.LiveLinkMicPkPresenter; import com.yunbao.live.presenter.LiveLinkMicPkPresenter;
import com.yunbao.live.presenter.LiveLinkMicPresenter; import com.yunbao.live.presenter.LiveLinkMicPresenter;
import com.yunbao.live.presenter.LiveRyLinkMicPkPresenter; import com.yunbao.live.presenter.LiveRyLinkMicPkPresenter;
import com.yunbao.live.presenter.LiveSwLinkMicPkPresenter;
import com.yunbao.live.socket.SocketClient; import com.yunbao.live.socket.SocketClient;
import com.yunbao.live.socket.SocketMessageListener; import com.yunbao.live.socket.SocketMessageListener;
import com.yunbao.live.socket.SocketRyChatUtil; import com.yunbao.live.socket.SocketRyChatUtil;
import com.yunbao.live.socket.SocketRyClient; import com.yunbao.live.socket.SocketRyClient;
import com.yunbao.live.socket.SocketSwChatUtil;
import com.yunbao.live.socket.SocketSwClient;
import com.yunbao.live.utils.LoadDian9TuUtil; import com.yunbao.live.utils.LoadDian9TuUtil;
import com.yunbao.live.views.AbsLiveViewHolder; import com.yunbao.live.views.AbsLiveViewHolder;
import com.yunbao.live.views.LiveAddImpressViewHolder; import com.yunbao.live.views.LiveAddImpressViewHolder;
@ -125,9 +128,13 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
protected LiveEndViewHolder mLiveEndViewHolder; protected LiveEndViewHolder mLiveEndViewHolder;
protected LiveLinkMicPresenter mLiveLinkMicPresenter;//观众与主播连麦逻辑 protected LiveLinkMicPresenter mLiveLinkMicPresenter;//观众与主播连麦逻辑
protected LiveLinkMicAnchorPresenter mLiveLinkMicAnchorPresenter;//主播与主播连麦逻辑 protected LiveLinkMicAnchorPresenter mLiveLinkMicAnchorPresenter;//主播与主播连麦逻辑
protected LiveLinkMicPkPresenter mLiveLinkMicPkPresenter;//主播与主播PK逻辑 protected LiveLinkMicPkPresenter mLiveLinkMicPkPresenter;//主播与主播PK逻辑 腾讯
public static LiveRyLinkMicPkPresenter mLiveRyLinkMicPkPresenter;//主播与主播PK逻辑 public static LiveRyLinkMicPkPresenter mLiveRyLinkMicPkPresenter;//主播与主播PK逻辑 融云
public static LiveSwLinkMicPkPresenter mLiveSwLinkMicPkPresenter;//主播与主播PK逻辑 声网
public SocketClient mSocketClient; public SocketClient mSocketClient;
public SocketSwClient mSocketSwClient;
public SocketRyClient mSocketRyClient; public SocketRyClient mSocketRyClient;
protected LiveBean mLiveBean; protected LiveBean mLiveBean;
@ -160,6 +167,8 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
protected List<LiveUserGiftBean> mAudienceList = new ArrayList<>(); protected List<LiveUserGiftBean> mAudienceList = new ArrayList<>();
protected LiveMicAnchorDialogFragment.OnMicListener micListener = null; protected LiveMicAnchorDialogFragment.OnMicListener micListener = null;
public static boolean isSw;
@Override @Override
protected void main() { protected void main() {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
@ -233,13 +242,22 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
// if (isRy == false) { // if (isRy == false) {
// SocketChatUtil.sendUpdateVotesMessage(mLiveUid, mLiveTypeVal, 1); // SocketChatUtil.sendUpdateVotesMessage(mLiveUid, mLiveTypeVal, 1);
// } else { // } else {
if(isSw){
SocketSwChatUtil.sendUpdateVotesMessage(mLiveUid, mLiveTypeVal, 1);
}else{
SocketRyChatUtil.sendUpdateVotesMessage(mLiveUid, mLiveTypeVal, 1); SocketRyChatUtil.sendUpdateVotesMessage(mLiveUid, mLiveTypeVal, 1);
}
// } // }
} }
// if (isRy == false) { // if (isRy == false) {
// SocketChatUtil.getFakeFans(mLiveUid); // SocketChatUtil.getFakeFans(mLiveUid);
// } else { // } else {
if(isSw){
SocketSwChatUtil.getFakeFans(mLiveUid);
}else{
SocketRyChatUtil.getFakeFans(mLiveUid); SocketRyChatUtil.getFakeFans(mLiveUid);
}
// } // }
} }
} }
@ -393,18 +411,29 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
if (mLiveRyLinkMicPkPresenter != null) { if (mLiveRyLinkMicPkPresenter != null) {
mLiveRyLinkMicPkPresenter.onPkProgressChanged(leftGift, rightGift, bean); mLiveRyLinkMicPkPresenter.onPkProgressChanged(leftGift, rightGift, bean);
} }
if (mLiveSwLinkMicPkPresenter != null) {
mLiveSwLinkMicPkPresenter.onPkProgressChanged(leftGift, rightGift, bean);
}
} }
@Override @Override
public void onEndPk(long leftUid, long rightUid, long left, long right, LivePKUserListBean bean) { public void onEndPk(long leftUid, long rightUid, long left, long right, LivePKUserListBean bean) {
if (mLiveRyLinkMicPkPresenter != null) { if (mLiveRyLinkMicPkPresenter != null) {
L.eSw("onEndPk 结束PK mLiveRyLinkMicPkPresenter");
if (mLiveUid.equals(leftUid + "")) { if (mLiveUid.equals(leftUid + "")) {
mLiveRyLinkMicPkPresenter.onPkProgressEnd(left, right, bean); mLiveRyLinkMicPkPresenter.onPkProgressEnd(left, right, bean);
} else { } else {
mLiveRyLinkMicPkPresenter.onPkProgressEnd(right, left, bean); mLiveRyLinkMicPkPresenter.onPkProgressEnd(right, left, bean);
} }
} }
if (mLiveSwLinkMicPkPresenter != null) {
L.eSw("onEndPk 结束PK mLiveSwLinkMicPkPresenter");
if (mLiveUid.equals(leftUid + "")) {
mLiveSwLinkMicPkPresenter.onPkProgressEnd(left, right, bean);
} else {
mLiveSwLinkMicPkPresenter.onPkProgressEnd(right, left, bean);
}
}
} }
/** /**
@ -557,6 +586,7 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
*/ */
@Override @Override
public void onAnchorAcceptLinkMic() { public void onAnchorAcceptLinkMic() {
L.eSw("onAnchorAcceptLinkMic(1)");
if (mLiveLinkMicPresenter != null) { if (mLiveLinkMicPresenter != null) {
mLiveLinkMicPresenter.onAnchorAcceptLinkMic(); mLiveLinkMicPresenter.onAnchorAcceptLinkMic();
} }
@ -668,6 +698,10 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
if (mLiveRyLinkMicPkPresenter != null) { if (mLiveRyLinkMicPkPresenter != null) {
mLiveRyLinkMicPkPresenter.onLinkMicPkClose(1); mLiveRyLinkMicPkPresenter.onLinkMicPkClose(1);
} }
if (mLiveSwLinkMicPkPresenter != null) {
mLiveSwLinkMicPkPresenter.onLinkMicPkClose(1);
}
// } // }
@ -718,7 +752,7 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
@Override @Override
public void onLinkMicPkApply(UserBean u, String stream, int forwhat) { public void onLinkMicPkApply(UserBean u, String stream, int forwhat) {
//主播直播间实现此逻辑 //主播直播间实现此逻辑
L.eSw("onLinkMicPkApply----------------------------------------------");
} }
/** /**
@ -727,7 +761,14 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
@Override @Override
public void onLinkMicPkStart(final String pkUid, final String pkhead, final String pkname, String isLadders) { public void onLinkMicPkStart(final String pkUid, final String pkhead, final String pkname, String isLadders) {
if (mContext instanceof LiveAudienceActivity) return; if (mContext instanceof LiveAudienceActivity) return;
Log.e("ry", "pkUid = " + pkUid + ", pkhead = " + pkhead + ", pkname = " + pkname + ", isLadders = " + isLadders); L.eSw("pkUid = " + pkUid + ", pkhead = " + pkhead + ", pkname = " + pkname + ", isLadders = " + isLadders);
if (isSw) {
if (mLiveSwLinkMicPkPresenter != null && mLiveRoomViewHolder != null) {
mLiveSwLinkMicPkPresenter.onLinkMicPkStart(pkUid, 1);
pr = new pkRunnable(pkUid, pkhead, pkname, isLadders);
mHandler.postDelayed(pr, 4000);//3秒后执行Runnable中的run方法
}
} else {
if (mLiveRyLinkMicPkPresenter != null && mLiveRoomViewHolder != null) { if (mLiveRyLinkMicPkPresenter != null && mLiveRoomViewHolder != null) {
mLiveRyLinkMicPkPresenter.onLinkMicPkStart(pkUid, 1); mLiveRyLinkMicPkPresenter.onLinkMicPkStart(pkUid, 1);
pr = new pkRunnable(pkUid, pkhead, pkname, isLadders); pr = new pkRunnable(pkUid, pkhead, pkname, isLadders);
@ -735,6 +776,7 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
} }
} }
}
public Handler mHandler = new Handler(); public Handler mHandler = new Handler();
public pkRunnable pr; public pkRunnable pr;
@ -773,6 +815,8 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
mLiveRyLinkMicPkPresenter.onLinkMicPkClose(i); mLiveRyLinkMicPkPresenter.onLinkMicPkClose(i);
} else if (mLiveLinkMicPkPresenter != null) { } else if (mLiveLinkMicPkPresenter != null) {
mLiveLinkMicPkPresenter.onLinkMicPkClose(i); mLiveLinkMicPkPresenter.onLinkMicPkClose(i);
} else if (mLiveSwLinkMicPkPresenter != null) {
mLiveSwLinkMicPkPresenter.onLinkMicPkClose(i);
} }
} }
@ -811,6 +855,9 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
} else if (mLiveLinkMicPkPresenter != null) { } else if (mLiveLinkMicPkPresenter != null) {
mLiveLinkMicPkPresenter.onLinkMicPkEnd(winUid); mLiveLinkMicPkPresenter.onLinkMicPkEnd(winUid);
mLiveRoomViewHolder.setDelOtherInfo(); mLiveRoomViewHolder.setDelOtherInfo();
} else if (mLiveSwLinkMicPkPresenter != null) {
mLiveSwLinkMicPkPresenter.onLinkMicPkEnd(winUid);
mLiveRoomViewHolder.setDelOtherInfo();
} }
} }
@ -967,7 +1014,11 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
onCoinChanged(coin); onCoinChanged(coin);
} }
String[] data = new String[]{obj.getString("barragetoken")}; String[] data = new String[]{obj.getString("barragetoken")};
if(isSw){
SocketSwChatUtil.sendDanmuMessage(mLiveUid, contents, obj.getIntValue("level_fans"));
}else{
SocketRyChatUtil.sendDanmuMessage(mLiveUid, contents, obj.getIntValue("level_fans")); SocketRyChatUtil.sendDanmuMessage(mLiveUid, contents, obj.getIntValue("level_fans"));
}
} else if (code == 1001) { } else if (code == 1001) {
DialogUitl.showSimpleDialog(mContext, msg, new DialogUitl.SimpleCallback2() { DialogUitl.showSimpleDialog(mContext, msg, new DialogUitl.SimpleCallback2() {
@Override @Override
@ -1001,16 +1052,45 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
} }
} }
int guardType = mLiveGuardInfo != null ? mLiveGuardInfo.getMyGuardType() : Constants.GUARD_TYPE_NONE; int guardType = mLiveGuardInfo != null ? mLiveGuardInfo.getMyGuardType() : Constants.GUARD_TYPE_NONE;
if(isSw){
SocketSwChatUtil.sendChatMessage(mLiveUid, content, IMLoginManager.get(mContext).getUserInfo().anchorUserType(), mSocketUserType, guardType, atUserID, atUserName);
}else{
SocketRyChatUtil.sendChatMessage(mLiveUid, content, IMLoginManager.get(mContext).getUserInfo().anchorUserType(), mSocketUserType, guardType, atUserID, atUserName); SocketRyChatUtil.sendChatMessage(mLiveUid, content, IMLoginManager.get(mContext).getUserInfo().anchorUserType(), mSocketUserType, guardType, atUserID, atUserName);
}
}
/**
* 系统 消息 融云
*/
public static void sendSystemMessageSw(String content) {
if(isSw){
SocketSwChatUtil.sendSystemMessage(mLiveUid, content);
}else{
SocketRyChatUtil.sendSystemMessage(mLiveUid, content);
}
}
/**
* 系统 消息 声网
*/
public static void sendSystemMessageRy(String content) {
if(isSw){
SocketSwChatUtil.sendSystemMessage(mLiveUid, content);
}else{
SocketRyChatUtil.sendSystemMessage(mLiveUid, content);
}
} }
/** /**
* 系统 消息 * 系统 消息
*/ */
public static void sendSystemMessage(String content) { public void sendSystemMessage(String content) {
if(isSw){
SocketSwChatUtil.sendSystemMessage(mLiveUid, content);
}else{
SocketRyChatUtil.sendSystemMessage(mLiveUid, content); SocketRyChatUtil.sendSystemMessage(mLiveUid, content);
} }
}
/** /**
@ -1018,7 +1098,11 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
*/ */
public void sendGiftMessage(LiveGiftBean giftBean, String giftToken, String ancherName, String by) { public void sendGiftMessage(LiveGiftBean giftBean, String giftToken, String ancherName, String by) {
int guardType = mLiveGuardInfo != null ? mLiveGuardInfo.getMyGuardType() : Constants.GUARD_TYPE_NONE; int guardType = mLiveGuardInfo != null ? mLiveGuardInfo.getMyGuardType() : Constants.GUARD_TYPE_NONE;
if(isSw){
SocketSwChatUtil.sendGiftMessage(giftBean.getType(), giftToken, mLiveUid, ancherName, guardType, by);
}else{
SocketRyChatUtil.sendGiftMessage(giftBean.getType(), giftToken, mLiveUid, ancherName, guardType, by); SocketRyChatUtil.sendGiftMessage(giftBean.getType(), giftToken, mLiveUid, ancherName, guardType, by);
}
} }
@ -1026,65 +1110,104 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
* 主播或管理员踢人 * 主播或管理员踢人
*/ */
public void kickUser(String toUid, String toName) { public void kickUser(String toUid, String toName) {
if(isSw){
SocketSwChatUtil.sendKickMessage(mLiveUid, toUid, toName);
}else{
SocketRyChatUtil.sendKickMessage(mLiveUid, toUid, toName); SocketRyChatUtil.sendKickMessage(mLiveUid, toUid, toName);
} }
}
/** /**
* 禁言 * 禁言
*/ */
public void setShutUp(String toUid, String toName, int type) { public void setShutUp(String toUid, String toName, int type) {
if(isSw){
SocketSwChatUtil.sendShutUpMessage(mLiveUid, toUid, toName, type);
}else{
SocketRyChatUtil.sendShutUpMessage(mLiveUid, toUid, toName, type); SocketRyChatUtil.sendShutUpMessage(mLiveUid, toUid, toName, type);
} }
}
/** /**
* 期限禁言 * 期限禁言
*/ */
public void setShutUp(String toUid, String toName, int type, int time) { public void setShutUp(String toUid, String toName, int type, int time) {
if(isSw){
SocketSwChatUtil.sendShutUpMessage(mLiveUid, toUid, toName, type, time);
}else{
SocketRyChatUtil.sendShutUpMessage(mLiveUid, toUid, toName, type, time); SocketRyChatUtil.sendShutUpMessage(mLiveUid, toUid, toName, type, time);
} }
}
/** /**
* 设置或取消管理员消息 * 设置或取消管理员消息
*/ */
public void sendSetAdminMessage(int action, String toUid, String toName) { public void sendSetAdminMessage(int action, String toUid, String toName) {
if(isSw){
SocketSwChatUtil.sendSetAdminMessage(mLiveUid, action, toUid, toName);
}else{
SocketRyChatUtil.sendSetAdminMessage(mLiveUid, action, toUid, toName); SocketRyChatUtil.sendSetAdminMessage(mLiveUid, action, toUid, toName);
} }
}
/** /**
* 超管关闭直播间 * 超管关闭直播间
*/ */
public void superCloseRoom() { public void superCloseRoom() {
if(isSw){
SocketSwChatUtil.superCloseRoom(mLiveUid);
}else{
SocketRyChatUtil.superCloseRoom(mLiveUid); SocketRyChatUtil.superCloseRoom(mLiveUid);
} }
}
/** /**
* 更新主播映票数 * 更新主播映票数
*/ */
public void sendUpdateVotesMessage(int deltaVal) { public void sendUpdateVotesMessage(int deltaVal) {
if(isSw){
SocketSwChatUtil.sendUpdateVotesMessage(mLiveUid, deltaVal);
}else{
SocketRyChatUtil.sendUpdateVotesMessage(mLiveUid, deltaVal); SocketRyChatUtil.sendUpdateVotesMessage(mLiveUid, deltaVal);
} }
}
/** /**
* 发送购买守护成功消息 * 发送购买守护成功消息
*/ */
public void sendBuyGuardMessage(String votes, int guardNum, int guardType) { public void sendBuyGuardMessage(String votes, int guardNum, int guardType) {
if(isSw){
SocketSwChatUtil.sendBuyGuardMessage(mLiveUid, votes, guardNum, guardType);
}else{
SocketRyChatUtil.sendBuyGuardMessage(mLiveUid, votes, guardNum, guardType); SocketRyChatUtil.sendBuyGuardMessage(mLiveUid, votes, guardNum, guardType);
} }
}
public void sendBuyGuardMessage2(String votes, int guardNum, int guardType, String ancherName, String liveId) { public void sendBuyGuardMessage2(String votes, int guardNum, int guardType, String ancherName, String liveId) {
if (guardType != 1) { if (guardType != 1) {
if(isSw){
SocketSwChatUtil.sendBuyGuardMessage2(mLiveUid, votes, guardNum, guardType, ancherName, liveId);
}else{
SocketRyChatUtil.sendBuyGuardMessage2(mLiveUid, votes, guardNum, guardType, ancherName, liveId); SocketRyChatUtil.sendBuyGuardMessage2(mLiveUid, votes, guardNum, guardType, ancherName, liveId);
} }
} }
}
/** /**
* 发送发红包成功消息 * 发送发红包成功消息
*/ */
public void sendRedPackMessage() { public void sendRedPackMessage() {
if(isSw){
SocketSwChatUtil.sendRedPackMessage(mLiveUid);
}else{
SocketRyChatUtil.sendRedPackMessage(mLiveUid); SocketRyChatUtil.sendRedPackMessage(mLiveUid);
} }
}
/** /**
@ -1335,8 +1458,7 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
if (outRankHideFirst) { if (outRankHideFirst) {
//获取隐身的用户的ID //获取隐身的用户的ID
LiveNetManager.get(mContext) LiveNetManager.get(mContext).getNobleRankHideUserList(new com.yunbao.common.http.base.HttpCallback<NobleRankHideUserListModel>() {
.getNobleRankHideUserList(new com.yunbao.common.http.base.HttpCallback<NobleRankHideUserListModel>() {
@Override @Override
public void onSuccess(NobleRankHideUserListModel data) { public void onSuccess(NobleRankHideUserListModel data) {
outRankHide = data.getInRankHide(); outRankHide = data.getInRankHide();
@ -1527,6 +1649,13 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
} }
} }
@Override
public void onLinkDRMicPkQuit(String uid) {
if(mLiveSwLinkMicPkPresenter!=null){
mLiveSwLinkMicPkPresenter.onLinkDRMicPkQuit(uid);
}
}
@Override @Override
public boolean isSoftInputShowed() { public boolean isSoftInputShowed() {
if (mKeyBoardHeightUtil != null) { if (mKeyBoardHeightUtil != null) {
@ -1671,15 +1800,18 @@ public abstract class LiveActivity extends AbsActivity implements SocketMessageL
micListener = fragment.getMicListener(); micListener = fragment.getMicListener();
fragment.setMicQueueList(mMicQueueList); fragment.setMicQueueList(mMicQueueList);
fragment.setAudienceList(mAudienceList); fragment.setAudienceList(mAudienceList);
if(isSw){
fragment.show(((LiveSwAnchorActivity) mContext).getSupportFragmentManager(), "LiveMicAnchorDialogFragment");
}else{
fragment.show(((LiveRyAnchorActivity) mContext).getSupportFragmentManager(), "LiveMicAnchorDialogFragment"); fragment.show(((LiveRyAnchorActivity) mContext).getSupportFragmentManager(), "LiveMicAnchorDialogFragment");
} }
}
/** /**
* 获取连麦列表 * 获取连麦列表
*/ */
public void showMicList(String uid, LiveRoomViewHolder mLiveRoomViewHolder) { public void showMicList(String uid, LiveRoomViewHolder mLiveRoomViewHolder) {
LiveNetManager.get(mContext) LiveNetManager.get(mContext).getDRMicUserList(uid, new com.yunbao.common.http.base.HttpCallback<List<LinkMicUserBean>>() {
.getDRMicUserList(uid, new com.yunbao.common.http.base.HttpCallback<List<LinkMicUserBean>>() {
@Override @Override
public void onSuccess(List<LinkMicUserBean> data) { public void onSuccess(List<LinkMicUserBean> data) {
if (mLiveRoomViewHolder != null) { if (mLiveRoomViewHolder != null) {

View File

@ -282,7 +282,7 @@ public class LiveAnchorActivity extends LiveActivity implements LiveFunctionClic
+ CommonAppConfig.getInstance().getUid() + "&token=" + CommonAppConfig.getInstance().getUid() + "&token="
+ CommonAppConfig.getInstance().getToken() + "&anchorUid=" + mLiveUid + CommonAppConfig.getInstance().getToken() + "&anchorUid=" + mLiveUid
+ "&isZh=" + ((IMLoginManager.get(mContext).getLocaleLanguage() == Locale.SIMPLIFIED_CHINESE) ? "1" : "0"); + "&isZh=" + ((IMLoginManager.get(mContext).getLocaleLanguage() == Locale.SIMPLIFIED_CHINESE) ? "1" : "0");
ZhuangBanActivity.forward(mContext, url, false,0); ZhuangBanActivity.forward(mContext, url, false, 0);
break; break;
case Constants.LIVE_FUNC_LINK_MIC://连麦 case Constants.LIVE_FUNC_LINK_MIC://连麦
openLinkMicAnchorWindow(); openLinkMicAnchorWindow();
@ -471,7 +471,7 @@ public class LiveAnchorActivity extends LiveActivity implements LiveFunctionClic
} }
mLiveReadyViewHolder = null; mLiveReadyViewHolder = null;
if (mLiveRoomViewHolder == null) { if (mLiveRoomViewHolder == null) {
mLiveRoomViewHolder = new LiveRoomViewHolder(false, 2, mContext, mContainer, (GifImageView) findViewById(R.id.gift_gif), (SVGAImageView) findViewById(R.id.gift_svga), mContainerWrap, getWindowManager()); mLiveRoomViewHolder = new LiveRoomViewHolder(false, 2, mContext, mContainer, (GifImageView) findViewById(R.id.gift_gif), (SVGAImageView) findViewById(R.id.gift_svga), mContainerWrap, getWindowManager(),false);
mLiveRoomViewHolder.addToParent(); mLiveRoomViewHolder.addToParent();
mLiveRoomViewHolder.subscribeActivityLifeCycle(); mLiveRoomViewHolder.subscribeActivityLifeCycle();
mLiveRoomViewHolder.setLiveInfo(mLiveUid, mStream, obj.getIntValue("userlist_time") * 1000); mLiveRoomViewHolder.setLiveInfo(mLiveUid, mStream, obj.getIntValue("userlist_time") * 1000);
@ -632,6 +632,9 @@ public class LiveAnchorActivity extends LiveActivity implements LiveFunctionClic
// } else { // } else {
// SocketRyChatUtil.closeLive(mLiveUid, mSocketRyClient); // SocketRyChatUtil.closeLive(mLiveUid, mSocketRyClient);
//断开socket //断开socket
if (mSocketSwClient != null) {
mSocketSwClient.disConnect();
}
if (mSocketRyClient != null) { if (mSocketRyClient != null) {
mSocketRyClient.disConnect(); mSocketRyClient.disConnect();
} }
@ -885,7 +888,7 @@ public class LiveAnchorActivity extends LiveActivity implements LiveFunctionClic
} }
}); });
} else { } else {
ToastUtil.show("主播正在PK稍後再試"); ToastUtil.show(getString(R.string.pking_over));
} }
} }
} }
@ -938,7 +941,7 @@ public class LiveAnchorActivity extends LiveActivity implements LiveFunctionClic
} }
}); });
} else { } else {
ToastUtil.show("主播正在PK稍後再試"); ToastUtil.show(mContext.getString(R.string.pking_over));
} }
} }
} }
@ -997,9 +1000,15 @@ public class LiveAnchorActivity extends LiveActivity implements LiveFunctionClic
} }
} }
@Override
public void onLinkDRMicPKToUser(UserBean u) {
}
//多人PK接受 //多人PK接受
@Override @Override
public void onLinkDRMicPkApplyOk(UserBean u) { public void onLinkDRMicPkApplyOk(UserBean u) {
L.eSw("onLinkDRMicPkApplyOk(UserBean u)");
if (mLiveLinkMicPkPresenter != null) { if (mLiveLinkMicPkPresenter != null) {
mLiveLinkMicPkPresenter.onLinkDRMicPkApplyOk(u); mLiveLinkMicPkPresenter.onLinkDRMicPkApplyOk(u);
} }

View File

@ -15,6 +15,7 @@ import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView; import android.widget.ImageView;
import androidx.annotation.IdRes; import androidx.annotation.IdRes;
@ -36,6 +37,9 @@ import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition; import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.XPopupCallback; import com.lxj.xpopup.interfaces.XPopupCallback;
import com.lzf.easyfloat.EasyFloat; import com.lzf.easyfloat.EasyFloat;
import com.lzf.easyfloat.enums.ShowPattern;
import com.yunbao.common.dialog.DebugDialog;
import com.yunbao.common.interfaces.OnItemClickListener;
import com.yunbao.common.utils.MobclickAgent; import com.yunbao.common.utils.MobclickAgent;
import com.yunbao.common.CommonAppConfig; import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.Constants; import com.yunbao.common.Constants;
@ -125,7 +129,9 @@ import com.yunbao.live.dialog.LiveWishListDialogFragment4Audience;
import com.yunbao.live.dialog.SignDialogFragment; import com.yunbao.live.dialog.SignDialogFragment;
import com.yunbao.live.event.LinkMicTxAccEvent; import com.yunbao.live.event.LinkMicTxAccEvent;
import com.yunbao.live.event.LiveAudienceEvent; import com.yunbao.live.event.LiveAudienceEvent;
import com.yunbao.live.event.LiveOpenSuccessEvent;
import com.yunbao.live.http.ImHttpUtil; import com.yunbao.live.http.ImHttpUtil;
import com.yunbao.live.utils.LiveTextRender;
import com.yunbao.live.views.LiveRoomPlayViewHolder; import com.yunbao.live.views.LiveRoomPlayViewHolder;
import com.yunbao.live.views.LiveRoomViewHolder; import com.yunbao.live.views.LiveRoomViewHolder;
import com.yunbao.live.views.PortraitLiveManager; import com.yunbao.live.views.PortraitLiveManager;
@ -208,6 +214,7 @@ public class LiveAudienceActivity extends LiveActivity {
mProcessResultUtil = new ProcessResultUtil(this); mProcessResultUtil = new ProcessResultUtil(this);
Intent intent = getIntent(); Intent intent = getIntent();
mLiveSDK = intent.getIntExtra(Constants.LIVE_SDK, Constants.LIVE_SDK_KSY); mLiveSDK = intent.getIntExtra(Constants.LIVE_SDK, Constants.LIVE_SDK_KSY);
isSw = intent.getBooleanExtra(Constants.LIVE_SDK_IS_SW, false);
L.e(TAG, "直播sdk----->" + (mLiveSDK == Constants.LIVE_SDK_KSY ? "金山云" : "腾讯云")); L.e(TAG, "直播sdk----->" + (mLiveSDK == Constants.LIVE_SDK_KSY ? "金山云" : "腾讯云"));
mLiveType = intent.getIntExtra(Constants.LIVE_TYPE, Constants.LIVE_TYPE_NORMAL); mLiveType = intent.getIntExtra(Constants.LIVE_TYPE, Constants.LIVE_TYPE_NORMAL);
mLiveTypeVal = intent.getIntExtra(Constants.LIVE_TYPE_VAL, 0); mLiveTypeVal = intent.getIntExtra(Constants.LIVE_TYPE_VAL, 0);
@ -226,6 +233,43 @@ public class LiveAudienceActivity extends LiveActivity {
fragment.show(((FragmentActivity) mContext).getSupportFragmentManager(), "YoursystemisolderDialog"); fragment.show(((FragmentActivity) mContext).getSupportFragmentManager(), "YoursystemisolderDialog");
IMLoginManager.get(mContext).setXiaJBG(true); IMLoginManager.get(mContext).setXiaJBG(true);
} }
/* new Handler(Looper.getMainLooper())
.postDelayed(new Runnable() {
@Override
public void run() {
DebugDialog.getInstance(new DebugDialog.DebugDialogRunnable() {
@Override
public void run(DebugDialog dialog) {
dialog.setShowPattern(ShowPattern.ALL_TIME);
dialog.show();
dialog.setView("+",new Button(mContext),view -> LiveTextRender.textTemp++);
dialog.setView("-",new Button(mContext),view -> LiveTextRender.textTemp--);
dialog.setView("+",new Button(mContext),view -> LiveTextRender.textTemp++);
dialog.setView("中/英",new Button(mContext),view ->{
if(LiveTextRender.userName.startsWith("")){
LiveTextRender.userName="英文34567890";
}else{
LiveTextRender.userName="中文测试中文测试中文";
}
});
dialog.setView("长/短",new Button(mContext),view ->{
if(LiveTextRender.userName.length()>5){
LiveTextRender.userName="abcdefg";
}else{
LiveTextRender.userName="中文中文";
}
});
LiveTextRender.onItemClickListener = new OnItemClickListener<String>() {
@Override
public void onItemClick(String bean, int position) {
dialog.setParams(bean.split("\\|")[0], bean.split("\\|")[1]+"|"+position);
}
};
}
});
}
},1000);*/
} }
private final MicStatusManager.OnMicStatusListener onMicStatusListener = new MicStatusManager.OnMicStatusListener() { private final MicStatusManager.OnMicStatusListener onMicStatusListener = new MicStatusManager.OnMicStatusListener() {
@ -299,8 +343,7 @@ public class LiveAudienceActivity extends LiveActivity {
Log.e(TAG, "mCurrentItem:" + mCurrentItem); Log.e(TAG, "mCurrentItem:" + mCurrentItem);
if (mCurrentItem == itemModelList.size() - 1) { if (mCurrentItem == itemModelList.size() - 1) {
if (isRadPacetModle) {//从红包专区进去的走红包专区列表 if (isRadPacetModle) {//从红包专区进去的走红包专区列表
MainNetManager.get(mContext) MainNetManager.get(mContext).getRedPacket(new com.yunbao.common.http.base.HttpCallback<List<AnchorRecommendItemModel>>() {
.getRedPacket(new com.yunbao.common.http.base.HttpCallback<List<AnchorRecommendItemModel>>() {
@Override @Override
public void onSuccess(List<AnchorRecommendItemModel> data) { public void onSuccess(List<AnchorRecommendItemModel> data) {
if (TextUtils.equals(data.get(0).getUid(), mLiveBean.getUid())) { if (TextUtils.equals(data.get(0).getUid(), mLiveBean.getUid())) {
@ -316,8 +359,7 @@ public class LiveAudienceActivity extends LiveActivity {
} }
}); });
} else { } else {
MainNetManager.get(mContext) MainNetManager.get(mContext).anchorRecommendType("30", isSw ? "1" : "0", new com.yunbao.common.http.base.HttpCallback<AnchorRecommendModel>() {
.anchorRecommendType("30", new com.yunbao.common.http.base.HttpCallback<AnchorRecommendModel>() {
@Override @Override
public void onSuccess(AnchorRecommendModel data) { public void onSuccess(AnchorRecommendModel data) {
if (TextUtils.equals(data.getList().get(0).getUid(), mLiveBean.getUid())) { if (TextUtils.equals(data.getList().get(0).getUid(), mLiveBean.getUid())) {
@ -351,13 +393,16 @@ public class LiveAudienceActivity extends LiveActivity {
if (itemModelList.size() == 0) { if (itemModelList.size() == 0) {
return; return;
} }
Log.e("直播间接口调用排查", "transformPage 11");
ViewGroup viewGroup = (ViewGroup) page; ViewGroup viewGroup = (ViewGroup) page;
Log.e(TAG, "position:" + mCurrentItem); Log.e(TAG, "position:" + mCurrentItem);
if ((position < 0 && viewGroup.getId() != mCurrentItem)) { if ((position < 0 && viewGroup.getId() != mCurrentItem)) {
Log.e("直播间接口调用排查", "transformPage 22");
// room_container 为视频播放的根布局 id // room_container 为视频播放的根布局 id
View rootView = viewGroup.findViewById(R.id.drawer_layout); View rootView = viewGroup.findViewById(R.id.drawer_layout);
if (rootView != null && rootView.getParent() != null && rootView.getParent() instanceof ViewGroup) { if (rootView != null && rootView.getParent() != null && rootView.getParent() instanceof ViewGroup) {
((ViewGroup) (rootView.getParent())).removeView(rootView); ((ViewGroup) (rootView.getParent())).removeView(rootView);
Log.e("直播间接口调用排查", "transformPage 33");
manager.onRemove(false); manager.onRemove(false);
} }
} }
@ -366,8 +411,6 @@ public class LiveAudienceActivity extends LiveActivity {
loadData(viewGroup, mCurrentItem); loadData(viewGroup, mCurrentItem);
} }
} }
}); });
getDrawer(); getDrawer();
@ -403,7 +446,7 @@ public class LiveAudienceActivity extends LiveActivity {
mHandler.removeCallbacks(pr); mHandler.removeCallbacks(pr);
pr = null; pr = null;
} }
manager.onAdd(mLiveBean, mLiveType, mLiveTypeVal, mLiveSDK); manager.onAdd(mLiveBean, mLiveType, mLiveTypeVal, mLiveSDK, isSw);
//加载完页面后再后台静默下载礼物svga //加载完页面后再后台静默下载礼物svga
downloadAllGift(); downloadAllGift();
@ -412,7 +455,9 @@ public class LiveAudienceActivity extends LiveActivity {
} else { } else {
new LiveRoomCheckLivePresenter(mContext, data.getUid(), data.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() { new LiveRoomCheckLivePresenter(mContext, data.getUid(), data.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() {
@Override @Override
public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk) { public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk, boolean isSw1) {
L.eSw("onLiveRoomChanged:" + isSw1);
isSw = isSw1;
liveIndex = false; liveIndex = false;
try { try {
mLiveSDK = Integer.parseInt(liveSdk); mLiveSDK = Integer.parseInt(liveSdk);
@ -440,7 +485,7 @@ public class LiveAudienceActivity extends LiveActivity {
} }
mViewGroup.addView(manager.getRootView()); mViewGroup.addView(manager.getRootView());
manager.onAdd(mLiveBean, liveType, mLiveTypeVal, mLiveSDK); manager.onAdd(mLiveBean, liveType, mLiveTypeVal, mLiveSDK, isSw);
//加载完页面后再后台静默下载礼物svga //加载完页面后再后台静默下载礼物svga
downloadAllGift(); downloadAllGift();
over(); over();
@ -482,12 +527,7 @@ public class LiveAudienceActivity extends LiveActivity {
if (TextUtils.isEmpty(mLiveUid) || TextUtils.isEmpty(mStream)) { if (TextUtils.isEmpty(mLiveUid) || TextUtils.isEmpty(mStream)) {
return; return;
} }
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.GIFT_POPUP).setmLiveUid(mLiveUid).setmStream(mStream).setPk(isPk).setLiveGuardInfo(mLiveGuardInfo));
.setType(LiveAudienceEvent.LiveAudienceType.GIFT_POPUP)
.setmLiveUid(mLiveUid)
.setmStream(mStream)
.setPk(isPk)
.setLiveGuardInfo(mLiveGuardInfo));
}); });
} }
@ -495,13 +535,7 @@ public class LiveAudienceActivity extends LiveActivity {
if (TextUtils.isEmpty(mLiveUid) || TextUtils.isEmpty(mStream)) { if (TextUtils.isEmpty(mLiveUid) || TextUtils.isEmpty(mStream)) {
return; return;
} }
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.GIFT_POPUP).setmLiveUid(mLiveUid).setmStream(mStream).setPk(isPk).setLiveGuardInfo(mLiveGuardInfo).setmWishGiftId(giftId));
.setType(LiveAudienceEvent.LiveAudienceType.GIFT_POPUP)
.setmLiveUid(mLiveUid)
.setmStream(mStream)
.setPk(isPk)
.setLiveGuardInfo(mLiveGuardInfo)
.setmWishGiftId(giftId));
} }
public void openGiftWindow(String giftId, String for_by) { public void openGiftWindow(String giftId, String for_by) {
@ -510,14 +544,7 @@ public class LiveAudienceActivity extends LiveActivity {
} }
new Handler(Looper.getMainLooper()).post(() -> { new Handler(Looper.getMainLooper()).post(() -> {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.GIFT_POPUP).setmLiveUid(mLiveUid).setmStream(mStream).setPk(isPk).setLiveGuardInfo(mLiveGuardInfo).setmWishGiftId(giftId).setUname("1"));//setUname==by
.setType(LiveAudienceEvent.LiveAudienceType.GIFT_POPUP)
.setmLiveUid(mLiveUid)
.setmStream(mStream)
.setPk(isPk)
.setLiveGuardInfo(mLiveGuardInfo)
.setmWishGiftId(giftId)
.setUname("1"));//setUname==by
}); });
} }
@ -566,8 +593,20 @@ public class LiveAudienceActivity extends LiveActivity {
} }
@Override @Override
public void onLinkDRMicPkApplyOk(UserBean u) { public void onLinkDRMicPKToUser(UserBean u) {
//manager.getmLivePlayViewHolder().setDrMicInfo(u);
}
@Override
public void onLinkDRMicPkQuit(String uid) {
}
@Override
public void onLinkDRMicPkApplyOk(UserBean u) {
L.eSw("onLinkDRMicPkApplyOk:" + u.getId());
//多人PK 连麦
//manager.getmLivePlayViewHolder().setDrMicInfo(u);
} }
@Override @Override
@ -583,13 +622,7 @@ public class LiveAudienceActivity extends LiveActivity {
@Override @Override
public void onBackPressed() { public void onBackPressed() {
if (manager != null && manager.getsudGameMin()) { if (manager != null && manager.getsudGameMin()) {
new XPopup.Builder(mContext) new XPopup.Builder(mContext).asCustom(new HintCustomPopup(mContext, mContext.getString(com.yunbao.common.R.string.dialog_tip), mContext.getString(com.yunbao.common.R.string.the_live_room)).setLiveOpenOk(mContext.getString(com.yunbao.common.R.string.confirm)).setLiveOpenCancel(mContext.getString(com.yunbao.common.R.string.cancel)).setCallBack(new HintCustomPopup.HintCustomCallBack() {
.asCustom(new HintCustomPopup(mContext,
mContext.getString(com.yunbao.common.R.string.dialog_tip),
mContext.getString(com.yunbao.common.R.string.the_live_room))
.setLiveOpenOk(mContext.getString(com.yunbao.common.R.string.confirm))
.setLiveOpenCancel(mContext.getString(com.yunbao.common.R.string.cancel))
.setCallBack(new HintCustomPopup.HintCustomCallBack() {
@Override @Override
public void onSure() { public void onSure() {
MobclickAgent.onEvent(mContext, "live_room_close", "退出直播间"); MobclickAgent.onEvent(mContext, "live_room_close", "退出直播间");
@ -638,8 +671,7 @@ public class LiveAudienceActivity extends LiveActivity {
} }
public void end() { public void end() {
if (manager != null) if (manager != null) manager.end();
manager.end();
} }
/** /**
@ -694,24 +726,21 @@ public class LiveAudienceActivity extends LiveActivity {
* 计时收费更新主播映票数 * 计时收费更新主播映票数
*/ */
public void roomChargeUpdateVotes() { public void roomChargeUpdateVotes() {
if (manager != null) if (manager != null) manager.sendUpdateVotesMessage();
manager.sendUpdateVotesMessage();
} }
/** /**
* 暂停播放 * 暂停播放
*/ */
public void pausePlay() { public void pausePlay() {
if (manager != null) if (manager != null) manager.pausePlay();
manager.pausePlay();
} }
/** /**
* 恢复播放 * 恢复播放
*/ */
public void resumePlay() { public void resumePlay() {
if (manager != null) if (manager != null) manager.resumePlay();
manager.resumePlay();
} }
public CountDownTimer getCountDownTimer() { public CountDownTimer getCountDownTimer() {
@ -722,8 +751,7 @@ public class LiveAudienceActivity extends LiveActivity {
* 充值成功 * 充值成功
*/ */
public void onChargeSuccess() { public void onChargeSuccess() {
if (manager != null) if (manager != null) manager.onChargeSuccess();
manager.onChargeSuccess();
} }
public void setCoinNotEnough(boolean coinNotEnough) { public void setCoinNotEnough(boolean coinNotEnough) {
@ -739,6 +767,14 @@ public class LiveAudienceActivity extends LiveActivity {
manager.onLinkMicTxAccEvent(e); manager.onLinkMicTxAccEvent(e);
} }
/**
* 腾讯sdk连麦时候切换低延时流
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void onLinkMicTxAccEvent(LiveOpenSuccessEvent e) {
manager.loadTimeoutRunnableGone();
}
/** /**
* 腾讯sdk时候主播连麦回调 * 腾讯sdk时候主播连麦回调
* *
@ -819,7 +855,8 @@ public class LiveAudienceActivity extends LiveActivity {
mStream = liveBean.getStream(); mStream = liveBean.getStream();
mAncherName = liveBean.getUserNiceName(); mAncherName = liveBean.getUserNiceName();
mAncherIcon = liveBean.getAvatar(); mAncherIcon = liveBean.getAvatar();
manager.onAdd(liveBean, mLiveType, mLiveTypeVal, mLiveSDK); //暂时 true
manager.onAdd(liveBean, mLiveType, mLiveTypeVal, mLiveSDK, isSw);
} }
} }
} }
@ -845,8 +882,7 @@ public class LiveAudienceActivity extends LiveActivity {
} }
GiftCacheUtil.getInstance().restart(); GiftCacheUtil.getInstance().restart();
if (manager.isEnterRoom()) { if (manager.isEnterRoom()) {
new Handler(Looper.getMainLooper()).postDelayed(() -> OpenAdManager.getInstance().show(OpenAdManager.TYPE_LIVE, new Handler(Looper.getMainLooper()).postDelayed(() -> OpenAdManager.getInstance().show(OpenAdManager.TYPE_LIVE, LiveGuardInfo.isGuard(mLiveGuardInfo)), 400);
LiveGuardInfo.isGuard(mLiveGuardInfo)), 400);
} }
} }
@ -858,8 +894,7 @@ public class LiveAudienceActivity extends LiveActivity {
private void adjustFullScreen(Configuration config) { private void adjustFullScreen(Configuration config) {
final WindowInsetsControllerCompat insetsController = ViewCompat.getWindowInsetsController(getWindow().getDecorView()); final WindowInsetsControllerCompat insetsController = ViewCompat.getWindowInsetsController(getWindow().getDecorView());
if (insetsController == null) if (insetsController == null) return;
return;
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
insetsController.hide(WindowInsetsCompat.Type.systemBars()); insetsController.hide(WindowInsetsCompat.Type.systemBars());
} else { } else {
@ -909,7 +944,7 @@ public class LiveAudienceActivity extends LiveActivity {
if (userIndex != -1) { if (userIndex != -1) {
list.remove(userIndex); list.remove(userIndex);
} }
CustomDrawerPopupView customDrawerPopupView = new CustomDrawerPopupView(mContext).setList(list).setLiveId(mLiveBean.getUid()); CustomDrawerPopupView customDrawerPopupView = new CustomDrawerPopupView(mContext, isSw).setList(list).setLiveId(mLiveBean.getUid());
customDrawerPopupView.setCallBack(new CustomDrawerPopupView.CustomDrawerPopupCallBack() { customDrawerPopupView.setCallBack(new CustomDrawerPopupView.CustomDrawerPopupCallBack() {
@Override @Override
@ -933,10 +968,11 @@ public class LiveAudienceActivity extends LiveActivity {
LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class); LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class);
new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() { new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() {
@Override @Override
public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk) { public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk, boolean isSw1) {
if (liveBean == null) { if (liveBean == null) {
return; return;
} }
isSw = isSw1;
if (MicStatusManager.getInstance().isMic(liveUid)) { if (MicStatusManager.getInstance().isMic(liveUid)) {
MicStatusManager.getInstance().showDownMicDialog(mContext); MicStatusManager.getInstance().showDownMicDialog(mContext);
return; return;
@ -958,8 +994,7 @@ public class LiveAudienceActivity extends LiveActivity {
public void informationTransfer(CustomDrawerPopupEvent event) { public void informationTransfer(CustomDrawerPopupEvent event) {
//跳转贵族 //跳转贵族
if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.noble))) { if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.noble))) {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.NOBLE));
.setType(LiveAudienceEvent.LiveAudienceType.NOBLE));
//跳转守护 //跳转守护
} else if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.guard_guard))) { } else if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.guard_guard))) {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent()
@ -968,8 +1003,7 @@ public class LiveAudienceActivity extends LiveActivity {
manager.onGuardRed(); manager.onGuardRed();
//跳转粉丝团 //跳转粉丝团
} else if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.fan_club))) { } else if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.fan_club))) {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.FAN_CLUB));
.setType(LiveAudienceEvent.LiveAudienceType.FAN_CLUB));
} }
} }
@ -995,69 +1029,53 @@ public class LiveAudienceActivity extends LiveActivity {
@Override @Override
public void evenTheWheat() { public void evenTheWheat() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.LIAN_MAI));
.setType(LiveAudienceEvent.LiveAudienceType.LIAN_MAI));
} }
@Override @Override
public void effectsSetting() { public void effectsSetting() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.EFFECTS_SETTINGS));
.setType(LiveAudienceEvent.LiveAudienceType.EFFECTS_SETTINGS));
} }
@Override @Override
public void slideSetting() { public void slideSetting() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.SLIDE_SETTINGS));
.setType(LiveAudienceEvent.LiveAudienceType.SLIDE_SETTINGS));
} }
@Override @Override
public void floatSetting() { public void floatSetting() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.FLOAT_SETTING));
.setType(LiveAudienceEvent.LiveAudienceType.FLOAT_SETTING));
} }
@Override @Override
public void systemNotice() { public void systemNotice() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setBean(mLiveBean).setType(LiveAudienceEvent.LiveAudienceType.NOTICE));
.setBean(mLiveBean)
.setType(LiveAudienceEvent.LiveAudienceType.NOTICE));
} }
@Override @Override
public void changeVideo() { public void changeVideo() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setBean(mLiveBean).setType(LiveAudienceEvent.LiveAudienceType.LIVE_VIDEO));
.setBean(mLiveBean)
.setType(LiveAudienceEvent.LiveAudienceType.LIVE_VIDEO));
} }
@Override @Override
public void online() { public void online() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setBean(mLiveBean).setType(LiveAudienceEvent.LiveAudienceType.ONLINE));
.setBean(mLiveBean)
.setType(LiveAudienceEvent.LiveAudienceType.ONLINE));
} }
@Override @Override
public void reportLayout() { public void reportLayout() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setBean(mLiveBean).setType(LiveAudienceEvent.LiveAudienceType.REPORT));
.setBean(mLiveBean)
.setType(LiveAudienceEvent.LiveAudienceType.REPORT));
} }
@Override @Override
public void share() { public void share() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setBean(mLiveBean).setType(LiveAudienceEvent.LiveAudienceType.LIVE_SHARE));
.setBean(mLiveBean)
.setType(LiveAudienceEvent.LiveAudienceType.LIVE_SHARE));
} }
@Override @Override
public void changeFontSize() { public void changeFontSize() {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setBean(mLiveBean).setType(LiveAudienceEvent.LiveAudienceType.FONT_SIZE));
.setBean(mLiveBean)
.setType(LiveAudienceEvent.LiveAudienceType.FONT_SIZE));
} }
@Override @Override
@ -1065,23 +1083,18 @@ public class LiveAudienceActivity extends LiveActivity {
if (manager != null && manager.getsudGameMin()) { if (manager != null && manager.getsudGameMin()) {
ToastUtil.show(WordUtil.isNewZh() ? "您已在游戏房间中" : "You are already in the game room"); ToastUtil.show(WordUtil.isNewZh() ? "您已在游戏房间中" : "You are already in the game room");
} else { } else {
new XPopup.Builder(mContext) //直播间来的
.enableDrag(false) new XPopup.Builder(mContext).enableDrag(false)
// .dismissOnTouchOutside(false) // .dismissOnTouchOutside(false)
// .dismissOnBackPressed(false) // .dismissOnBackPressed(false)
.moveUpToKeyboard(false) .moveUpToKeyboard(false).asCustom(new SudGameListPopup(mContext, interactionID, child, mLiveUid))
.asCustom(new SudGameListPopup(mContext, interactionID, child, mLiveUid))
.show(); .show();
} }
} }
}); });
new XPopup.Builder(mContext) new XPopup.Builder(mContext).hasShadowBg(false).isDestroyOnDismiss(true).isLightStatusBar(false).popupPosition(PopupPosition.Right)//右边
.hasShadowBg(false)
.isDestroyOnDismiss(true)
.isLightStatusBar(false)
.popupPosition(PopupPosition.Right)//右边
.hasStatusBarShadow(true) //启用状态栏阴影 .hasStatusBarShadow(true) //启用状态栏阴影
.setPopupCallback(new XPopupCallback() { .setPopupCallback(new XPopupCallback() {
@Override @Override
@ -1127,9 +1140,7 @@ public class LiveAudienceActivity extends LiveActivity {
public void onClickOutside(BasePopupView popupView) { public void onClickOutside(BasePopupView popupView) {
} }
}) }).asCustom(customDrawerPopupView).show();
.asCustom(customDrawerPopupView)
.show();
} }
break; break;
@ -1179,15 +1190,9 @@ public class LiveAudienceActivity extends LiveActivity {
//粉絲團粉絲團 //粉絲團粉絲團
//不是粉絲 //不是粉絲
if (LiveAudienceActivity.is_fans == null || "2".equals(LiveAudienceActivity.is_fans)) { if (LiveAudienceActivity.is_fans == null || "2".equals(LiveAudienceActivity.is_fans)) {
bundle.putString(Constants.URL, bundle.putString(Constants.URL, (CommonAppConfig.HOST + "/h5/live/joinFansClub.html" + "?uid=" + userInfo.getId() + "&token=" + userInfo.getToken() + "&anchorUid=" + mLiveUid) + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0));
(CommonAppConfig.HOST + "/h5/live/joinFansClub.html" +
"?uid=" + userInfo.getId() +
"&token=" + userInfo.getToken() + "&anchorUid=" + mLiveUid) + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0));
} else { } else {
bundle.putString(Constants.URL, bundle.putString(Constants.URL, (CommonAppConfig.HOST + "/h5/live/fansClub.html" + "?uid=" + userInfo.getId() + "&token=" + userInfo.getToken() + "&anchorUid=" + mLiveUid) + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0));
(CommonAppConfig.HOST + "/h5/live/fansClub.html" +
"?uid=" + userInfo.getId() +
"&token=" + userInfo.getToken() + "&anchorUid=" + mLiveUid) + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0));
} }
bundle.putString("liveUid", mLiveUid); bundle.putString("liveUid", mLiveUid);
bundle.putString("anchorName", mAncherName); bundle.putString("anchorName", mAncherName);
@ -1197,25 +1202,18 @@ public class LiveAudienceActivity extends LiveActivity {
break; break;
case GUARD: case GUARD:
if (event.getObject() == null) { if (event.getObject() == null) {
openNewGuardListWindow(mContext instanceof LiveRyAnchorActivity); openNewGuardListWindow(mContext instanceof LiveSwAnchorActivity);
} else { } else {
openNewBuyGuardWindow(true); openNewBuyGuardWindow(true);
} }
break; break;
case LIVE_WKS://周星榜 case LIVE_WKS://周星榜
String weeklyStarUrl = CommonAppConfig.HOST + "/h5/activity/weekStar/index.html?&uid=" String weeklyStarUrl = CommonAppConfig.HOST + "/h5/activity/weekStar/index.html?&uid=" + userInfo.getId() + "&token=" + userInfo.getToken() + "&anchorUid=" + mLiveUid + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0);
+ userInfo.getId() +
"&token=" + userInfo.getToken() + "&anchorUid=" + mLiveUid + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0);
ZhuangBanActivity.forward(mContext, weeklyStarUrl, false, 1); ZhuangBanActivity.forward(mContext, weeklyStarUrl, false, 1);
break; break;
case NOBLE: case NOBLE:
Constants.isTitle = true; Constants.isTitle = true;
String nobleUrl = CommonAppConfig.HOST + "/h5/Noble/index.html?nickname=" + userInfo.getUserNicename() String nobleUrl = CommonAppConfig.HOST + "/h5/Noble/index.html?nickname=" + userInfo.getUserNicename() + "&usernobId=" + userInfo.getNobleId() + "&token=" + userInfo.getToken() + "&anchorUid=" + mLiveBean.getUid() + "&ancherName=" + mLiveBean.getUserNiceName() + "&uid=" + userInfo.getId() + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0);
+ "&usernobId=" + userInfo.getNobleId()
+ "&token=" + userInfo.getToken()
+ "&anchorUid=" + mLiveBean.getUid()
+ "&ancherName=" + mLiveBean.getUserNiceName()
+ "&uid=" + userInfo.getId() + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0);
ZhuangBanActivity.forward(mContext, nobleUrl, false, 1); ZhuangBanActivity.forward(mContext, nobleUrl, false, 1);
break; break;
case LIAN_MAI: case LIAN_MAI:
@ -1229,9 +1227,7 @@ public class LiveAudienceActivity extends LiveActivity {
manager.micIngTypeTwo(event.getBean(), event.getLiveType(), event.getLiveTypeVal()); manager.micIngTypeTwo(event.getBean(), event.getLiveType(), event.getLiveTypeVal());
} else { } else {
//获取房间连麦状态 //获取房间连麦状态
HttpClient.getInstance().get("live.getDrLm", "live.getDrLm") HttpClient.getInstance().get("live.getDrLm", "live.getDrLm").params("uid", mLiveUid, true).execute(new HttpCallback() {
.params("uid", mLiveUid, true)
.execute(new HttpCallback() {
@Override @Override
public void onSuccess(int code, String msg, String[] info) { public void onSuccess(int code, String msg, String[] info) {
if (code == 0) { if (code == 0) {
@ -1268,31 +1264,20 @@ public class LiveAudienceActivity extends LiveActivity {
} }
break; break;
case OPEN_PARAMETERS: case OPEN_PARAMETERS:
mDanmuPrice = TextUtils.equals(event.getParametersModel().getmDanmuPrice(), mDanmuPrice) ? mDanmuPrice = TextUtils.equals(event.getParametersModel().getmDanmuPrice(), mDanmuPrice) ? mDanmuPrice : event.getParametersModel().getmDanmuPrice();
mDanmuPrice : event.getParametersModel().getmDanmuPrice(); mSocketUserType = TextUtils.equals(String.valueOf(mSocketUserType), String.valueOf(event.getParametersModel().getmSocketUserType())) ? mSocketUserType : event.getParametersModel().getmSocketUserType();
mSocketUserType = TextUtils.equals(String.valueOf(mSocketUserType), String.valueOf(event.getParametersModel().getmSocketUserType())) ? mChatLevel = TextUtils.equals(String.valueOf(mChatLevel), String.valueOf(event.getParametersModel().getmChatLevel())) ? mChatLevel : event.getParametersModel().getmChatLevel();
mSocketUserType : event.getParametersModel().getmSocketUserType(); mDanMuLevel = TextUtils.equals(String.valueOf(mDanMuLevel), String.valueOf(event.getParametersModel().getmDanMuLevel())) ? mDanMuLevel : event.getParametersModel().getmDanMuLevel();
mChatLevel = TextUtils.equals(String.valueOf(mChatLevel), String.valueOf(event.getParametersModel().getmChatLevel())) ? mLiveType = TextUtils.equals(String.valueOf(mLiveType), String.valueOf(event.getParametersModel().getmLiveType())) ? mLiveType : event.getParametersModel().getmLiveType();
mChatLevel : event.getParametersModel().getmChatLevel(); mLiveTypeVal = TextUtils.equals(String.valueOf(mLiveTypeVal), String.valueOf(event.getParametersModel().getmLiveTypeVal())) ? mLiveTypeVal : event.getParametersModel().getmLiveTypeVal();
mDanMuLevel = TextUtils.equals(String.valueOf(mDanMuLevel), String.valueOf(event.getParametersModel().getmDanMuLevel())) ? mLiveGuardInfo = event.getParametersModel().getmLiveGuardInfo() == null ? mLiveGuardInfo : event.getParametersModel().getmLiveGuardInfo();
mDanMuLevel : event.getParametersModel().getmDanMuLevel(); liveBg = TextUtils.equals(String.valueOf(liveBg), String.valueOf(event.getParametersModel().getLiveBg())) ? liveBg : event.getParametersModel().getLiveBg();
mLiveType = TextUtils.equals(String.valueOf(mLiveType), String.valueOf(event.getParametersModel().getmLiveType())) ? is_fans = TextUtils.equals(String.valueOf(is_fans), String.valueOf(event.getParametersModel().getIs_fans())) ? is_fans : event.getParametersModel().getIs_fans();
mLiveType : event.getParametersModel().getmLiveType(); fansNum = TextUtils.equals(String.valueOf(fansNum), String.valueOf(event.getParametersModel().getFansNum())) ? fansNum : event.getParametersModel().getFansNum();
mLiveTypeVal = TextUtils.equals(String.valueOf(mLiveTypeVal), String.valueOf(event.getParametersModel().getmLiveTypeVal())) ?
mLiveTypeVal : event.getParametersModel().getmLiveTypeVal();
mLiveGuardInfo = event.getParametersModel().getmLiveGuardInfo() == null ?
mLiveGuardInfo : event.getParametersModel().getmLiveGuardInfo();
liveBg = TextUtils.equals(String.valueOf(liveBg), String.valueOf(event.getParametersModel().getLiveBg())) ?
liveBg : event.getParametersModel().getLiveBg();
is_fans = TextUtils.equals(String.valueOf(is_fans), String.valueOf(event.getParametersModel().getIs_fans())) ?
is_fans : event.getParametersModel().getIs_fans();
fansNum = TextUtils.equals(String.valueOf(fansNum), String.valueOf(event.getParametersModel().getFansNum())) ?
fansNum : event.getParametersModel().getFansNum();
break; break;
case ACTIVITY_CENTER://活动中心 case ACTIVITY_CENTER://活动中心
String url = CommonAppConfig.HOST + "/h5/live/hallOfFame/index.html?g=Appapi&m=Turntable&a=tricky"; String url = CommonAppConfig.HOST + "/h5/live/hallOfFame/index.html?g=Appapi&m=Turntable&a=tricky";
url += "&uid=" + CommonAppConfig.getInstance().getUid() + "&token=" url += "&uid=" + CommonAppConfig.getInstance().getUid() + "&token=" + CommonAppConfig.getInstance().getToken() + "&anchorUid=" + mLiveUid + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0);
+ CommonAppConfig.getInstance().getToken() + "&anchorUid=" + mLiveUid + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0);
Log.i("tag", url); Log.i("tag", url);
Intent intent = new Intent(mContext, ZhuangBanActivity.class); Intent intent = new Intent(mContext, ZhuangBanActivity.class);
intent.putExtra("url", url); intent.putExtra("url", url);
@ -1314,10 +1299,7 @@ public class LiveAudienceActivity extends LiveActivity {
break; break;
case POPULAR: case POPULAR:
url = CommonAppConfig.HOST + "/h5/activity/PopularityTask/index.html"; url = CommonAppConfig.HOST + "/h5/activity/PopularityTask/index.html";
url += "?anchorUid=" + mLiveUid url += "?anchorUid=" + mLiveUid + "&stream=" + mStream + "&uid=" + CommonAppConfig.getInstance().getUid() + "&token=" + CommonAppConfig.getInstance().getToken() + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0);
+ "&stream=" + mStream
+ "&uid=" + CommonAppConfig.getInstance().getUid()
+ "&token=" + CommonAppConfig.getInstance().getToken() + "&isZh=" + (WordUtil.isNewZh() ? "1" : 0);
LiveHDDialogFragment liveHDDialogFragment = new LiveHDDialogFragment(); LiveHDDialogFragment liveHDDialogFragment = new LiveHDDialogFragment();
bundle.putString("url", url); bundle.putString("url", url);
bundle.putInt("show_type", 0); bundle.putInt("show_type", 0);
@ -1390,16 +1372,13 @@ public class LiveAudienceActivity extends LiveActivity {
} }
if (micListener != null) { if (micListener != null) {
micListener.updateMicList(mMicQueueList); micListener.updateMicList(mMicQueueList);
DialogUitl.showSimpleDialog(mContext, DialogUitl.showSimpleDialog(mContext, String.format(mContext.getString(R.string.live_mic_user_apply), ((LinkMicUserBean) event.getObject()).getUserNicename()), new DialogUitl.SimpleCallback() {
String.format(mContext.getString(R.string.live_mic_user_apply), ((LinkMicUserBean) event.getObject()).getUserNicename()),
new DialogUitl.SimpleCallback() {
@Override @Override
public void onConfirmClick(Dialog dialog, String content) { public void onConfirmClick(Dialog dialog, String content) {
openMicWindow(2); openMicWindow(2);
dialog.dismiss(); dialog.dismiss();
} }
} });
);
} }
break; break;
case LINK_MIC_CANCEL: case LINK_MIC_CANCEL:
@ -1447,7 +1426,7 @@ public class LiveAudienceActivity extends LiveActivity {
if (manager.getmLivePlayViewHolder() != null) { if (manager.getmLivePlayViewHolder() != null) {
manager.getmLivePlayViewHolder().setPkEndview(); manager.getmLivePlayViewHolder().setPkEndview();
manager.setPkStatus(false); manager.setPkStatus(false);
manager.mLivePlayViewHolder.endPk();
} }
if (manager != null) { if (manager != null) {
manager.removeDetailView(); manager.removeDetailView();
@ -1622,22 +1601,14 @@ public class LiveAudienceActivity extends LiveActivity {
if (type.equals(bean.getType())) { if (type.equals(bean.getType())) {
switch (type) { switch (type) {
case "1": case "1":
startActivity(new Intent(mContext, SystemMessageActivity.class) startActivity(new Intent(mContext, SystemMessageActivity.class).putExtra("type", bean.getType()).putExtra("uid", "").putExtra("title", bean.getTitle()).putExtra("headImg", ""));
.putExtra("type", bean.getType())
.putExtra("uid", "")
.putExtra("title", bean.getTitle())
.putExtra("headImg", ""));
break; break;
case "3": case "3":
AppEventsLogger.newLogger(mContext).logEvent("FB_customer_service"); AppEventsLogger.newLogger(mContext).logEvent("FB_customer_service");
if (bean.getLink() != null && !"".equals(bean.getLink())) { if (bean.getLink() != null && !"".equals(bean.getLink())) {
WebViewActivity.forward(mContext, bean.getLink(), true); WebViewActivity.forward(mContext, bean.getLink(), true);
} else { } else {
startActivity(new Intent(mContext, SystemMessageActivity.class) startActivity(new Intent(mContext, SystemMessageActivity.class).putExtra("type", bean.getType()).putExtra("uid", "").putExtra("title", "").putExtra("headImg", ""));
.putExtra("type", bean.getType())
.putExtra("uid", "")
.putExtra("title", "")
.putExtra("headImg", ""));
} }
break; break;
@ -1666,9 +1637,10 @@ public class LiveAudienceActivity extends LiveActivity {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("num", "9"); map.put("num", "9");
map.put("live_recommend", "sidebar"); map.put("live_recommend", "sidebar");
map.put(" is_shengwang", isSw ? "1" : "0");
//推荐位 //推荐位
MainNetManager.get(mContext) MainNetManager.get(mContext).anchorRecommend(map, new com.yunbao.common.http.base.HttpCallback<AnchorRecommendModel>() {
.anchorRecommend(map, new com.yunbao.common.http.base.HttpCallback<AnchorRecommendModel>() {
@Override @Override
public void onSuccess(AnchorRecommendModel anchorRecommendModel) { public void onSuccess(AnchorRecommendModel anchorRecommendModel) {
list.clear(); list.clear();
@ -1756,11 +1728,7 @@ public class LiveAudienceActivity extends LiveActivity {
case 0: case 0:
if (liveSudGamePopupXPopup == null) { if (liveSudGamePopupXPopup == null) {
liveSudGamePopupXPopup = new LiveSudGamePopup(mContext, event.getCreateSudRoomModel()); liveSudGamePopupXPopup = new LiveSudGamePopup(mContext, event.getCreateSudRoomModel());
new XPopup.Builder(mContext) new XPopup.Builder(mContext).enableDrag(false).dismissOnTouchOutside(false).dismissOnBackPressed(false).asCustom(liveSudGamePopupXPopup).show();
.enableDrag(false)
.dismissOnTouchOutside(false)
.dismissOnBackPressed(false)
.asCustom(liveSudGamePopupXPopup).show();
} else { } else {
if (liveSudGamePopupXPopup != null) { if (liveSudGamePopupXPopup != null) {
liveSudGamePopupXPopup.dialog.show(); liveSudGamePopupXPopup.dialog.show();
@ -1856,17 +1824,14 @@ public class LiveAudienceActivity extends LiveActivity {
if (!TextUtils.isEmpty(event.getRightsInterests())) { if (!TextUtils.isEmpty(event.getRightsInterests())) {
//跳转贵族 //跳转贵族
if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.noble))) { if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.noble))) {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.NOBLE));
.setType(LiveAudienceEvent.LiveAudienceType.NOBLE));
//跳转守护 //跳转守护
} else if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.guard_guard))) { } else if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.guard_guard))) {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.GUARD));
.setType(LiveAudienceEvent.LiveAudienceType.GUARD));
manager.onGuardRed(); manager.onGuardRed();
//跳转粉丝团 //跳转粉丝团
} else if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.fan_club))) { } else if (TextUtils.equals(event.getRightsInterests(), getString(com.yunbao.common.R.string.fan_club))) {
Bus.get().post(new LiveAudienceEvent() Bus.get().post(new LiveAudienceEvent().setType(LiveAudienceEvent.LiveAudienceType.FAN_CLUB));
.setType(LiveAudienceEvent.LiveAudienceType.FAN_CLUB));
} }
} }
//互动游戏 //互动游戏
@ -1875,12 +1840,11 @@ public class LiveAudienceActivity extends LiveActivity {
if (manager != null && manager.getsudGameMin()) { if (manager != null && manager.getsudGameMin()) {
ToastUtil.show(WordUtil.isNewZh() ? "您已在游戏房间中" : "You are already in the game room"); ToastUtil.show(WordUtil.isNewZh() ? "您已在游戏房间中" : "You are already in the game room");
} else { } else {
new XPopup.Builder(mContext) //直播间来的
.enableDrag(false) new XPopup.Builder(mContext).enableDrag(false)
// .dismissOnTouchOutside(false) // .dismissOnTouchOutside(false)
// .dismissOnBackPressed(false) // .dismissOnBackPressed(false)
.moveUpToKeyboard(false) .moveUpToKeyboard(false).asCustom(new SudGameListPopup(mContext, event.getInteractionID(), event.getChild(), mLiveUid))
.asCustom(new SudGameListPopup(mContext, event.getInteractionID(), event.getChild(), mLiveUid))
.show(); .show();
} }
@ -1938,9 +1902,7 @@ public class LiveAudienceActivity extends LiveActivity {
new Handler().postDelayed(new Runnable() { new Handler().postDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
new XPopup.Builder(mContext) new XPopup.Builder(mContext).asCustom(new DragonExpirePopup(mContext, mLiveUid, maturityDateRemindModel, mStream)).show();
.asCustom(new DragonExpirePopup(mContext, mLiveUid, maturityDateRemindModel, mStream))
.show();
} }
}, 3000); }, 3000);
@ -1987,8 +1949,7 @@ public class LiveAudienceActivity extends LiveActivity {
private void checkMsgRed() { private void checkMsgRed() {
LiveNetManager.get(mContext) LiveNetManager.get(mContext).getContactMsg(1, new com.yunbao.common.http.base.HttpCallback<List<LiveUserMailBoxModel>>() {
.getContactMsg(1, new com.yunbao.common.http.base.HttpCallback<List<LiveUserMailBoxModel>>() {
@Override @Override
public void onSuccess(List<LiveUserMailBoxModel> data) { public void onSuccess(List<LiveUserMailBoxModel> data) {
Log.i(TAG, "onSuccess: " + data.size()); Log.i(TAG, "onSuccess: " + data.size());

View File

@ -552,7 +552,7 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
boolean ret = RCRTCEngine.getInstance().getDefaultVideoStream().setWatermark(BitmapUtil.getInstance().convertMirror(resource), rect); boolean ret = RCRTCEngine.getInstance().getDefaultVideoStream().setWatermark(BitmapUtil.getInstance().convertMirror(resource), rect);
sendSystemMessage(mContext.getString(R.string.live_anchor_leave)); sendSystemMessageRy(mContext.getString(R.string.live_anchor_leave));
} }
@Override @Override
@ -565,7 +565,7 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
leave_img.setVisibility(View.GONE); leave_img.setVisibility(View.GONE);
// 清除水印 // 清除水印
boolean ret = RCRTCEngine.getInstance().getDefaultVideoStream().setWatermark(null, rect); boolean ret = RCRTCEngine.getInstance().getDefaultVideoStream().setWatermark(null, rect);
sendSystemMessage(mContext.getString(R.string.live_anchor_come_back)); sendSystemMessageRy(mContext.getString(R.string.live_anchor_come_back));
} }
HttpClient.getInstance().get("Live.isLeave", "Live.isLeave") HttpClient.getInstance().get("Live.isLeave", "Live.isLeave")
@ -719,6 +719,7 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
fragment.show(getSupportFragmentManager(), "LiveLinkMicListDialogFragment");*/ fragment.show(getSupportFragmentManager(), "LiveLinkMicListDialogFragment");*/
FreePkDialogFragment fragment = new FreePkDialogFragment(); FreePkDialogFragment fragment = new FreePkDialogFragment();
fragment.setDrPkNum(pk_nub); fragment.setDrPkNum(pk_nub);
fragment.setLiveUid(mLiveUid);
fragment.show(getSupportFragmentManager(), "LiveLinkMicListDialogFragment"); fragment.show(getSupportFragmentManager(), "LiveLinkMicListDialogFragment");
} }
@ -736,6 +737,7 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
public void openRandomPkWindow() { public void openRandomPkWindow() {
RandomPkDialogFragment fragment = new RandomPkDialogFragment(); RandomPkDialogFragment fragment = new RandomPkDialogFragment();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putBoolean("isSw",false);
fragment.setArguments(bundle); fragment.setArguments(bundle);
fragment.show(getSupportFragmentManager(), "RandomPkDialogFragment"); fragment.show(getSupportFragmentManager(), "RandomPkDialogFragment");
} }
@ -784,7 +786,7 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
} }
mLiveReadyViewHolder = null; mLiveReadyViewHolder = null;
if (mLiveRoomViewHolder == null) { if (mLiveRoomViewHolder == null) {
mLiveRoomViewHolder = new LiveRoomViewHolder(true, 2, mContext, mContainer, (GifImageView) findViewById(R.id.gift_gif), (SVGAImageView) findViewById(R.id.gift_svga), mContainerWrap, getWindowManager()); mLiveRoomViewHolder = new LiveRoomViewHolder(true, 2, mContext, mContainer, (GifImageView) findViewById(R.id.gift_gif), (SVGAImageView) findViewById(R.id.gift_svga), mContainerWrap, getWindowManager(),isSw);
mLiveRoomViewHolder.setManager(manager); mLiveRoomViewHolder.setManager(manager);
mLiveRoomViewHolder.addToParent(); mLiveRoomViewHolder.addToParent();
mLiveRoomViewHolder.subscribeActivityLifeCycle(); mLiveRoomViewHolder.subscribeActivityLifeCycle();
@ -970,7 +972,7 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
JSONObject obj = JSON.parseObject(info[0]); JSONObject obj = JSON.parseObject(info[0]);
JSONObject datas = obj.getJSONObject("data"); JSONObject datas = obj.getJSONObject("data");
try { try {
SocketRyChatUtil.closeLive(datas.getString("votes"), datas.getString("length"), datas.getString("nums"), mLiveUid, mSocketRyClient); SocketRyChatUtil.closeLive(datas.getString("votes"), datas.getString("length"), datas.getString("nums"), mLiveUid);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -1235,8 +1237,6 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
JSONObject obj = JSON.parseObject(info[0]); JSONObject obj = JSON.parseObject(info[0]);
if (obj != null) { if (obj != null) {
if (obj.getString("ispk").equals("0")) { if (obj.getString("ispk").equals("0")) {
IMRTCManager.getInstance().requestJoinOtherRoom(pkUid, true, extra, new IRCRTCResultCallback() { IMRTCManager.getInstance().requestJoinOtherRoom(pkUid, true, extra, new IRCRTCResultCallback() {
@Override @Override
public void onSuccess() { public void onSuccess() {
@ -1268,7 +1268,7 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
}); });
} else { } else {
ToastUtil.show("主播正在PK稍後再試"); ToastUtil.show(mContext.getString(R.string.pking_over));
if (RandomPkManager.getInstance().isRandomModel()) { if (RandomPkManager.getInstance().isRandomModel()) {
RandomPkManager.getInstance().setPkStatus(RandomPkManager.PK_STATUS_REFUSE); RandomPkManager.getInstance().setPkStatus(RandomPkManager.PK_STATUS_REFUSE);
} }
@ -1343,7 +1343,7 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
} }
}); });
} else { } else {
ToastUtil.show("主播正在PK稍後再試"); ToastUtil.show(mContext.getString(R.string.pking_over));
} }
} }
} }
@ -1402,6 +1402,11 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
} }
} }
@Override
public void onLinkDRMicPKToUser(UserBean u) {
}
//多人PK接受 //多人PK接受
@Override @Override
public void onLinkDRMicPkApplyOk(UserBean u) { public void onLinkDRMicPkApplyOk(UserBean u) {
@ -1641,8 +1646,11 @@ public class LiveRyAnchorActivity extends LiveActivity implements LiveFunctionCl
} }
if (mLiveRoomViewHolder != null) { if (mLiveRoomViewHolder != null) {
mLiveRoomViewHolder.seisShowGif(true); mLiveRoomViewHolder.seisShowGif(true);
if(isDRPK==1){
mLiveRoomViewHolder.endDRGif(); mLiveRoomViewHolder.endDRGif();
} }
}
// if (mLiveRoomViewHolder != null) { // if (mLiveRoomViewHolder != null) {
// mLiveRoomViewHolder.hotAddVisibility(false); // mLiveRoomViewHolder.hotAddVisibility(false);
// } // }

File diff suppressed because it is too large Load Diff

View File

@ -213,7 +213,7 @@ public class LiveTRTCAnchorActivity extends TRTCBaseActivity {
return; return;
} }
String title = mEditTitle.getText().toString().trim(); String title = mEditTitle.getText().toString().trim();
LiveHttpUtil.newcreateRoom(title, mLiveClassID, mLiveType, mLiveTypeVal, null,0, new HttpCallback() { LiveHttpUtil.newcreateRoom(title, mLiveClassID, mLiveType, mLiveTypeVal, null,0,false, new HttpCallback() {
@Override @Override
public void onSuccess(int code, String msg, final String[] info) { public void onSuccess(int code, String msg, final String[] info) {
if (code == 0 && info.length > 0) { if (code == 0 && info.length > 0) {

View File

@ -197,8 +197,8 @@ public class PDLIiveChatActivity extends FragmentActivity {
LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class); LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class);
new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() { new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() {
@Override @Override
public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk) { public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk,boolean isSw) {
RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveSdk), Integer.parseInt(liveTypeVal)); RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveSdk), Integer.parseInt(liveTypeVal),isSw);
} }
@Override @Override

View File

@ -19,6 +19,7 @@ import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.lxj.xpopup.XPopup; import com.lxj.xpopup.XPopup;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.Constants; import com.yunbao.common.Constants;
import com.yunbao.common.R; import com.yunbao.common.R;
import com.yunbao.common.activity.AbsActivity; import com.yunbao.common.activity.AbsActivity;
@ -40,7 +41,7 @@ import com.yunbao.common.glide.ImgLoader;
import com.yunbao.common.http.base.HttpCallback; import com.yunbao.common.http.base.HttpCallback;
import com.yunbao.common.http.live.LiveNetManager; import com.yunbao.common.http.live.LiveNetManager;
import com.yunbao.common.manager.IMLoginManager; import com.yunbao.common.manager.IMLoginManager;
import com.yunbao.common.manager.imrongcloud.GameMicManager; import com.yunbao.common.manager.imrongcloud.GameRyMicManager;
import com.yunbao.common.sud.QuickStartGameViewModel; import com.yunbao.common.sud.QuickStartGameViewModel;
import com.yunbao.common.sud.decorator.SudFSMMGDecorator; import com.yunbao.common.sud.decorator.SudFSMMGDecorator;
import com.yunbao.common.sud.model.GameConfigModel; import com.yunbao.common.sud.model.GameConfigModel;
@ -71,8 +72,8 @@ import cn.rongcloud.rtc.api.RCRTCRoom;
import cn.rongcloud.rtc.api.stream.RCRTCInputStream; import cn.rongcloud.rtc.api.stream.RCRTCInputStream;
import cn.rongcloud.rtc.base.RTCErrorCode; import cn.rongcloud.rtc.base.RTCErrorCode;
@Route(path = RouteUtil.PATH_SudGameActivity) @Route(path = RouteUtil.PATH_SudRyGameActivity)
public class SudGameActivity extends AbsActivity implements GameMicManager.MeetingCallback { public class SudRyGameActivity extends AbsActivity implements GameRyMicManager.MeetingCallback {
private FrameLayout gameContainer; private FrameLayout gameContainer;
private long mInteractionID; private long mInteractionID;
private String mLiveUid; private String mLiveUid;
@ -80,7 +81,7 @@ public class SudGameActivity extends AbsActivity implements GameMicManager.Meeti
private CreateSudRoomModel mCreateSudRoomModel; private CreateSudRoomModel mCreateSudRoomModel;
private TextView roomName, roomNumber; private TextView roomName, roomNumber;
private GameMicManager gameMicManager; private GameRyMicManager gameMicManager;
private ImageView gameCloseWheat, gameSeat; private ImageView gameCloseWheat, gameSeat;
private boolean disable = true, publishDefault = false; private boolean disable = true, publishDefault = false;
@ -107,7 +108,7 @@ public class SudGameActivity extends AbsActivity implements GameMicManager.Meeti
private List<CustomSidebarChildModel> customSidebarChildModels = new ArrayList<>(); private List<CustomSidebarChildModel> customSidebarChildModels = new ArrayList<>();
private void initDate() { private void initDate() {
CommonAppConfig.getInstance().getConfig().isSw();
LiveNetManager.get(mContext) LiveNetManager.get(mContext)
.getCustomSidebarInfo("1", new HttpCallback<List<CustomSidebarInfoModel>>() { .getCustomSidebarInfo("1", new HttpCallback<List<CustomSidebarInfoModel>>() {
@Override @Override
@ -137,9 +138,9 @@ public class SudGameActivity extends AbsActivity implements GameMicManager.Meeti
.getRoomMicStatus(new HttpCallback<RoomMicStatusModel>() { .getRoomMicStatus(new HttpCallback<RoomMicStatusModel>() {
@Override @Override
public void onSuccess(RoomMicStatusModel data) { public void onSuccess(RoomMicStatusModel data) {
gameMicManager = new GameMicManager(); gameMicManager = new GameRyMicManager();
gameMicManager.attachView(SudGameActivity.this); gameMicManager.attachView(SudRyGameActivity.this);
gameMicManager.config(SudGameActivity.this); gameMicManager.config(SudRyGameActivity.this);
//语音 //语音
if (TextUtils.equals(data.getMicStatus(), "1")) { if (TextUtils.equals(data.getMicStatus(), "1")) {
imOff = true; imOff = true;
@ -276,7 +277,7 @@ public class SudGameActivity extends AbsActivity implements GameMicManager.Meeti
bundle.putString(Constants.STREAM, ""); bundle.putString(Constants.STREAM, "");
bundle.putString(Constants.TO_UID, sudGameUserModel.getId() + ""); bundle.putString(Constants.TO_UID, sudGameUserModel.getId() + "");
fragment.setArguments(bundle); fragment.setArguments(bundle);
fragment.show(((SudGameActivity) mContext).getSupportFragmentManager(), "LiveUserDialogFragment"); fragment.show(((SudRyGameActivity) mContext).getSupportFragmentManager(), "LiveUserDialogFragment");
} }
}); });
userList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)); userList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));

View File

@ -0,0 +1,744 @@
package com.yunbao.live.activity;
import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.Constants;
import com.yunbao.common.R;
import com.yunbao.common.activity.AbsActivity;
import com.yunbao.common.adapter.SudGameChatAdapter;
import com.yunbao.common.adapter.SudGameUserListAdapter;
import com.yunbao.common.bean.CheckRemainingBalance;
import com.yunbao.common.bean.CreateSudRoomModel;
import com.yunbao.common.bean.CustomSidebarChildModel;
import com.yunbao.common.bean.CustomSidebarInfoModel;
import com.yunbao.common.bean.HttpCallbackModel;
import com.yunbao.common.bean.RoomMicStatusModel;
import com.yunbao.common.bean.SudGameChatImModel;
import com.yunbao.common.bean.SudGameUserModel;
import com.yunbao.common.dialog.SudGameInputPopupWindow;
import com.yunbao.common.event.CheckRemainingBalanceEvent;
import com.yunbao.common.event.SubGameEvent;
import com.yunbao.common.event.SudGameSocketImEvent;
import com.yunbao.common.glide.ImgLoader;
import com.yunbao.common.http.base.HttpCallback;
import com.yunbao.common.http.live.LiveNetManager;
import com.yunbao.common.manager.IMLoginManager;
import com.yunbao.common.manager.imrongcloud.GameSwMicManager;
import com.yunbao.common.sud.QuickStartGameViewModel;
import com.yunbao.common.sud.decorator.SudFSMMGDecorator;
import com.yunbao.common.sud.model.GameConfigModel;
import com.yunbao.common.sud.model.GameViewInfoModel;
import com.yunbao.common.sud.state.SudMGPAPPState;
import com.yunbao.common.sud.state.SudMGPMGState;
import com.yunbao.common.utils.Bus;
import com.yunbao.common.utils.DpUtil;
import com.yunbao.common.utils.ProcessResultUtil;
import com.yunbao.common.utils.RouteUtil;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.utils.WordUtil;
import com.yunbao.common.views.LiveSudGameHistoryPopup;
import com.yunbao.common.views.TopGradual;
import com.yunbao.common.views.weight.ViewClicksAntiShake;
import com.yunbao.live.dialog.LiveUserDialogFragment;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import cn.rongcloud.rtc.api.RCRTCEngine;
import cn.rongcloud.rtc.api.RCRTCRemoteUser;
import cn.rongcloud.rtc.api.RCRTCRoom;
import cn.rongcloud.rtc.api.stream.RCRTCInputStream;
import cn.rongcloud.rtc.base.RTCErrorCode;
import io.agora.beautyapi.faceunity.agora.SWAuManager;
import io.rong.imlib.IRongCoreCallback;
import io.rong.imlib.IRongCoreEnum;
import io.rong.imlib.chatroom.base.RongChatRoomClient;
@Route(path = RouteUtil.PATH_SudSwGameActivity)
public class SudSwGameActivity extends AbsActivity implements GameSwMicManager.MeetingCallback {
private FrameLayout gameContainer;
private long mInteractionID;
private String mLiveUid;
private final QuickStartGameViewModel gameViewModel = new QuickStartGameViewModel(); // 创建ViewModel
private CreateSudRoomModel mCreateSudRoomModel;
private TextView roomName, roomNumber;
private GameSwMicManager gameMicManager;
private ImageView gameCloseWheat, gameSeat;
private boolean disable = true, publishDefault = false;
private RecyclerView chatList, userList;
private SudGameChatAdapter mLiveChatAdapter;
private SudGameUserListAdapter sudGameUserListAdapter;
private ProcessResultUtil mProcessResultUtil;
private List<String> muteUser = new ArrayList<>();
private boolean imOff;
private boolean isSw = CommonAppConfig.getInstance().getConfig().isSw();
@Override
protected int getLayoutId() {
return R.layout.activity_sud_game;
}
@Override
protected void main() {
Bus.getOn(this);
super.main();
initView();
initDate();
}
private List<CustomSidebarChildModel> customSidebarChildModels = new ArrayList<>();
private void initDate() {
LiveNetManager.get(mContext).getCustomSidebarInfo("1", new HttpCallback<List<CustomSidebarInfoModel>>() {
@Override
public void onSuccess(List<CustomSidebarInfoModel> data) {
for (CustomSidebarInfoModel datum : data) {
if (datum.getType().equals("6")) {
customSidebarChildModels = datum.getChild();
return;
}
}
}
@Override
public void onError(String error) {
}
});
// 设置禁用麦克风采集
//RCRTCEngine.getInstance().getDefaultAudioStream().setMicrophoneDisable(disable);
ImgLoader.display(mContext, R.mipmap.icon_game_close_wheat, gameCloseWheat);
gameCloseWheat.setVisibility(View.INVISIBLE);
mProcessResultUtil = new ProcessResultUtil(this);
LiveNetManager.get(mContext).getRoomMicStatus(new HttpCallback<RoomMicStatusModel>() {
@Override
public void onSuccess(RoomMicStatusModel data) {
gameMicManager = new GameSwMicManager();
gameMicManager.attachView(SudSwGameActivity.this);
gameMicManager.config(SudSwGameActivity.this);
//初始化声网引擎
SWAuManager.get().initRtcEngineAudio(mContext);
//语音
if (TextUtils.equals(data.getMicStatus(), "1")) {
imOff = true;
gameSeat.setVisibility(View.VISIBLE);
userList.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (!mProcessResultUtil.checkPermissions(new String[]{Manifest.permission.RECORD_AUDIO})) {
ToastUtil.show("拒绝权限将无法使用上麦功能");
mProcessResultUtil.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, new Runnable() {
@Override
public void run() {
}
});
}
}
}, 1500);
} else {
imOff = false;
gameSeat.setVisibility(View.GONE);
userList.setVisibility(View.GONE);
}
if (TextUtils.equals(data.getImStatus(), "1")) {
findViewById(R.id.game_review_input).setVisibility(View.VISIBLE);
chatList.setVisibility(View.VISIBLE);
} else {
findViewById(R.id.game_review_input).setVisibility(View.GONE);
chatList.setVisibility(View.GONE);
}
gameMicManager.setmRoomID(mLiveUid);
if (isSw) {
SWAuManager.get().joinAudioRoom("v" + mLiveUid, CommonAppConfig.SWToken, Integer.parseInt(CommonAppConfig.getInstance().getUid()));
onJoinRoomSuccess(null);
onJoinSuccess();
} else {
gameMicManager.joinRoom(mLiveUid, imOff);
}
}
@Override
public void onError(String error) {
imOff = false;
//文字
findViewById(R.id.game_review_input).setVisibility(View.GONE);
chatList.setVisibility(View.GONE);
//语音
gameCloseWheat.setVisibility(View.GONE);
gameSeat.setVisibility(View.GONE);
userList.setVisibility(View.GONE);
}
});
}
private void onJoinSuccess() {
RongChatRoomClient.getInstance().joinChatRoom("v" + mLiveUid, -1, new IRongCoreCallback.OperationCallback() {
@Override
public void onSuccess() {
Log.i("tx", "加入成功");
gameMicManager.enterRoom();
}
@Override
public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {
Log.i("tx", "加入" + "失败" + coreErrorCode);
if (WordUtil.isNewZh()) {
ToastUtil.show("網絡不佳無法連接,請重新進入");
} else {
ToastUtil.show("The network is not connected, please re-enter");
}
}
});
}
@Override
protected void onDestroy() {
LiveNetManager.get(mContext).leaveMic(mLiveUid, new HttpCallback<HttpCallbackModel>() {
@Override
public void onSuccess(HttpCallbackModel data) {
}
@Override
public void onError(String error) {
}
});
if(isSw){
SWAuManager.get().exitChannelAll();
}
if (gameMicManager != null) {
gameMicManager.leaveRoom();
gameMicManager.detachView();
}
Bus.getOff(this);
super.onDestroy();
}
private void initView() {
String createSudRoomJson = getIntent().getStringExtra("CreateSudRoom");
mCreateSudRoomModel = new Gson().fromJson(createSudRoomJson, CreateSudRoomModel.class);
mInteractionID = mCreateSudRoomModel.getLongSudGameId();
mLiveUid = mCreateSudRoomModel.getSudGameRoomId();
gameContainer = findViewById(R.id.game_container);
roomName = findViewById(R.id.room_name);
roomNumber = findViewById(R.id.room_number);
gameCloseWheat = findViewById(R.id.game_close_wheat);
gameSeat = findViewById(R.id.game_seat);
chatList = findViewById(R.id.chat_list);
userList = findViewById(R.id.user_list);
//聊天栏
FrameLayout.LayoutParams params1 = (FrameLayout.LayoutParams) chatList.getLayoutParams();
params1.topMargin = DpUtil.dp2px(65);
chatList.setLayoutParams(params1);
chatList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
layoutManager.setOrientation(RecyclerView.VERTICAL);
layoutManager.setStackFromEnd(true);
chatList.setLayoutManager(layoutManager);
chatList.addItemDecoration(new TopGradual());
chatList.setItemViewCacheSize(10);
mLiveChatAdapter = new SudGameChatAdapter(mContext);
chatList.setAdapter(mLiveChatAdapter);
sudGameUserListAdapter = new SudGameUserListAdapter(new ArrayList<>());
ImgLoader.display(mContext, WordUtil.isNewZh() ? R.mipmap.icon_game_seat : R.mipmap.icon_game_seat_en, gameSeat);
sudGameUserListAdapter.setSudGameSmallCallBack(new SudGameUserListAdapter.SudGameSmallCallBack() {
@Override
public void unMute(String userID, int position) {
if (!TextUtils.equals(String.valueOf(IMLoginManager.get(mContext).getUserInfo().getId()), userID)) {
if (isSw) {
//靜音
SWAuManager.get().setMicAudio(Integer.parseInt(userID), false);
onSubscribeSuccess(userID, false, position);
} else {
gameMicManager.refreshStreams(userID, false, position);
}
} else {
ToastUtil.show(WordUtil.isNewZh() ? "無法對本人靜音" : "Unable to mute myself");
}
muteUser.remove(userID);
}
@Override
public void mute(String userID, int position) {
muteUser.add(userID);
if (!TextUtils.equals(String.valueOf(IMLoginManager.get(mContext).getUserInfo().getId()), userID)) {
if (isSw) {
//开启声音
SWAuManager.get().setMicAudio(Integer.parseInt(userID), true);
onSubscribeSuccess(userID, true, position);
} else {
gameMicManager.refreshStreams(userID, true, position);
}
} else {
ToastUtil.show(WordUtil.isNewZh() ? "無法對本人靜音" : "Unable to mute myself");
}
}
@Override
public void viewInformation(SudGameUserModel sudGameUserModel) {
LiveUserDialogFragment fragment = new LiveUserDialogFragment();
Bundle bundle = new Bundle();
bundle.putString(Constants.LIVE_UID, "uid");
bundle.putString(Constants.STREAM, "");
bundle.putString(Constants.TO_UID, sudGameUserModel.getId() + "");
fragment.setArguments(bundle);
fragment.show(((SudSwGameActivity) mContext).getSupportFragmentManager(), "LiveUserDialogFragment");
}
});
userList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
userList.setAdapter(sudGameUserListAdapter);
if (mCreateSudRoomModel != null) {
roomName.setText(mCreateSudRoomModel.getRoomName());
roomNumber.setText(mCreateSudRoomModel.getSudGameRoomId());
}
ViewClicksAntiShake.clicksAntiShake(findViewById(R.id.exit), new ViewClicksAntiShake.ViewClicksCallBack() {
@Override
public void onViewClicks() {
gameViewModel.onDestroy();
finish();
}
});
ViewClicksAntiShake.clicksAntiShake(findViewById(R.id.sud_history), new ViewClicksAntiShake.ViewClicksCallBack() {
@Override
public void onViewClicks() {
new XPopup.Builder(mContext).enableDrag(false).asCustom(new LiveSudGameHistoryPopup(mContext, customSidebarChildModels)).show();
}
});
ViewClicksAntiShake.clicksAntiShake(findViewById(R.id.game_seat), new ViewClicksAntiShake.ViewClicksCallBack() {
@Override
public void onViewClicks() {
if (imOff && gameMicManager != null) {
if (mProcessResultUtil.checkPermissions(new String[]{Manifest.permission.RECORD_AUDIO})) {
if (publishDefault) {
disable = true;
// 设置禁用麦克风采集
if (isSw) {
//下麥
SWAuManager.get().setMicAn(false);
onUnPublishStreamsSuccess();
} else {
RCRTCEngine.getInstance().getDefaultAudioStream().setMicrophoneDisable(disable);
// ImgLoader.display(mContext, R.mipmap.icon_game_close_wheat, gameCloseWheat);
gameMicManager.unPublishStreams();
}
} else {
if (sudGameUserListAdapter.isMicMax()) {
ToastUtil.show(WordUtil.isNewZh() ? "上麥人數最大7人" : "The maximum number of people on the microphone is 7");
} else {
//上麦
if (isSw) {
SWAuManager.get().setMicAn(true);
onPublishSuccess();
} else {
gameMicManager.publishDefaultAVStream();
}
}
}
} else {
mProcessResultUtil.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, new Runnable() {
@Override
public void run() {
}
});
}
}
}
});
ViewClicksAntiShake.clicksAntiShake(gameCloseWheat, new ViewClicksAntiShake.ViewClicksCallBack() {
@Override
public void onViewClicks() {
if (imOff && gameMicManager != null) {
gameCloseWheat.post(new Runnable() {
@Override
public void run() {
if (disable) {
disable = false;
// 设置禁用麦克风采集
if (isSw) {
SWAuManager.get().setMicAn(true);
} else {
RCRTCEngine.getInstance().getDefaultAudioStream().setMicrophoneDisable(disable);
}
ImgLoader.display(mContext, R.mipmap.icon_game_open_wheat, gameCloseWheat);
LiveNetManager.get(mContext).onMic(mLiveUid, new HttpCallback<HttpCallbackModel>() {
@Override
public void onSuccess(HttpCallbackModel data) {
}
@Override
public void onError(String error) {
}
});
ToastUtil.show(WordUtil.isNewZh() ? "麥克風已開啟" : "Microphone turned on");
} else {
disable = true;
// 设置禁用麦克风采集
if(isSw){
SWAuManager.get().setMicAn(false);
}else{
RCRTCEngine.getInstance().getDefaultAudioStream().setMicrophoneDisable(disable);
}
ImgLoader.display(mContext, R.mipmap.icon_game_close_wheat, gameCloseWheat);
LiveNetManager.get(mContext).offMic(mLiveUid, new HttpCallback<HttpCallbackModel>() {
@Override
public void onSuccess(HttpCallbackModel data) {
}
@Override
public void onError(String error) {
}
});
ToastUtil.show(WordUtil.isNewZh() ? "麥克風已關閉" : "Microphone turned off");
}
}
});
}
}
});
ViewClicksAntiShake.clicksAntiShake(findViewById(R.id.game_review_input), new ViewClicksAntiShake.ViewClicksCallBack() {
@Override
public void onViewClicks() {
new XPopup.Builder(mContext).enableDrag(false).asCustom(new SudGameInputPopupWindow(mContext, new SudGameInputPopupWindow.SudGameInputCallBack() {
@Override
public void sendMessage(String textMessage) {
gameMicManager.sendMessage(textMessage);
}
})).show();
}
});
gameViewModel.gameViewLiveData.observe(this, new Observer<View>() {
@Override
public void onChanged(View view) {
if (view == null) { // 在关闭游戏时把游戏View给移除
gameContainer.removeAllViews();
} else { // 把游戏View添加到容器内
gameContainer.addView(view, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
}
}
});
// 加载游戏参数定义可查看BaseGameViewModel.switchGame()方法注释
// 游戏配置
GameConfigModel gameConfigModel = gameViewModel.getGameConfigModel();
gameConfigModel.ui.ping.hide = true; // 配置不隐藏ping值
gameConfigModel.ui.level.hide = true; // 配置不隐藏ping值
gameConfigModel.ui.lobby_game_setting.hide = true; // 配置不隐藏ping值
gameConfigModel.ui.lobby_players.custom = true;
gameConfigModel.ui.join_btn.custom = true;
gameConfigModel.ui.game_settle_again_btn.custom = true;
gameConfigModel.ui.start_btn.custom = true;
// SudMGP平台64bit游戏ID
gameViewModel.switchGame((Activity) mContext, mLiveUid, mInteractionID);
// gameViewModel.sudFSTAPPDecorator.notifyAPPCommonSelfIn(true, -1, true, 1);
// gameViewModel.sudFSTAPPDecorator.notifyAPPCommonSelfCaptain(String.valueOf(IMLoginManager.get(mContext).getUserInfo().getId()));
// ViewClicksAntiShake.clicksAntiShake(gameTitle, new ViewClicksAntiShake.ViewClicksCallBack() {
// @Override
// public void onViewClicks() {
//
// }
// });
// 设置游戏安全操作区域
GameViewInfoModel.GameViewRectModel gameViewRectModel = new GameViewInfoModel.GameViewRectModel();
gameViewRectModel.left = 0;
gameViewRectModel.top = DpUtil.dp2px(155);
gameViewRectModel.right = 0;
gameViewRectModel.bottom = DpUtil.dp2px(155);
gameViewModel.gameViewRectModel = gameViewRectModel;
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onCheckRemainingBalanceEvent(CheckRemainingBalanceEvent event) {
switch (event.getSudMGPMGState()) {
case SudMGPMGState.MG_COMMON_SELF_CLICK_JOIN_BTN:
case SudMGPMGState.MG_COMMON_SELF_CLICK_GAME_SETTLE_AGAIN_BTN:
LiveNetManager.get(mContext).checkRemainingBalance(mCreateSudRoomModel.getSudGameRoomId(), new HttpCallback<CheckRemainingBalance>() {
@Override
public void onSuccess(CheckRemainingBalance data) {
if (TextUtils.equals(String.valueOf(data.getGoldenBeanRemainingBalance()), "1")) {
gameViewModel.sudFSTAPPDecorator.notifyAPPCommonSelfIn(true, event.getSeatIndex(), true, 1);
} else {
if (IMLoginManager.get(mContext).getLocaleLanguage() == Locale.SIMPLIFIED_CHINESE) {
ToastUtil.show("貨幣数量不足 ");
} else {
ToastUtil.show("Insufficient number of currency");
}
}
// ToastUtil.show(data.toString());
}
@Override
public void onError(String error) {
if (IMLoginManager.get(mContext).getLocaleLanguage() == Locale.SIMPLIFIED_CHINESE) {
ToastUtil.show("貨幣数量不足 ");
} else {
ToastUtil.show("Insufficient number of currency");
}
}
});
break;
case SudMGPMGState.MG_COMMON_GAME_SETTLE:
gameViewModel.sudFSTAPPDecorator.notifyAPPCommonSelfIn(false, event.getSeatIndex(), true, 1);
break;
case SudMGPMGState.MG_COMMON_SELF_CLICK_START_BTN:
LiveNetManager.get(mContext).gameStartCheckRemainingBalance(mCreateSudRoomModel.getSudGameId(), mCreateSudRoomModel.getSudGameRoomId(), new HttpCallback<CheckRemainingBalance>() {
@Override
public void onSuccess(CheckRemainingBalance data) {
if (data.getStatus() == 1) {
gameViewModel.sudFSTAPPDecorator.notifyAPPCommonSelfPlaying(true);
} else {
}
}
@Override
public void onError(String error) {
ToastUtil.show(error);
}
});
break;
case SudMGPMGState.MG_COMMON_GAME_STATE:
LiveNetManager.get(mContext).deductMoney(mCreateSudRoomModel.getSudGameRoomId());
break;
}
}
@Override
public void onJoinRoomSuccess(RCRTCRoom rcrtcRoom) {
LiveNetManager.get(mContext).getRoomMicData(mLiveUid, new HttpCallback<List<SudGameUserModel>>() {
@Override
public void onSuccess(List<SudGameUserModel> data) {
gameMicManager.refreshStreams(data);
sudGameUserListAdapter.refreshSudGameUserList(data, muteUser);
}
@Override
public void onError(String error) {
ToastUtil.show(error);
}
});
// 主动订阅远端用户发布的资源
// gameMicManager.subscribeAVStream();
}
@Override
public void onJoinRoomFailed(RTCErrorCode rtcErrorCode) {
ToastUtil.show("加入失败 " + rtcErrorCode.toString());
}
@Override
public void onPublishSuccess() {
runOnUiThread(new Runnable() {
@Override
public void run() {
ImgLoader.display(mContext, WordUtil.isNewZh() ? R.mipmap.icon_game_hang_up : R.mipmap.icon_game_hang_up_en, gameSeat);
publishDefault = true;
gameCloseWheat.setVisibility(View.VISIBLE);
disable = false;
// 设置禁用麦克风采集
RCRTCEngine.getInstance().getDefaultAudioStream().setMicrophoneDisable(disable);
ImgLoader.display(mContext, R.mipmap.icon_game_open_wheat, gameCloseWheat);
}
});
LiveNetManager.get(mContext).joinMic(mLiveUid, new HttpCallback<HttpCallbackModel>() {
@Override
public void onSuccess(HttpCallbackModel data) {
}
@Override
public void onError(String error) {
}
});
}
@Override
public void onPublishFailed() {
ToastUtil.show(WordUtil.isNewZh() ? "語音加入失敗" : "Voice joining failed");
}
@Override
public void onSubscribeSuccess(List<RCRTCInputStream> inputStreamList) {
// ToastUtil.show("订阅成功 ");
}
@Override
public void onSubscribeFailed() {
ToastUtil.show("订阅失败 ");
}
@Override
public void onSubscribeSuccess(String userID, boolean mute, int position) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mute) {
ToastUtil.show(WordUtil.isNewZh() ? "已靜音該用戶" : "The user has been muted");
} else {
ToastUtil.show(WordUtil.isNewZh() ? "已取消該用戶靜音" : "The user has been unmuted");
}
sudGameUserListAdapter.muteUser(userID, mute, position);
}
});
}
@Override
public void onSubscribeFailed(String userID) {
ToastUtil.show("订阅失败 ");
}
@Override
public void onUserJoined(RCRTCRemoteUser rcrtcRemoteUser) {
}
@Override
public void onUserLeft(RCRTCRemoteUser rcrtcRemoteUser) {
}
@Override
public void insertItem(SudGameChatImModel sudGameChatImModel) {
mLiveChatAdapter.insertItem(sudGameChatImModel);
}
@Override
public void refreshSudGameUserList(List<SudGameUserModel> personList) {
sudGameUserListAdapter.refreshSudGameUserList(personList, muteUser);
}
@Override
public void onUnPublishStreamsSuccess() {
runOnUiThread(new Runnable() {
@Override
public void run() {
ImgLoader.display(mContext, WordUtil.isNewZh() ? R.mipmap.icon_game_seat : R.mipmap.icon_game_seat_en, gameSeat);
publishDefault = false;
gameCloseWheat.setVisibility(View.INVISIBLE);
}
});
LiveNetManager.get(mContext).leaveMic(mLiveUid, new HttpCallback<HttpCallbackModel>() {
@Override
public void onSuccess(HttpCallbackModel data) {
}
@Override
public void onError(String error) {
}
});
}
@Override
public void onUnPublishStreamsFailed() {
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onSudGameSocketImEvent(SudGameSocketImEvent event) {
gameMicManager.processingMessage(event);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onSudGameUserModel(SudGameUserModel model) {
if (model.isNullUser()) {
if (!publishDefault) {
if (mProcessResultUtil.checkPermissions(new String[]{Manifest.permission.RECORD_AUDIO})) {
if (sudGameUserListAdapter.isMicMax()) {
ToastUtil.show(WordUtil.isNewZh() ? "上麥人數最大7人" : "The maximum number of people on the microphone is 7");
} else {
gameMicManager.publishDefaultAVStream();
}
} else {
mProcessResultUtil.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, new Runnable() {
@Override
public void run() {
}
});
}
} else {
ToastUtil.show(WordUtil.isNewZh() ? "已經是上麥狀態" : "It is already in the wheat state");
}
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onSudGameStatus(SubGameEvent event) {
if (event.getType() == 0) {
Log.i("游戏回调", "onGameStateChange: event :" + event.toString());
if (event.getModel().getCode() == 1001 || event.getModel().getCode() == 1002) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("result", 0);
gameViewModel.sudFSTAPPDecorator.notifyStateChange(SudMGPAPPState.APP_COMMON_GAME_CREATE_ORDER_RESULT, jsonObject.toString());
}
}
}
}

View File

@ -172,7 +172,7 @@ public class WebViewActivityMedal extends AbsActivity {
LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class); LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class);
new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() { new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() {
@Override @Override
public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk) { public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk,boolean isSw) {
if (liveBean == null) { if (liveBean == null) {
return; return;
} }
@ -180,7 +180,7 @@ public class WebViewActivityMedal extends AbsActivity {
MicStatusManager.getInstance().showDownMicDialog(mContext); MicStatusManager.getInstance().showDownMicDialog(mContext);
return; return;
} }
RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk)); RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk),isSw);
finish(); finish();
} }

View File

@ -409,7 +409,7 @@ public class ZhuangBanActivity extends AbsActivity {
LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class); LiveBean liveBean = JSON.parseObject(info[0], LiveBean.class);
new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() { new LiveRoomCheckLivePresenter(mContext, liveBean.getUid(), liveBean.getStream(), new LiveRoomCheckLivePresenter.NewActionListener() {
@Override @Override
public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk) { public void onLiveRoomChanged(String liveUid, String stream, int liveType, String liveTypeVal, String liveSdk,boolean isSw) {
if (liveBean == null) { if (liveBean == null) {
return; return;
} }
@ -426,7 +426,7 @@ public class ZhuangBanActivity extends AbsActivity {
EventBus.getDefault().post(new LiveRoomChangeEvent(liveBean, liveType, Integer.parseInt(liveTypeVal))); EventBus.getDefault().post(new LiveRoomChangeEvent(liveBean, liveType, Integer.parseInt(liveTypeVal)));
finish(); finish();
} else { } else {
RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk)); RouteUtil.forwardLiveAudienceActivity(liveBean, liveType, Integer.parseInt(liveTypeVal), Integer.parseInt(liveSdk),isSw);
} }
finish(); finish();
} }

View File

@ -21,7 +21,7 @@ import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.Constants; import com.yunbao.common.Constants;
import com.yunbao.common.adapter.RefreshAdapter; import com.yunbao.common.adapter.RefreshAdapter;
import com.yunbao.common.bean.BaseModel; import com.yunbao.common.bean.BaseModel;
import com.yunbao.common.bean.LevelBean; import com.yunbao.common.bean.MsgSwitchFollowlModel;
import com.yunbao.common.bean.UserBean; import com.yunbao.common.bean.UserBean;
import com.yunbao.common.custom.CommonRefreshView; import com.yunbao.common.custom.CommonRefreshView;
import com.yunbao.common.dialog.AbsDialogFragment; import com.yunbao.common.dialog.AbsDialogFragment;
@ -35,9 +35,11 @@ import com.yunbao.common.utils.CommonIconUtil;
import com.yunbao.common.utils.SVGAViewUtils; import com.yunbao.common.utils.SVGAViewUtils;
import com.yunbao.common.utils.ToastUtil; import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.utils.WordUtil; import com.yunbao.common.utils.WordUtil;
import com.yunbao.common.views.weight.ViewClicksAntiShake;
import com.yunbao.live.R; import com.yunbao.live.R;
import com.yunbao.live.activity.LiveActivity; import com.yunbao.live.activity.LiveActivity;
import com.yunbao.live.socket.SocketSendBean; import com.yunbao.live.socket.SocketSendBean;
import com.yunbao.live.socket.SocketSwClient;
import com.yunbao.live.utils.LiveTextRender; import com.yunbao.live.utils.LiveTextRender;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -119,15 +121,13 @@ public class AnchorUserMicInfoAdapter extends RefreshAdapter<UserBean> {
gift_svga = (SVGAImageView) itemView.findViewById(R.id.gift_svga); gift_svga = (SVGAImageView) itemView.findViewById(R.id.gift_svga);
mBtn = itemView.findViewById(R.id.mic_btn); mBtn = itemView.findViewById(R.id.mic_btn);
mClose = itemView.findViewById(R.id.mic_exit); mClose = itemView.findViewById(R.id.mic_exit);
mBtn.setOnClickListener(v -> { ViewClicksAntiShake.clicksAntiShake(mBtn, new ViewClicksAntiShake.ViewClicksCallBack() {
@Override
public void onViewClicks() {
if (MicedUserManager.get().getMicUserList().size() < 3) { if (MicedUserManager.get().getMicUserList().size() < 3) {
if (v.getTag() != null) { if (mBtn.getTag() != null) {
UserBean tag = (UserBean) v.getTag(); UserBean tag = (UserBean) mBtn.getTag();
if (tag.getTypeMic() == TYPE_MIC_REQUEST) { if (tag.getTypeMic() == TYPE_MIC_REQUEST) {
SocketSendBean bean = createSocketSendBean().param("targetId", tag.getId());
applyMic(tag, 1, bean);
ToastUtil.show(mContext.getString(R.string.live_mic_invite));
} else if (tag.getTypeMic() == TYPE_MIC_INVITE) {
applyMic(tag, 4, createSocketSendBean()); applyMic(tag, 4, createSocketSendBean());
ToastUtil.show(mContext.getString(R.string.live_mic_request)); ToastUtil.show(mContext.getString(R.string.live_mic_request));
for (int i = 0; i < mList.size(); i++) { for (int i = 0; i < mList.size(); i++) {
@ -136,14 +136,19 @@ public class AnchorUserMicInfoAdapter extends RefreshAdapter<UserBean> {
notifyItemChanged(i); notifyItemChanged(i);
} }
} }
} else if (tag.getTypeMic() == TYPE_MIC_INVITE) {
SocketSendBean bean = createSocketSendBean().param("targetId", tag.getId());
applyMic(tag, 1, bean);
ToastUtil.show(mContext.getString(R.string.live_mic_invite));
} }
} }
}else { }else {
ToastUtil.show(mContext.getString(R.string.live_mic_max)); ToastUtil.show(mContext.getString(R.string.live_mic_max));
} }
}
}); });
mClose.setOnClickListener(v -> { mClose.setOnClickListener(v -> {
if (v.getTag() != null) { if (v.getTag() != null) {
API.get().createPDLiveApi(false) API.get().createPDLiveApi(false)
@ -167,14 +172,14 @@ public class AnchorUserMicInfoAdapter extends RefreshAdapter<UserBean> {
return new SocketSendBean() return new SocketSendBean()
.param("_method_", Constants.LIAN_MAI) .param("_method_", Constants.LIAN_MAI)
.param("uname", CommonAppConfig.getInstance().getUserBean().getUserNiceName()) .param("uname", CommonAppConfig.getInstance().getUserBean().getUserNiceName())
.param("avatar", CommonAppConfig.getInstance().getUserBean().getAvatar()) .param("uhead", CommonAppConfig.getInstance().getUserBean().getAvatar())
.param("uid", CommonAppConfig.getInstance().getUid()); .param("uid", CommonAppConfig.getInstance().getUid());
} }
/** /**
* 发送IM消息 * 发送IM消息
* *
* @param action 4为同意请求1为邀请其余见 {@link com.yunbao.live.socket.SocketRyClient} Constants.LIAN_MAI解析 * @param action 4为同意请求1为邀请其余见 {@link SocketSwClient} Constants.LIAN_MAI解析
*/ */
void applyMic(UserBean bean, int action, SocketSendBean msg) { void applyMic(UserBean bean, int action, SocketSendBean msg) {
msg.param("action", action); msg.param("action", action);

View File

@ -22,6 +22,7 @@ import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.utils.WordUtil; import com.yunbao.common.utils.WordUtil;
import com.yunbao.live.R; import com.yunbao.live.R;
import com.yunbao.live.activity.LiveRyAnchorActivity; import com.yunbao.live.activity.LiveRyAnchorActivity;
import com.yunbao.live.activity.LiveSwAnchorActivity;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -35,6 +36,7 @@ public class FreePkRecyclerAdapter extends RefreshAdapter<RandomPkUserBean> {
private static final int ITEM = 2; private static final int ITEM = 2;
private int freePkNum;//PK次数 private int freePkNum;//PK次数
private int mDrPkNum = -1;//多人PK剩余次数-1则认为是单人PK private int mDrPkNum = -1;//多人PK剩余次数-1则认为是单人PK
private String liveUid;
public void setFreePkNum(int freePkNum) { public void setFreePkNum(int freePkNum) {
this.freePkNum = freePkNum; this.freePkNum = freePkNum;
@ -48,6 +50,10 @@ public class FreePkRecyclerAdapter extends RefreshAdapter<RandomPkUserBean> {
this.mDrPkNum = mDrPkNum; this.mDrPkNum = mDrPkNum;
} }
public void setLiveUid(String liveUid) {
this.liveUid = liveUid;
}
@NonNull @NonNull
@Override @Override
public HeadViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public HeadViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@ -126,10 +132,9 @@ public class FreePkRecyclerAdapter extends RefreshAdapter<RandomPkUserBean> {
} }
if (freePkNum == 0 && mDrPkNum == -1) { if (freePkNum == 0 && mDrPkNum == -1) {
ToastUtil.show(mContext.getString(R.string.free_pk_num_null)); ToastUtil.show(mContext.getString(R.string.free_pk_num_null));
// return; return;
} }
LiveHttpUtil.getMicList(liveUid, 0, new com.yunbao.common.http.HttpCallback() {
LiveHttpUtil.getMicList(LiveRyAnchorActivity.mLiveUid, 0, new com.yunbao.common.http.HttpCallback() {
@Override @Override
public void onSuccess(int code, String msg, String[] info) { public void onSuccess(int code, String msg, String[] info) {
System.out.println("code = " + code + ", msg = " + msg + ", info = " + Arrays.deepToString(info)); System.out.println("code = " + code + ", msg = " + msg + ", info = " + Arrays.deepToString(info));
@ -142,9 +147,14 @@ public class FreePkRecyclerAdapter extends RefreshAdapter<RandomPkUserBean> {
ToastUtil.show("invite " + bean.getUserNiceName() + " successful"); ToastUtil.show("invite " + bean.getUserNiceName() + " successful");
} }
mOnItemClickListener.onItemClick(bean, -1); mOnItemClickListener.onItemClick(bean, -1);
if(mContext instanceof LiveSwAnchorActivity){
((LiveSwAnchorActivity) mContext).linkMicAnchorApply(bean.getId(), bean.getId(),
false);
}else{
((LiveRyAnchorActivity) mContext).linkMicAnchorApply(bean.getId(), bean.getId(), ((LiveRyAnchorActivity) mContext).linkMicAnchorApply(bean.getId(), bean.getId(),
((LiveRyAnchorActivity) mContext).buildLinkMicJSON().toString() ((LiveRyAnchorActivity) mContext).buildLinkMicJSON().toString()
); );
}
return; return;
} }
if (mDrPkNum <= 0) { if (mDrPkNum <= 0) {
@ -157,7 +167,11 @@ public class FreePkRecyclerAdapter extends RefreshAdapter<RandomPkUserBean> {
} }
yaoqing.put(bean.getId(), bean.getId()); yaoqing.put(bean.getId(), bean.getId());
if (yaoqing.size() < 5) { if (yaoqing.size() < 5) {
if(mContext instanceof LiveSwAnchorActivity){
((LiveSwAnchorActivity) mContext).linkDrMicAnchorApply(bean.getId(), bean.getId());
}else{
((LiveRyAnchorActivity) mContext).linkDrMicAnchorApply(bean.getId(), bean.getId()); ((LiveRyAnchorActivity) mContext).linkDrMicAnchorApply(bean.getId(), bean.getId());
}
} else { } else {
ToastUtil.show(WordUtil.isNewZh() ? "多人PK最大參與人數為4人" : "The maximum number of participants in a multiplayer PK is 4 people"); ToastUtil.show(WordUtil.isNewZh() ? "多人PK最大參與人數為4人" : "The maximum number of participants in a multiplayer PK is 4 people");
} }
@ -222,13 +236,13 @@ public class FreePkRecyclerAdapter extends RefreshAdapter<RandomPkUserBean> {
mId.setText(bean.getId()); mId.setText(bean.getId());
if (bean.isPk()) { if (bean.isPk()) {
mStatus.setText("PK中"); mStatus.setText("PK中");
ImgLoader.display(mContext, R.mipmap.ic_random_pk_pk, mPkStatus); ImgLoader.display(mContext, R.mipmap.ic_random_pk_pk_unselect, mPkStatus);
if (!WordUtil.isNewZh()) { if (!WordUtil.isNewZh()) {
mStatus.setText("PK"); mStatus.setText("PK");
} }
} else { } else {
ImgLoader.display(mContext, R.mipmap.ic_random_pk_pk, mPkStatus);
mStatus.setText("空闲"); mStatus.setText("空闲");
ImgLoader.display(mContext, R.mipmap.ic_random_pk_pk_unselect, mPkStatus);
if (!WordUtil.isNewZh()) { if (!WordUtil.isNewZh()) {
mStatus.setText("free"); mStatus.setText("free");
} }

View File

@ -210,7 +210,8 @@ public class LiveChatAdapter extends RecyclerView.Adapter {
class Vh extends RecyclerView.ViewHolder { class Vh extends RecyclerView.ViewHolder {
LinearLayout mBg, view_follow, view_action_game, view_zg, xydComplete; LinearLayout mBg, view_follow, view_action_game, view_zg, xydComplete;
TextView mTextView, tv_chat_active_into, tv_chat_avtive_name, tv_zg_anchorname, textTxt2, automatic_chat; TextView tv_chat_active_into, tv_chat_avtive_name, tv_zg_anchorname, textTxt2, automatic_chat;
TextView mTextView;
RoundedImageView avatar; RoundedImageView avatar;
View v_chat_active_close; View v_chat_active_close;
RecyclerView rv_chat_active; RecyclerView rv_chat_active;

View File

@ -13,7 +13,7 @@ import androidx.recyclerview.widget.RecyclerView;
import com.yunbao.common.Constants; import com.yunbao.common.Constants;
import com.yunbao.common.interfaces.OnItemClickListener; import com.yunbao.common.interfaces.OnItemClickListener;
import com.yunbao.live.R; import com.yunbao.live.R;
import com.yunbao.live.activity.LiveRyAnchorActivity; import com.yunbao.live.activity.LiveSwAnchorActivity;
import com.yunbao.live.bean.LiveFunctionBean; import com.yunbao.live.bean.LiveFunctionBean;
import java.util.ArrayList; import java.util.ArrayList;
@ -38,11 +38,10 @@ public class LiveFunctionAdapter extends RecyclerView.Adapter<LiveFunctionAdapte
mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_CAMERA, R.mipmap.icon_live_func_camera, R.string.live_camera)); mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_CAMERA, R.mipmap.icon_live_func_camera, R.string.live_camera));
mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_LINK_MIC, R.mipmap.icon_danrenpk, R.string.live_link_pk)); mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_LINK_MIC, R.mipmap.icon_danrenpk, R.string.live_link_pk));
mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_DR, R.mipmap.icon_duorenpk, R.string.live_dr)); mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_DR, R.mipmap.icon_duorenpk, R.string.live_dr));
if (!(context instanceof LiveRyAnchorActivity)) { if (!(context instanceof LiveSwAnchorActivity)) {
mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_MIC, R.mipmap.icon_microphone, R.string.live_mic)); mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_MIC, R.mipmap.icon_microphone, R.string.live_mic));
} }
if (leave == 0) { if (leave == 0) {
mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_ZSLK, R.mipmap.icon_leave, R.string.live_zslk)); mList.add(new LiveFunctionBean(Constants.LIVE_FUNC_ZSLK, R.mipmap.icon_leave, R.string.live_zslk));
} else { } else {

View File

@ -208,6 +208,10 @@ public class LiveChatBean {
return this; return this;
} }
public String getMedal_new_en() {
return medal_new_en;
}
public String getHot_card() { public String getHot_card() {
return hot_card; return hot_card;
} }

Some files were not shown because too many files have changed in this diff Show More