Compare commits

..

2 Commits

Author SHA1 Message Date
811e1bf875 tinker_base-3.7.3-splash 2020-02-19 17:17:59 +08:00
5c929ba308 更换引导图 2020-02-19 16:46:08 +08:00
4775 changed files with 93521 additions and 215409 deletions

1
.gitignore vendored
View File

@ -7,6 +7,5 @@ local.properties
captures/
build/
release-app/
test-app/
scripts/apk-channel/
app/src/test/java/com/gh/gamecenter

View File

@ -1,44 +0,0 @@
stages:
- analysis
- sendmail
## 代码检查
sonarqube_analysis:
tags:
- offline-test
stage: analysis
image: sonarsource/sonar-scanner-cli:latest
dependencies: [] #禁止传递来的artifact
script:
## 获取项目的一级组和二级组和项目名作为projectKey例如projectKey=platform-backend-eci-monitor
- group=`echo $CI_PROJECT_PATH | sed 's#/#-#g'`
- sonar-scanner
-Dsonar.host.url=http://sonarqube-server.sonarqube:9000/
-Dsonar.login=be43de7264ce4c4766eb0c020373c3e74e6df257
-Dsonar.jacoco.reportPaths=target/jacoco.exec
-Dsonar.projectKey=$group
-Dsonar.projectName=$CI_PROJECT_PATH
-Dsonar.sourceEncoding=UTF-8
-Dsonar.exclusions=**/vendor/**,**/errcode/**
-Dsonar.gitlab.project_id=$CI_PROJECT_ID
-Dsonar.gitlab.commit_sha=$CI_COMMIT_SHA
-Dsonar.gitlab.ref_name=$CI_COMMIT_REF_NAME
-Dsonar.gitlab.ci_merge_request_iid=$CI_MERGE_REQUEST_IID
-Dsonar.gitlab.merge_request_discussion=true
-Dsonar.java.binaries=. # 如果不使用Maven或Gradle进行分析则必须手动提供测试二进制文件
only:
- dev
## 发送简易检测结果报告
send_sonar_report:
tags:
- offline-test
stage: sendmail
image: hub.shanqu.cc/library/docker:latest
dependencies: [] #禁止传递来的artifact
script:
- group=`echo $CI_PROJECT_PATH | sed 's#/#-#g'`
- docker login -u "${HARBOR_REGISTRY_USERNAME}" -p "${HARBOR_REGISTRY_PASSWORD}" "${HARBOR_REGISTRY}"
- docker run -e PROJECTKEY=$group -e EMAIL=$GITLAB_USER_EMAIL --name send-email --rm hub.shanqu.cc/platform/send-sonar-report:latest
only:
- dev

5
.gitmodules vendored
View File

@ -1,7 +1,4 @@
[submodule "libraries/LGLibrary"]
path = libraries/LGLibrary
url = git@git.shanqu.cc:android/common-library.git
url = git@gitlab.ghzs.com:android/common-library.git
branch = master
[submodule "assistant_flutter"]
path = assistant_flutter
url = git@git.shanqu.cc:halo/android/flutter-module.git

120
README.md
View File

@ -1,65 +1,69 @@
# 光环助手Android客户端
### 概述
光环助手Android客户端目前使用 Kotlin 作为主要开发语言,以 MVVM 作为参考架构模式进行开发
### 约束
为编写易读易维护且较健壮的代码,可参考以下约束
1. 尽量将逻辑代码放置于 ViewModel 中View 中只执行 UI 操作
2. 尽量使 View 在被销毁之后仍能恢复状态,处理方式可参考 [保存界面状态](https://developer.android.com/topic/libraries/architecture/saving-states)
3. 尽量参考原有文件结构及命名规范,即以 大模块 - 小模块 的形式生成包关系
4. 遵循最小改动原则,在提交代码前务必先检查变动的代码,尽量以可控的变动规模来构成一个 commit ,以便日后追踪问题
5. 代码规范可参考 [AOSP Java 风格](https://source.android.com/setup/contribute/code-style)
6. 尽量使用 Kotlin 来写新文件
7. 尽量不要使用 DataBinding
8. Commit 前请确保不带入非项目必须文件,可手动修改 [.gitignore](https://stackoverflow.com/questions/8527597/how-do-i-ignore-files-in-a-directory-in-git) 文件忽略
9. 优先使用 ViewBinding 获取 View 对象
10. No AsyncTask!
### 公用部分
本项目使用 LiveData 实现了一个简单通用的基础列表分页功能,具体可见 `ListFragment`, `ListViewModel` 等类,理想情况下只需少量代码即可新建一个简单分页列表
### 首次拉取项目代码
`git clone -b dev git@git.shanqu.cc:halo/android/assistant-android.git --recursive`
### git 版本管理
本项目使用简化版的 git flow 来管理分支,细节请看 [光环安卓简单 git 规范](https://git.ghzs.com/halo/android/assistant-android/-/wikis/%E5%85%89%E7%8E%AF%E5%AE%89%E5%8D%93%E7%AE%80%E5%8D%95-git-%E8%A7%84%E8%8C%83)
### API 环境配置
本项目使用 Build Variants 来切换 API 环境
* internal 为测试环境
* publish 为正式环境
### 图片资源配置
* 新增图片资源时,默认只添加最高规格的 xxxhdpi 文件
* 新增图片资源时,需要将其转换为 .webp 格式 (包括含透明图层的图片默认质量为90%) (转换后体积变大的文件除外)
### 第三方appkey等配置
* 修改 `gradle.properties` 文件将各种key填入其中实现统一管理
* 通过 gradle 文件内的 resValue/buildConfigField/manifestPlaceHolder 方式实现编译期间修改,具体情况请参考 ``./build.gradle`` 和 ``./app/build.gradle`` 配置
### 混淆配置
* 本项目使用了微信的 [AndResGuard](https://github.com/shwenzhang/AndResGuard) 作为资源混淆压缩方案,新增需要使用 `getIdentifier` 获取的资源文件时需要添加至白名单
* 本项目默认使用 R8 作为混淆工具,往 proguard-rules.txt 添加 proguard 新配置项时请检查可用性(如语法等)
### APK打包配置
> 打内部测试包:`./scripts/test_build.sh`
> 打邮件测试包:`./scripts/jenkins_build.sh`
* 使用[ApkChannelPackage](https://github.com/ltlovezh/ApkChannelPackage)的方案
* 打包命令,视情况使用:
> 打包Tinker基准包`./scripts/tinker_release_base.sh`
> 以Tinker基准包打渠道包`./scripts/tinker_release_channel.sh`
> 以Tinker基准包打补丁包`./scripts/tinker_release_patch.sh`
### 混淆配置
* 配置文件Android默认配置+proguard-rules.txt等
* 参考libraries下每个项目独立的配置文件`proguard-project.txt`
### apk大小优化
* 限制resConfig资源集
* 开启ShrinkResources
* 开启混淆使用minifyEnabled(仅在release开启
* pngquant对png压缩、png/jpg->webp(未尝试)
### 第三方appkey等配置
* 修改`gradle.properties`文件将各种key填入其中实现统一管理
* 通过gradle文件内的resValue/buildConfigField/manifestPlaceHolder方式实现编译期间修改具体情况请参考``./build.gradle``和``./app/build.gradle``配置
### 拉取代码步骤
1. 拉取主项目代码: `git clone -b dev git@gitlab.ghzhushou.com:halo/assistant-android.git`
2. 初始化公用类库: `bash ./scripts/submodules_init.sh`
### submodule管理方式(只拉取master)
* 提交代码需要cd到submodule文件夹去做修改
* 更新远端代码,`bash ./scripts/submodules_update.sh`
### TODO
* 把原有 EventBus 的消息 Type 统一一个文件内
* 将实现细节从 View(Fragment、Activity) 剥离并以 MVVM 结构改造
* 重构 MainActivity
* GSON 序列化用统一一个, GsonUtil fromJson
* CleanApkAdapter 转化字符串size工具函数 比如SpeedUtils
* getString 解决 字符串hardcode问题
* ~~Adapter 里面clicklistener 用接口传参将点击操作委托给controller~~
* ~~Adapter ViewHolder的功能部分重写到ViewHolder类本身~~
* ~~activity 统一入口未完成(外部入口相关)去除多余activity使用统一toolbar~~
* ~~release / debug compile不同的类库不需要再做什么开关~~
* ~~Toolbar分离有图形按钮/没有图形按钮~~
### TODO Since 3.1
- 解决 Utils 工具类引发的内存泄漏问题
- 把原有 EventBus 的消息 Type 统一到一个文件内
- 将实现细节从 View(Fragment、Activity) 剥离并以 MVVM 结构改造
- ~~将 ListViewModel 所对应的 ListRepository 合并到 ListViewModel 中~~
- 依照光环助手界面功能以大模块 - 小模块的方式去修改包结构,包内文件建议以包名摘要作为前缀
- ~~使用 RxJava 的 Debounce 和 Map 操作优化搜索触发机制 参考资料:[1](https://proandroiddev.com/building-an-autocompleting-edittext-using-rxjava-f69c5c3f5a40),[2](https://medium.com/@kurtisnusbaum/rxandroid-basics-part-2-6e877af352)~~
- ~~把 ListViewModel 的数据结构类型转换方式换为抽象方法,让继承的类实现,避免出现无响应的问题~~
- ~~rxjava2 如果接口返回为空 会发生异常:java.lang.NullPointerException: Null is not a valid element (答案编辑) 解决方法->com.gh.gamecenter.retrofit.Response~~
- constraintLayout 1.1.2 导致布局出现异常(问题编辑标签选择弹窗)
- 搞清楚 GameManager 的用途,看能不能去掉
- 重构一下 MainActivity

View File

@ -1,17 +1,21 @@
// This comment exists for a reason, do not delete
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android' // kotlin
apply plugin: 'kotlin-parcelize'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'AndResGuard'
import groovy.xml.XmlUtil
// apkChannelPackage
apply plugin: 'channel'
apply from: 'tinker-support.gradle'
android {
buildFeatures {
viewBinding true
dataBinding true
androidExtensions {
experimental = true
}
dataBinding {
enabled = true
}
compileOptions {
@ -19,32 +23,13 @@ android {
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
dexOptions {
// jumboMode = true
javaMaxHeapSize "4g"
preDexLibraries true
maxProcessCount 8
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
kapt {
useBuildCache = true
javacOptions {
// 增加注解处理器的最大错误次数,默认为 100
option("-Xmaxerrs", 500)
}
}
defaultConfig {
vectorDrawables.useSupportLibrary = true
multiDexEnabled true
javaCompileOptions {
annotationProcessorOptions {
@ -53,17 +38,9 @@ android {
}
ndk {
// 如果不添加 `arm64` 调用系统的 PackageManager 的方法读取安装包信息的时候会出现 native 层闪退,草
// 添加了 `arm64` 以后部分 5.0 的设备会报用错 so 的问题,
// couldn't find DSO to load: libimagepipeline.so caused by: dlopen failed: "/data/data/com.gh.gamecenter/lib-main/libimagepipeline.so" is 64-bit instead of 32-bit result: 0
// 以 OPPO R7PLUS 为例,明明设备是骁龙 615ARMv8-64 bit 的设备却不支持 arm64 的 abi限制了只使用 java 后还是报错,只有 5.05.1 设备无法复现 : (
// 惊了
abiFilters "armeabi-v7a", "arm64-v8a", "x86"
abiFilters "armeabi-v7a", "x86"
}
renderscriptTargetApi 18
renderscriptSupportModeEnabled true
// 由于app只针对中文用户所以仅保留zh资源其他删掉
resConfigs "zh"
@ -78,21 +55,18 @@ android {
/**
* All third-party appid/appkey
*/
buildConfigField "String", "API_HOST", "\"${API_HOST}\""
buildConfigField "String", "NEW_API_HOST", "\"${NEW_API_HOST}\""
buildConfigField "String", "WECHAT_APPID", "\"${WECHAT_APPID}\""
buildConfigField "String", "WECHAT_SECRET", "\"${WECHAT_SECRET}\""
buildConfigField "String", "TENCENT_APPID", "\"${TENCENT_APPID}\""
buildConfigField "String", "WEIBO_APPKEY", "\"${WEIBO_APPKEY}\""
buildConfigField "String", "QUICK_LOGIN_APPID", "\"${QUICK_LOGIN_APPID}\""
buildConfigField "String", "QUICK_LOGIN_APPKEY", "\"${QUICK_LOGIN_APPKEY}\""
buildConfigField "String", "MTA_APPKEY", "\"${MTA_APPKEY}\""
buildConfigField "String", "TD_APPID", "\"${TD_APPID}\""
/**
* Build Time 供区分 jenkins 打包时间用
* IS_NIGHT_MODE_ON 供区分夜间模式功能是否启用
*/
buildConfigField "long", "BUILD_TIME", "0"
buildConfigField "boolean", "IS_NIGHT_MODE_ON", "true"
}
// gradle 2.2以上默认同时启用v1和v2优先用于Android N
@ -115,7 +89,7 @@ android {
signingConfig signingConfigs.debug
buildConfigField "String", "EXPOSURE_REPO", "\"test\""
buildConfigField "String", "EXPOSURE_VERSION", "\"E4\""
buildConfigField "String", "EXPOSURE_VERSION", "\"E3\""
multiDexKeepProguard file("tinker_multidexkeep.pro")
}
@ -127,72 +101,75 @@ android {
signingConfig signingConfigs.release
buildConfigField "String", "EXPOSURE_REPO", "\"exposure\""
buildConfigField "String", "EXPOSURE_VERSION", "\"E4\""
buildConfigField "String", "EXPOSURE_VERSION", "\"E3\""
multiDexKeepProguard file("tinker_multidexkeep.pro")
}
}
// Ignore useless variant
variantFilter { variant ->
def names = variant.flavors*.name
def isDebugType = variant.buildType.name == "debug"
if ((names.contains("tea")) && isDebugType) {
setIgnore(true)
}
}
flavorDimensions("env")
sourceSets {
publish {
java.srcDirs = ['src/main/java']
}
internal {
java.srcDirs = ['src/main/java']
}
tea {
java.srcDirs = ['src/main/java', 'src/tea/java']
}
}
flavorDimensions "nonsense"
/**
* 多渠道打包,渠道请参考"channel.txt"文件所有渠道值均通过java code设置
*/
productFlavors {
// publish release host
publish {
dimension "nonsense"
buildConfigField "String", "API_HOST", "\"${API_HOST}\""
buildConfigField "String", "COMMENT_HOST", "\"${COMMENT_HOST}\""
buildConfigField "String", "DATA_HOST", "\"${DATA_HOST}\""
buildConfigField "String", "UMENG_APPKEY", "\"${UMENG_APPKEY}\""
buildConfigField "String", "UMENG_MESSAGE_SECRET", "\"${UMENG_MESSAGE_SECRET}\""
buildConfigField "String", "MIPUSH_APPID", "\"${MIPUSH_APPID}\""
buildConfigField "String", "MIPUSH_APPKEY", "\"${MIPUSH_APPKEY}\""
buildConfigField "String", "MEIZUPUSH_APPID", "\"${MEIZUPUSH_APPID}\""
buildConfigField "String", "MEIZUPUSH_APPKEY", "\"${MEIZUPUSH_APPKEY}\""
buildConfigField "String", "BUGLY_APPID", "\"${BUGLY_APPID}\""
}
// internal test dev host
internal {
dimension "env"
dimension "nonsense"
versionNameSuffix "-debug"
buildConfigField "String", "DEV_API_HOST", "\"${DEV_API_HOST}\""
buildConfigField "String", "NEW_DEV_API_HOST", "\"${NEW_DEV_API_HOST}\""
}
buildConfigField "String", "API_HOST", "\"${DEV_API_HOST}\""
buildConfigField "String", "COMMENT_HOST", "\"${DEV_COMMENT_HOST}\""
buildConfigField "String", "DATA_HOST", "\"${DEV_DATA_HOST}\""
// publish release host˛
publish {
dimension "env"
buildConfigField "String", "UMENG_APPKEY", "\"${DEBUG_UMENG_APPKEY}\""
buildConfigField "String", "UMENG_MESSAGE_SECRET", "\"${DEBUG_UMENG_MESSAGE_SECRET}\""
buildConfigField "String", "MIPUSH_APPID", "\"${DEBUG_MIPUSH_APPID}\""
buildConfigField "String", "MIPUSH_APPKEY", "\"${DEBUG_MIPUSH_APPKEY}\""
buildConfigField "String", "MEIZUPUSH_APPID", "\"${DEBUG_MEIZUPUSH_APPID}\""
buildConfigField "String", "MEIZUPUSH_APPKEY", "\"${DEBUG_MEIZUPUSH_APPKEY}\""
buildConfigField "String", "DEV_API_HOST", "\"${API_HOST}\""
buildConfigField "String", "NEW_DEV_API_HOST", "\"${NEW_API_HOST}\""
}
tea {
dimension "env"
buildConfigField "String", "DEV_API_HOST", "\"${API_HOST}\""
buildConfigField "String", "NEW_DEV_API_HOST", "\"${NEW_API_HOST}\""
manifestPlaceholders.put("APPLOG_SCHEME", "rangersapplog.byAx6uYt".toLowerCase())
buildConfigField "String", "BUGLY_APPID", "\"${DEBUG_BUGLY_APPID}\""
}
}
}
lintOptions {
// For flutter release build, see https://github.com/flutter/flutter/issues/58247
checkReleaseBuilds false
}
// apkChannelPackage
channel {
//多渠道包的输出目录默认为new File(project.buildDir,"channel")
baseOutputDir = new File(project.buildDir, "channel")
//多渠道包的命名规则,默认为:${appName}-${versionName}-${versionCode}-${flavorName}-${buildType}
apkNameFormat = '${appName}-${versionName}-${versionCode}-${flavorName}-${buildType}'
}
rebuildChannel {
// baseDebugApk = 已有Debug APK
// baseReleaseApk = 已有Release APK
// //默认为new File(project.buildDir, "rebuildChannel/debug")
// debugOutputDir = Debug渠道包输出目录
// //默认为new File(project.buildDir, "rebuildChannel/release")
// releaseOutputDir = Release渠道包输出目录
}
repositories {
flatDir {
dirs 'libs', 'libs/aars'
dirs 'libs/aars'
}
}
@ -203,39 +180,34 @@ dependencies {
testImplementation 'junit:junit:4.12'
debugImplementation "com.squareup.leakcanary:leakcanary-android:${leakcanary}"
debugImplementation "com.facebook.stetho:stetho:${stetho}"
debugImplementation "com.facebook.stetho:stetho-okhttp3:${stetho}"
debugImplementation "com.squareup.okhttp3:logging-interceptor:${okHttp}"
// debugImplementation "com.gu.android:toolargetool:${toolargetool}" // 需要使用调试时才启用
debugImplementation "com.github.nichbar:WhatTheStack:${whatTheStack}"
debugImplementation "io.github.didi.dokit:dokitx:${dokit}"
implementation "androidx.core:core-ktx:${core}"
implementation "androidx.fragment:fragment-ktx:${fragment}"
implementation "androidx.core:core:${core}"
implementation "androidx.fragment:fragment:${fragment}"
implementation "androidx.multidex:multidex:${multiDex}"
implementation "androidx.appcompat:appcompat:${appCompat}"
implementation "androidx.cardview:cardview:${cardView}"
implementation "androidx.annotation:annotation:${annotation}"
implementation "androidx.constraintlayout:constraintlayout:${constraintLayout}"
implementation "androidx.recyclerview:recyclerview:${recyclerView}"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifeCycle"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifeCycle"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifeCycle"
implementation "androidx.lifecycle:lifecycle-extensions:$lifeCycleExtensions"
implementation "androidx.lifecycle:lifecycle-runtime:${lifeCycle}"
implementation "androidx.lifecycle:lifecycle-extensions:${lifeCycle}"
kapt "androidx.lifecycle:lifecycle-compiler:${lifeCycle}"
implementation "androidx.room:room-runtime:${room}"
implementation "androidx.room:room-rxjava2:${room}"
implementation "androidx.core:core-ktx:${ktx}"
implementation "androidx.viewpager2:viewpager2:${viewpager2}"
implementation "androidx.webkit:webkit:${webkit}"
kapt "androidx.room:room-compiler:${room}"
kapt "androidx.databinding:databinding-compiler:${databinding}"
implementation "com.google.android.material:material:${material}"
implementation "com.kyleduo.switchbutton:library:${switchButton}"
implementation "com.facebook.fresco:fresco:${fresco}"
implementation "com.facebook.fresco:animated-gif-lite:${fresco}"
implementation "com.facebook.fresco:animated-gif:${fresco}"
implementation "com.facebook.fresco:animated-drawable:${fresco}"
implementation "com.facebook.fresco:animated-webp:${fresco}"
implementation "com.facebook.fresco:webpsupport:${fresco}"
implementation "com.squareup.okhttp3:okhttp:${okHttp}"
@ -248,6 +220,8 @@ dependencies {
implementation "com.j256.ormlite:ormlite-android:${ormlite}"
implementation "com.j256.ormlite:ormlite-core:${ormlite}"
implementation "com.jakewharton:butterknife:${butterKnife}"
kapt "com.jakewharton:butterknife-compiler:${butterKnife}"
implementation "org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}"
implementation "org.greenrobot:eventbus:${eventbus}"
@ -262,13 +236,18 @@ dependencies {
implementation "com.daimajia.swipelayout:library:${swipeLayout}"
implementation "com.google.android:flexbox:${flexbox}"
implementation "com.sina.weibo.sdk:core:${weiboSDK}"
// bugly with tinker support
implementation "com.tencent.bugly:crashreport_upgrade:${buglyTinkerSupport}"
implementation 'com.google.android:flexbox:1.1.0'
implementation "pub.devrel:easypermissions:${easypermissions}"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "com.contrarywind:Android-PickerView:${pickerView}"
implementation 'com.contrarywind:Android-PickerView:4.1.3'
implementation "com.scwang.smartrefresh:SmartRefreshLayout:${smartRefreshLayout}"
implementation "net.cachapa.expandablelayout:expandablelayout:${expandableLayout}"
@ -281,65 +260,46 @@ dependencies {
implementation "com.squareup.picasso:picasso:${picasso}"
// for video streaming
implementation("com.github.CarGuo.GSYVideoPlayer:gsyVideoPlayer-java:$gsyVideo", {
implementation ("com.shuyu:gsyVideoPlayer-java:$gsyVideo",{
exclude module: "gsyvideoplayer-androidvideocache"
exclude group: "tv.danmaku.ijk.media"
})
implementation "com.github.CarGuo.GSYVideoPlayer:gsyVideoPlayer-exo_player2:$gsyVideo"
implementation "com.shuyu:gsyVideoPlayer-armv7a:$gsyVideo"
implementation "com.shuyu:gsyVideoPlayer-x86:$gsyVideo"
implementation "androidx.work:work-runtime:${workManager}"
implementation "com.github.wendux:DSBridge-Android:$dsBridge"
implementation "com.llew.huawei:verifier:${verifier}"
implementation "android.arch.work:work-runtime:${workManager}"
implementation "com.llew.huawei:verifier:1.0.6"
implementation "com.github.tbruyelle:rxpermissions:${rxPermissions}"
implementation "com.lg:skeleton:${skeleton}"
implementation "com.tencent.mm.opensdk:wechat-sdk-android-without-mta:${mta}"
implementation "com.github.nichbar:AndroidRomChecker:${romChecker}"
implementation 'com.ethanhua:skeleton:1.1.1'
implementation 'io.supercharge:shimmerlayout:2.1.0'
implementation "com.tencent.mm.opensdk:wechat-sdk-android-without-mta:5.3.1"
implementation 'com.walkud.rom.checker:RomChecker:1.0.0'
debugImplementation "com.github.nichbar.chucker:library:${chucker}"
releaseImplementation "com.github.nichbar.chucker:library-no-op:${chucker}"
teaImplementation "com.bytedance.applog:RangersAppLog-Lite-cn:${bytedanceApplog}"
debugImplementation "com.github.nichbar.chucker:library:$chucker"
releaseImplementation "com.github.nichbar.chucker:library-no-op:$chucker"
implementation "com.bytedance.applog:RangersAppLog-Lite-cn:$bytedanceApplog"
implementation "com.aliyun.dpa:oss-android-sdk:${oss}"
implementation 'com.aliyun.dpa:oss-android-sdk:2.9.2'
implementation "com.airbnb.android:lottie:${lottie}"
implementation "com.airbnb.android:lottie:$lottie"
implementation "net.lingala.zip4j:zip4j:${zip4j}"
implementation "io.sentry:sentry-android:4.3.0"
implementation("com.github.piasy:BigImageViewer:${bigImageViewer}", {
implementation("com.github.piasy:BigImageViewer:$bigImageViewer", {
exclude group: 'com.squareup.okhttp3'
exclude group: 'androidx.swiperefreshlayout'
exclude group: 'com.github.bumptech.glide'
exclude group: 'com.facebook.fresco'
})
implementation "com.github.PhilJay:MPAndroidChart:${chart}"
implementation "com.lahm.library:easy-protector-release:${easyProtector}"
implementation "com.github.hsiafan:apk-parser:${apkParser}"
implementation "org.nanohttpd:nanohttpd:${nanohttpd}"
implementation "com.aliyun.openservices:aliyun-log-android-sdk:${aliyunLog}"
implementation "com.lg:easyfloat:${easyFloat}"
implementation "io.github.florent37:shapeofview:${shapeOfView}"
implementation "io.github.sinaweibosdk:core:${weiboSDK}"
implementation "com.lg:apksig:${apksig}"
implementation "com.lg:gid:${gid}"
implementation "com.louiscad.splitties:splitties-fun-pack-android-base-with-views-dsl:${splitties}"
compileOnly "com.github.axen1314.lancet:lancet-base:${lancet_version}"
implementation project(':libraries:LGLibrary')
implementation project(':libraries:MTA')
implementation project(':libraries:QQShare')
implementation project(':libraries:TalkingData')
implementation project(':libraries:UmengPush')
// implementation project(':libraries:WechatShare')
implementation project(':libraries:im')
implementation project(':libraries:Matisse')
implementation project(path: ':libraries:gsyVideoPlayer-proxy_cache')
}
File propFile = file('sign.properties')
if (propFile.exists()) {
@ -370,7 +330,7 @@ if (propFile.exists()) {
android.buildTypes.release.signingConfig = null
}
// 用于测试读取 META-INF 里的文件
// 用于测试读取 META-INF 里的 JSON 的代码
//task generateMetaJson {
// def resDir = new File(buildDir, 'generated/FILES_FOR_META_INF/')
// def destDir = new File(resDir, 'META-INF/')
@ -397,202 +357,3 @@ if (propFile.exists()) {
// task.name.startsWith('merge') && task.name.endsWith('Resources')
// }.each { t -> t.dependsOn generateMetaJson }
//}
andResGuard {
mappingFile = null
use7zip = true
useSign = true
// 打开这个开关会keep住所有资源的原始路径只混淆资源的名字
keepRoot = false
// 设置这个值会把arsc name列混淆成相同的名字减少string常量池的大小
fixedResName = "arg"
// 打开这个开关会合并所有哈希值相同的资源,但请不要过度依赖这个功能去除去冗余资源
mergeDuplicatedRes = true
whiteList = [
"R.drawable.icon",
"R.drawable.ic_bar_back",
"R.drawable.toolbar_search_icon",
"R.drawable.bg_notification_answer_style_1",
"R.drawable.bg_notification_answer_style_2",
"R.drawable.bg_notification_article_style_1",
"R.drawable.bg_notification_article_style_2",
"R.drawable.bg_notification_feedback_style_1",
"R.drawable.bg_notification_feedback_style_2",
"R.drawable.bg_notification_gift_style_1",
"R.drawable.bg_notification_gift_style_2",
"R.drawable.bg_notification_login_style_1",
"R.drawable.bg_notification_login_style_2",
"R.drawable.bg_notification_question_style_1",
"R.drawable.bg_notification_question_style_2",
"R.drawable.bg_notification_rating_style_1",
"R.drawable.bg_notification_rating_style_2",
"R.drawable.bg_notification_reserve_game_style_1",
"R.drawable.bg_notification_reserve_game_style_2",
"R.drawable.bg_notification_video_style_1",
"R.drawable.bg_notification_video_style_2",
"R.drawable.ic_search_no_1",
"R.drawable.ic_search_no_2",
"R.drawable.ic_search_no_3",
"R.drawable.ic_search_no_4",
"R.drawable.ic_search_no_5",
"R.drawable.ic_search_no_6",
"R.drawable.ic_search_no_7",
"R.drawable.ic_search_no_8",
"R.drawable.ic_search_no_9",
"R.drawable.ic_search_no_10",
"R.drawable.ic_search_no_11",
"R.drawable.ic_search_no_12",
"R.drawable.ic_search_no_13",
"R.drawable.ic_search_no_14",
"R.drawable.ic_search_no_15",
"R.drawable.ic_search_no_16",
"R.drawable.ic_search_no_17",
"R.drawable.ic_search_no_18",
"R.drawable.ic_search_no_19",
"R.drawable.ic_search_no_20",
"R.drawable.ic_recommend_activity",
"R.drawable.ic_recommend_discount",
"R.drawable.ic_recommend_function",
"R.drawable.ic_recommend_gift",
"R.drawable.ic_recommend_role",
"R.drawable.login_btn_bg",
"R.drawable.ic_quick_login_check",
"R.drawable.ic_quick_login_uncheck",
"R.anim.anim_auth_in",
"R.anim.anim_auth_out",
"R.id.download_speed",
"R.id.download_percentage",
"R.id.comment",
"R.id.vote",
"R.id.watermark_hint",
"R.id.watermark_sb",
"R.id.bottomShareIv",
"R.id.bottomShareTv",
"R.id.recommendStarPref",
"R.id.recommendStar",
"R.drawable.help_search_delete",
"R.drawable.suggest_type_normal",
"R.drawable.suggest_type_crash",
"R.drawable.suggest_type_game_question",
"R.drawable.suggest_type_game_collect",
"R.drawable.suggest_type_function_suggest",
"R.drawable.suggest_type_article_collect",
"R.drawable.suggest_type_copyright",
"R.drawable.help_result_empty",
"R.drawable.news_comment_detail_read",
"R.drawable.news_comment_detail_comment",
"R.drawable.news_comment_detail_share",
"R.drawable.ic_libao",
"R.drawable.ic_link",
"R.drawable.concern_message_icon",
"R.drawable.reuse_blank_hint",
"R.drawable.ic_concern",
"R.drawable.concern_down",
"R.drawable.concern_up",
"R.drawable.ic_libao_more",
"R.drawable.ic_libao_delete",
"R.drawable.ic_dialog_close",
"R.drawable.occupy2",
"R.drawable.kc_checkbox_unselect",
"R.drawable.kc_checkbox_select",
"R.drawable.ic_type_unselect",
"R.drawable.ic_type_selected",
"R.drawable.suggest_add_pic_icon",
"R.drawable.icon_pic_add",
"R.drawable.ask_search_input_delete",
"R.drawable.suggest_pic_delete"
]
compressFilePattern = [
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
]
sevenzip {
artifact = 'com.tencent.mm:SevenZip:1.2.20'
}
}
project.afterEvaluate {
def variants = null
try {
variants = android.applicationVariants
} catch (Throwable t) {
t.printStackTrace()
try {
variants = android.libraryVariants
} catch (Throwable tt) {
tt.printStackTrace()
}
}
if (variants != null) {
variants.all { variant ->
variant.outputs.each { output ->
def task = output.processManifestProvider.get()
if (task == null) {
return
}
/**
* 为 Manifest 的 Activity 的 configChanges 添加自己手动处理 configurationChanges 配置 [https://developer.android.com/guide/topics/resources/runtime-changes]
* AGP 4.1.0 从 ProcessManifest task 里拿 manifest 的 API 变更调整可以参考这里 [https://github.com/Tencent/tinker/pull/1476/commits/d71645729b13d545ca4ba6826f93fbf558751434]
* (搞半天还是不会抽离方法,有空再把 gradle 改成用 kotlin 实现吧)
*/
task.doLast {
def manifestFile = new File(multiApkManifestOutputDirectory.get().asFile, "AndroidManifest.xml")
if (manifestFile == null || !manifestFile.exists()) {
return
}
String[] configChanges = [
"density",
"fontScale",
"keyboard",
"keyboardHidden",
"layoutDirection",
"locale",
"mcc",
"mnc",
"navigation",
"orientation",
"screenLayout",
"screenSize",
"smallestScreenSize",
"touchscreen",
"uiMode"]
def parser = new XmlSlurper(false, true)
def manifest = parser.parse(manifestFile)
def app = manifest.'application'[0]
app.'activity'.each { act ->
String value = act.attributes()['android:configChanges']
if (value == null || value.isEmpty()) {
if (value == null) value = ""
configChanges.eachWithIndex { config, index ->
if (index != configChanges.length - 1) {
value += config + "|"
} else {
value += config
}
}
act.attributes()['androidconfigChanges'] = value
} else {
String[] valueSplit = value.split("\\|")
println configChanges
configChanges.eachWithIndex { config, index ->
if (!valueSplit.contains(config)) {
value += ("|" + config)
}
}
act.attributes()['android:configChanges'] = value
}
}
def tmpManifest = XmlUtil.serialize(manifest).replaceAll("androidconfigChanges", "android:configChanges")
manifest = parser.parseText(tmpManifest)
manifestFile.setText(XmlUtil.serialize(manifest), "utf-8")
}
}
}
}
}

Binary file not shown.

BIN
app/libs/gid-1.0.jar Normal file

Binary file not shown.

Binary file not shown.

View File

@ -1,266 +0,0 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in C:\Android\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# 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 *;
#}
#--------- remove logs start ----------------
-assumenosideeffects class com.lightgame.config.CommonDebug {
private static String getLogTag(...);
private static String getMethodName();
public static void logMethodName(...);
public static void logParams(...);
public static void logFields(...);
public static void logMethodWithParams(...);
}
#-assumenosideeffects class com.lightgame.config.CommonDebug {*;}
#-dontoptimize
#--------- remove logs end ----------------
-keepattributes *Annotation*,Signature,InnerClasses,EnclosingMethod
-dontwarn InnerClasses
# OrmLite uses reflection
-keep class com.j256.**
-keepclassmembers class com.j256.** { *; }
-keep enum com.j256.**
-keepclassmembers enum com.j256.** { *; }
-keep interface com.j256.**
-keepclassmembers interface com.j256.** { *; }
-dontwarn com.j256.**
#okhttp3
-dontwarn com.squareup.okhttp3.**
-dontwarn okio.**
-keep class com.squareup.okhttp3.** { *;}
# stetho
-keep class com.facebook.stetho.** { *; }
-dontwarn com.facebook.stetho.**
# Retrofit 2.2
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions
# Retrofit 2.X
## https://square.github.io/retrofit/ ##
-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions
-keepclasseswithmembers class * {
@retrofit2.http.* <methods>;
}
# rxjava
-keep class rx.schedulers.Schedulers {
public static <methods>;
}
-keep class rx.schedulers.ImmediateScheduler {
public <methods>;
}
-keep class rx.schedulers.TestScheduler {
public <methods>;
}
-keep class rx.schedulers.Schedulers {
public static ** test();
}
-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
long producerIndex;
long consumerIndex;
}
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
long producerNode;
long consumerNode;
}
-dontwarn rx.internal.util.**
## AutoScrollViewPager
-keep class cn.trinea.android.** { *; }
-keepclassmembers class cn.trinea.android.** { *; }
-dontwarn cn.trinea.android.**
## butterknife
# Retain generated class which implement Unbinder.
#-keep public class * implements butterknife.Unbinder { public <init>(**, android.view.View); }
#
## Prevent obfuscation of types which use ButterKnife annotations since the simple name
## is used to reflectively look up the generated ViewBinding.
#-keep class butterknife.*
#-keepclasseswithmembernames class * { @butterknife.* <methods>; }
#-keepclasseswithmembernames class * { @butterknife.* <fields>; }
-dontwarn butterknife.internal.**
-keep class **$$ViewInjector { *; }
-keepnames class * { @butterknife.InjectView *;}
-dontwarn butterknife.Views$InjectViewProcessor
-dontwarn com.gc.materialdesign.views.**
# eventbus
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
# weiboSdk
-keep class com.sina.weibo.sdk.** { *; }
-dontwarn android.webkit.WebView
-dontwarn android.webkit.WebViewClient
# app models
-keep class com.gh.common.view.** {*;}
-keep class com.gh.gamecenter.db.info.** {*;}
-keep class com.gh.gamecenter.entity.** {*;}
-keep class com.gh.gamecenter.qa.entity.** {*;}
-keep class com.gh.gamecenter.retrofit.** {*;}
-keep class com.gh.gamecenter.eventbus.** {*;}
-keep class com.gh.gamecenter.video.detail.** {*;}
-keep class * extends rx.Subscriber
#---------------------------------webview------------------------------------
-keepclassmembers class * extends android.webkit.WebViewClient {
public void *(android.webkit.WebView, java.lang.String, android.graphics.Bitmap);
public boolean *(android.webkit.WebView, java.lang.String);
}
-keepclassmembers class * extends android.webkit.WebViewClient {
public void *(android.webkit.WebView, java.lang.String);
}
#----------------------------------------------------------------------------
##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# For using GSON @Expose annotation
-keepattributes *Annotation*
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
-keepclassmembers enum * { *; }
##---------------End: proguard configuration for Gson ----------
# ------ bugly ---------
-dontwarn com.tencent.bugly.**
-keep public class com.tencent.bugly.**{*;}
# easypermission
-keepclassmembers class * {
@pub.devrel.easypermissions.AfterPermissionGranted <methods>;
}
# 重命名文件为SourceFile再配合mapping符号表可以拿到真实的类名
-renamesourcefileattribute SourceFile
# 保留源文件行号
-keepattributes SourceFile,LineNumberTable
-ignorewarnings
-keep @androidx.annotation.Keep class *
-keepclassmembers class ** {
@androidx.annotation.Keep *;
}
-keep class com.gh.loghub.** { *; }
### greenDAO 3
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties
-keep class org.greenrobot.greendao.** { *; }
# If you do not use SQLCipher:
-dontwarn org.greenrobot.greendao.database.**
# If you do not use RxJava:
-dontwarn rx.**
-dontwarn org.greenrobot.greendao.rx.**
-dontwarn org.greenrobot.greendao.**
### fastJson
-dontwarn com.alibaba.fastjson.**
-keep class com.alibaba.fastjson.** { *; }
-keepattributes Signature
-keepattributes Annotation
### AndroidX
-keep class androidx.core.app.CoreComponentFactory { *; }
#阿里云上传
-keep class com.alibaba.sdk.android.oss.** { *; }
-dontwarn okio.**
-dontwarn org.apache.commons.codec.binary.**
#视频相关
-keep class com.shuyu.gsyvideoplayer.video.** { *; }
-dontwarn com.shuyu.gsyvideoplayer.video.**
-keep class com.shuyu.gsyvideoplayer.video.base.** { *; }
-dontwarn com.shuyu.gsyvideoplayer.video.base.**
-keep class com.shuyu.gsyvideoplayer.utils.** { *; }
-dontwarn com.shuyu.gsyvideoplayer.utils.**
-keep class tv.danmaku.ijk.** { *; }
-dontwarn tv.danmaku.ijk.**
-keep public class * extends android.view.View{
*** get*();
void set*(***);
public <init>(android.content.Context);
public <init>(android.content.Context, android.util.AttributeSet);
public <init>(android.content.Context, android.util.AttributeSet, int);
}
#穿山甲
-keep class com.bytedance.sdk.openadsdk.** { *; }
-keep public interface com.bytedance.sdk.openadsdk.downloadnew.** {*;}
-keep class com.pgl.sys.ces.* {*;}
-keep class com.gyf.immersionbar.* {*;}
-dontwarn com.gyf.immersionbar.**
-keep class com.taobao.securityjni.**{*;}
-keep class com.taobao.wireless.security.**{*;}
-keep class com.ut.secbody.**{*;}
-keep class com.taobao.dp.**{*;}
-keep class com.alibaba.wireless.security.**{*;}
-keep class com.alibaba.sdk.android.**{*;}
-keep class com.ut.**{*;}
-keep class com.ta.**{*;}
-keep class com.gh.gamecenter.TeaHelper { *; }

View File

@ -1,3 +1,20 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in C:\Android\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# 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 *;
#}
#--------- remove logs start ----------------
-assumenosideeffects class com.lightgame.config.CommonDebug {
@ -9,69 +26,126 @@
public static void logMethodWithParams(...);
}
-assumenosideeffects class com.lightgame.utils.Utils {
public static void log(...);
}
#-assumenosideeffects class com.lightgame.config.CommonDebug {*;}
#-dontoptimize
#--------- remove logs end ----------------
#--------- remove useless mtahelper class --------
-assumenosideeffects class com.gh.common.util.MtaHelper {
public static void onEvent(...);
public static void onEventWithTime(...);
public static void onEventWithBasicDeviceInfo(...);
}
#--------- remove useless mta class end ----
-keepattributes *Annotation*,Signature,InnerClasses,EnclosingMethod
-dontwarn InnerClasses
# TODO Dicard sourceFile in final release build but remain in internal build.
-renamesourcefileattribute SourceFile
# Keep Attribute
-keepattributes *Annotation*,Signature,InnerClasses,EnclosingMethod,SourceFile,LineNumberTable
# OrmLite
-keep class com.j256.*
-keepclassmembers class com.j256.* { *; }
-keep enum com.j256.*
-keepclassmembers enum com.j256.* { *; }
-keep interface com.j256.*
-keepclassmembers interface com.j256.* { *; }
# OrmLite uses reflection
-keep class com.j256.**
-keepclassmembers class com.j256.** { *; }
-keep enum com.j256.**
-keepclassmembers enum com.j256.** { *; }
-keep interface com.j256.**
-keepclassmembers interface com.j256.** { *; }
-dontwarn com.j256.**
### AutoScrollViewPager
-keep class cn.trinea.android.* { *; }
-keepclassmembers class cn.trinea.android.* { *; }
#okhttp3
-dontwarn com.squareup.okhttp3.**
-dontwarn okio.**
-keep class com.squareup.okhttp3.** { *;}
# stetho
-keep class com.facebook.stetho.** { *; }
-dontwarn com.facebook.stetho.**
# Retrofit 2.2
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions
# Retrofit 2.X
## https://square.github.io/retrofit/ ##
-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions
-keepclasseswithmembers class * {
@retrofit2.http.* <methods>;
}
# rxjava
-keep class rx.schedulers.Schedulers {
public static <methods>;
}
-keep class rx.schedulers.ImmediateScheduler {
public <methods>;
}
-keep class rx.schedulers.TestScheduler {
public <methods>;
}
-keep class rx.schedulers.Schedulers {
public static ** test();
}
-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
long producerIndex;
long consumerIndex;
}
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
long producerNode;
long consumerNode;
}
-dontwarn rx.internal.util.**
## AutoScrollViewPager
-keep class cn.trinea.android.** { *; }
-keepclassmembers class cn.trinea.android.** { *; }
-dontwarn cn.trinea.android.**
### eventbus
-keepclassmembers class * {
## butterknife
# Retain generated class which implement Unbinder.
#-keep public class * implements butterknife.Unbinder { public <init>(**, android.view.View); }
#
## Prevent obfuscation of types which use ButterKnife annotations since the simple name
## is used to reflectively look up the generated ViewBinding.
#-keep class butterknife.*
#-keepclasseswithmembernames class * { @butterknife.* <methods>; }
#-keepclasseswithmembernames class * { @butterknife.* <fields>; }
-dontwarn butterknife.internal.**
-keep class **$$ViewInjector { *; }
-keepnames class * { @butterknife.InjectView *;}
-dontwarn butterknife.Views$InjectViewProcessor
-dontwarn com.gc.materialdesign.views.**
# eventbus
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
### Only required if you use AsyncExecutor
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
### weiboSdk
# weiboSdk
-keep class com.sina.weibo.sdk.** { *; }
-dontwarn android.webkit.WebView
-dontwarn android.webkit.WebViewClient
### wechatSdk
### TODO 这里用 com.tencent.*{*;} 不起效?但其它地方可以?
-keep class com.tencent.**{*;}
# app models
-keep class com.gh.common.view.** {*;}
-keep class com.gh.gamecenter.db.info.** {*;}
-keep class com.gh.gamecenter.entity.** {*;}
-keep class com.gh.gamecenter.qa.entity.** {*;}
-keep class com.gh.gamecenter.retrofit.** {*;}
-keep class com.gh.gamecenter.eventbus.** {*;}
-keep class * extends rx.Subscriber
### app models
-keep class com.gh.common.view.* {*;}
-keep class com.gh.gamecenter.db.info.* {*;}
-keep class com.gh.gamecenter.entity.* {*;}
-keep class com.gh.gamecenter.qa.entity.* {*;}
-keep class com.gh.gamecenter.retrofit.* {*;}
-keep class com.gh.gamecenter.eventbus.* {*;}
-keep class com.gh.gamecenter.video.detail.* {*;}
-keep class com.gh.gamecenter.home.gamecollection.* {*;}
###
#---------------------------------webview------------------------------------
-keepclassmembers class * extends android.webkit.WebViewClient {
public void *(android.webkit.WebView, java.lang.String, android.graphics.Bitmap);
public boolean *(android.webkit.WebView, java.lang.String);
@ -79,79 +153,91 @@
-keepclassmembers class * extends android.webkit.WebViewClient {
public void *(android.webkit.WebView, java.lang.String);
}
#----------------------------------------------------------------------------
### easypermission
##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# For using GSON @Expose annotation
-keepattributes *Annotation*
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
-keepclassmembers enum * { *; }
##---------------End: proguard configuration for Gson ----------
# ------ bugly ---------
-dontwarn com.tencent.bugly.**
-keep public class com.tencent.bugly.**{*;}
# easypermission
-keepclassmembers class * {
@pub.devrel.easypermissions.AfterPermissionGranted <methods>;
}
# TODO What's this ?
# 重命名文件为SourceFile再配合mapping符号表可以拿到真实的类名
-renamesourcefileattribute SourceFile
# 保留源文件行号
-keepattributes SourceFile,LineNumberTable
-ignorewarnings
### Keep Annotation
-keep @androidx.annotation.Keep class *
-keepclassmembers class * {
-keepclassmembers class ** {
@androidx.annotation.Keep *;
}
### 阿里云上传
-keep class com.alibaba.sdk.android.oss.* { *; }
-keep class com.gh.loghub.** { *; }
### greenDAO 3
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties
-keep class org.greenrobot.greendao.** { *; }
# If you do not use SQLCipher:
-dontwarn org.greenrobot.greendao.database.**
# If you do not use RxJava:
-dontwarn rx.**
-dontwarn org.greenrobot.greendao.rx.**
-dontwarn org.greenrobot.greendao.**
### fastJson
-dontwarn com.alibaba.fastjson.**
-keep class com.alibaba.fastjson.** { *; }
-keepattributes Signature
-keepattributes Annotation
### 广点通
-dontwarn com.qq.gdt.action.**
-keep class com.qq.gdt.action.** {*;}
### AndroidX
-keep class androidx.core.app.CoreComponentFactory { *; }
#阿里云上传
-keep class com.alibaba.sdk.android.oss.** { *; }
-dontwarn okio.**
-dontwarn org.apache.commons.codec.binary.**
### 视频相关
-keep class com.shuyu.gsyvideoplayer.video.* { *; }
#视频相关
-keep class com.shuyu.gsyvideoplayer.video.** { *; }
-dontwarn com.shuyu.gsyvideoplayer.video.**
-keep class com.shuyu.gsyvideoplayer.video.base.* { *; }
-keep class com.shuyu.gsyvideoplayer.video.base.** { *; }
-dontwarn com.shuyu.gsyvideoplayer.video.base.**
-keep class com.shuyu.gsyvideoplayer.utils.* { *; }
-keep class com.shuyu.gsyvideoplayer.utils.** { *; }
-dontwarn com.shuyu.gsyvideoplayer.utils.**
-keep class tv.danmaku.ijk.* { *; }
-dontwarn tv.danmaku.ijk.**
-keep public class * extends android.view.View{
*** get*();
void set*(***);
public <init>(android.content.Context);
public <init>(android.content.Context, android.util.AttributeSet);
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keep class com.alibaba.sdk.android.*{*;}
-keep class com.ut.*{*;}
-keep class com.ta.*{*;}
### TEA
-keep class com.gh.gamecenter.TeaHelper { *; }
### 阿里云日志
-keep class com.aliyun.sls.android.producer.* { *; }
-keep interface com.aliyun.sls.android.producer.* { *; }
### 中国移动一键登录
-dontwarn com.cmic.sso.sdk.**
-keep class com.cmic.sso.sdk.* { *; }
### EasyFloat
-keep class com.lzf.easyfloat.* {*;}
### 避免 WebChromeClient 被混淆
-keepclassmembers class * extends android.webkit.WebChromeClient{
public void openFileChooser(...);
}
### emoji4j
-keep class emoji4j.* {*;}
### dokit
-keep class com.didichuxing.** {*;}
# Flutter模块
-keep class com.gh.common.util.DirectUtils {
public static void directToQa(...);
public static void directToQaCollection(...);
public static void directToGift(...);
public static void directToConcernInfo(...);
public static void directToFeedback(...);
public static void directToSuggestion(...);
}
-keep class tv.danmaku.ijk.** { *; }
-dontwarn tv.danmaku.ijk.**

View File

@ -2,6 +2,9 @@ package com.gh.gamecenter;
import android.app.Application;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.squareup.leakcanary.LeakCanary;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
@ -15,8 +18,18 @@ import okhttp3.logging.HttpLoggingInterceptor;
public class Injection {
public static boolean appInit(Application application) {
// 监控Bundle大小,预防溢出(需要调试的时候再开启吧!)
// TooLargeTool.startLogging(application);
// init leakcanary
if (LeakCanary.isInAnalyzerProcess(application)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return false;
}
LeakCanary.install(application);
// init stetho
Stetho.initializeWithDefaults(application);
return true;
}
@ -25,6 +38,7 @@ public class Injection {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addNetworkInterceptor(interceptor);
builder.addNetworkInterceptor(new StethoInterceptor());
return builder;
}

View File

@ -9,6 +9,8 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 允许应用程序读取扩展存储器 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- 允许挂载和反挂载文件系统可移动存储 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 允许应用程序访问Wi-Fi网络状态信息 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 允许应用程序获取网络信息状态 -->
@ -21,35 +23,26 @@
<uses-permission android:name="android.permission.VIBRATE" />
<!-- 允许应用程序改变Wi-Fi连接状态 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 允许应用程序改变网络连接状态 -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- 允许应用程序快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<!-- 前台服务权限-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<!-- 允许应用程序打开系统窗口,显示其他应用程序 -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<!-- 修改系统设置的权限 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
<!-- bugly with tinker -->
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<!-- 如果有视频相关的广告且使用textureView播放请务必添加否则黑屏 -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-sdk tools:overrideLibrary="com.shuyu.gsyvideoplayer,
com.shuyu.gsyvideoplayer.lib,
com.haroldadmin.whatthestack,
com.shuyu.gsyvideoplayer.armv7a,
com.shuyu.gsyvideoplayer.x86,
com.shuyu.gsy.base,
shuyu.com.androidvideocache,
com.google.android.exoplayer2,
tv.danmaku.ijk.media.exo2,
pl.droidsonroids.gif,
com.lzf.easyfloat" />
pl.droidsonroids.gif" />
<!-- 去掉 SDK 一些流氓权限 -->
<uses-permission
@ -65,26 +58,16 @@
<!--android:largeHeap = "true"-->
<application
android:name="com.halo.assistant.HaloApp"
android:name="com.halo.assistant.TinkerApp"
android:allowBackup="true"
android:icon="@mipmap/logo"
android:label="@string/app_name"
android:largeHeap="true"
android:networkSecurityConfig="@xml/network_security_config"
android:resizeableActivity="true"
android:theme="@style/AppCompatTheme.APP"
tools:replace="android:name,android:allowBackup"
tools:targetApi="n">
<meta-data
android:name="io.sentry.auto-init"
android:value="false" />
<!-- 不让 sentry 读取系统事件 -->
<meta-data
android:name="io.sentry.breadcrumbs.system-events"
android:value="false" />
<!--android:launchMode = "singleTask"-->
<activity
android:name="com.gh.gamecenter.SplashScreenActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
@ -111,9 +94,8 @@
android:launchMode="singleTask"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.ImageViewerActivity"
android:theme="@style/Theme.Transparent" />
<!--android:theme = "@android:style/Theme.Black.NoTitleBar.Fullscreen" 退出时屏幕抖动 -->
<activity android:name="com.gh.gamecenter.ViewImageActivity" />
<activity
android:name="com.gh.gamecenter.SearchActivity"
@ -131,10 +113,6 @@
android:name="com.gh.gamecenter.ShellActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.gamedetail.history.HistoryApkListActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.NewsDetailActivity"
android:screenOrientation="portrait" />
@ -166,14 +144,6 @@
<activity
android:name="com.gh.gamecenter.WebActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.SingletonWebActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.FullScreenWebActivity"
android:screenOrientation="portrait" />
<activity
@ -186,8 +156,7 @@
<activity
android:name="com.gh.gamecenter.MessageDetailActivity"
android:screenOrientation="portrait"
android:theme="@style/TransparentStatusBarAndNavigationBar" />
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.LibaoActivity"
@ -214,18 +183,9 @@
android:name="com.gh.gamecenter.AboutActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.security.SecurityActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.security.BindPhoneActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.CommentDetailActivity"
android:screenOrientation="portrait"
android:theme="@style/TransparentStatusBarAndNavigationBar" />
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.mygame.MyGameActivity"
@ -244,6 +204,11 @@
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustResize" />
<activity
android:name="com.gh.gamecenter.ToolBoxActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="com.gh.gamecenter.WeiBoShareActivity"
android:screenOrientation="portrait"
@ -283,10 +248,18 @@
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="com.gh.gamecenter.qa.search.AskSearchActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.answer.detail.AnswerDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.questions.detail.QuestionsDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.answer.fold.AnswerFoldActivity"
android:screenOrientation="portrait" />
@ -307,6 +280,14 @@
android:name="com.gh.gamecenter.MessageKeFuActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.select.CommunitiesSelectActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.subject.CommunitySubjectActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.MessageInviteActivity"
android:screenOrientation="portrait" />
@ -323,6 +304,10 @@
android:name="com.gh.gamecenter.qa.myqa.MyAskActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.column.order.AskTabOrderActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.questions.edit.QuestionEditActivity"
android:screenOrientation="portrait" />
@ -344,6 +329,10 @@
android:name="com.gh.gamecenter.amway.AmwayActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.column.detail.AskColumnDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.NetworkDiagnosisActivity"
android:screenOrientation="portrait" />
@ -376,10 +365,6 @@
android:name="com.gh.gamecenter.qa.article.detail.ArticleDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.article.detail.comment.ArticleDetailCommentActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.draft.CommunityDraftWrapperActivity"
android:screenOrientation="portrait" />
@ -389,6 +374,14 @@
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name="com.gh.gamecenter.qa.questions.edit.manager.HistoryDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.questions.edit.manager.HistoryActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.editor.InsertAnswerWrapperActivity"
android:screenOrientation="portrait" />
@ -403,8 +396,7 @@
<activity
android:name="com.gh.gamecenter.gamedetail.rating.RatingReplyActivity"
android:screenOrientation="portrait"
android:theme="@style/TransparentStatusBarAndNavigationBar" />
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.history.HistoryActivity"
@ -422,21 +414,24 @@
android:name="com.gh.gamecenter.tag.TagsActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.article.SimpleArticleListActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.video.videomanager.VideoManagerActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.video.upload.view.UploadVideoActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.video.game.GameVideoActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.editor.LocalMediaActivity"
android:name="com.gh.gamecenter.qa.editor.VideoActivity"
android:screenOrientation="portrait" />
<activity
@ -461,8 +456,8 @@
<activity
android:name="com.gh.gamecenter.HelpAndFeedbackActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
android:windowSoftInputMode="stateHidden"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.help.HelpDetailActivity"
@ -470,11 +465,7 @@
<activity
android:name="com.gh.gamecenter.qa.comment.CommentActivity"
android:theme="@style/Theme.Transparent"
android:windowSoftInputMode="adjustNothing" />
<activity
android:name=".qa.dialog.ChooseForumActivity"
android:screenOrientation="portrait"
android:theme="@style/Theme.Transparent"
android:windowSoftInputMode="adjustNothing" />
@ -487,191 +478,13 @@
android:name=".gamedetail.myrating.MyRatingActivity"
android:screenOrientation="portrait" />
<!-- 使用小米/华为推送弹窗功能提高推送成功率-->
<activity
android:name="com.gh.gamecenter.gamedetail.fuli.kaifu.ServersCalendarActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.QaActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.answer.draft.AnswerDraftActivity"
android:screenOrientation="portrait" />
<activity
android:name=".gamedetail.rating.RatingFoldActivity"
android:screenOrientation="portrait" />
<activity
android:name=".video.data.VideoDataActivity"
android:screenOrientation="portrait" />
<activity
android:name=".video.poster.PosterEditActivity"
android:screenOrientation="portrait" />
<activity
android:name=".video.poster.PosterClipActivity"
android:screenOrientation="portrait" />
<activity
android:name=".forum.select.ForumSelectActivity"
android:screenOrientation="portrait" />
<activity
android:name=".forum.detail.ForumDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name=".forum.moderator.ModeratorListActivity"
android:screenOrientation="portrait" />
<activity
android:name=".forum.moderator.ApplyModeratorActivity"
android:screenOrientation="portrait" />
<activity
android:name=".video.label.VideoLabelActivity"
android:screenOrientation="portrait" />
<activity
android:name=".personalhome.border.AvatarBorderActivity"
android:screenOrientation="portrait" />
<activity
android:name=".personalhome.background.PersonalityBackgroundActivity"
android:screenOrientation="portrait" />
<activity
android:name=".personalhome.background.BackgroundPreviewActivity"
android:screenOrientation="portrait" />
<activity
android:name=".personalhome.background.BackgroundClipActivity"
android:screenOrientation="portrait"
android:theme="@style/TransparentStatusBarAndNavigationBar" />
<activity
android:name=".simulatorgame.SimulatorGameActivity"
android:screenOrientation="portrait" />
<activity
android:name=".simulatorgame.SimulatorManagementActivity"
android:screenOrientation="portrait" />
<activity
android:name=".catalog.CatalogActivity"
android:screenOrientation="portrait" />
<activity
android:name=".catalog.NewCatalogListActivity"
android:screenOrientation="portrait" />
<activity
android:name=".forum.search.ForumOrUserSearchActivity"
android:screenOrientation="portrait" />
<activity
android:name=".energy.EnergyCenterActivity"
android:launchMode="singleTask"
android:screenOrientation="portrait" />
<activity
android:name=".energy.EnergyHouseActivity"
android:screenOrientation="portrait" />
<activity
android:name=".personal.NewPersonalActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.questions.draft.QuestionDraftActivity"
android:screenOrientation="portrait" />
<activity
android:name=".servers.GameServerTestActivity"
android:screenOrientation="portrait" />
<activity
android:name=".category2.CategoryV2Activity"
android:screenOrientation="portrait" />
<activity
android:name=".personal.DeliveryInfoActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.editor.PreviewVideoActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.video.publish.VideoPublishActivity"
android:screenOrientation="portrait" />
<activity
android:name=".setting.GameDownloadSettingActivity"
android:screenOrientation="portrait" />
<activity
android:name=".setting.VideoSettingActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.video.detail.ForumVideoDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name=".video.videomanager.VideoDraftActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.questions.newdetail.NewQuestionDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.editor.FullScreenVideoActivity"
android:theme="@style/AppFullScreenTheme" />
<activity
android:name=".forum.list.ForumListActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.answer.detail.SimpleAnswerDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name=".game.commoncollection.detail.CommonCollectionDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name=".gamecollection.detail.GameCollectionDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name=".gamecollection.detail.GameCollectionPosterActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.cmic.sso.sdk.activity.LoginAuthActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Dialog" />
<activity
android:name=".home.skip.PackageSkipActivity"
android:screenOrientation="portrait" />
<!-- &lt;!&ndash; 使用小米/华为推送弹窗功能提高推送成功率&ndash;&gt;-->
<!-- <activity-->
<!-- android:name="com.gh.gamecenter.PushProxyActivity"-->
<!-- android:exported="true"-->
<!-- android:launchMode="singleTask"-->
<!-- android:theme="@android:style/Theme.Translucent" />-->
<activity
android:name="com.gh.gamecenter.PushProxyActivity"
android:exported="true"
android:theme="@android:style/Theme.Translucent" />
<activity
android:name="com.gh.gamecenter.SkipActivity"
android:theme="@style/Theme.AppCompat.Light.Fullscreen.Transparent">
<intent-filter>
@ -681,74 +494,16 @@
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
<intent-filter>
<data android:scheme="market" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
</activity>
<activity
android:name="com.gh.gamecenter.teenagermode.TeenagerModeActivity"
android:screenOrientation="portrait" />
<activity
android:name=".gamecollection.publish.GameCollectionEditActivity"
android:screenOrientation="portrait" />
<activity
android:name=".gamecollection.choose.ChooseGamesActivity"
android:screenOrientation="portrait" />
<activity
android:name=".gamecollection.choose.AddGamesActivity"
android:screenOrientation="portrait" />
<activity
android:name=".gamecollection.mine.MyGameCollectionActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.gamecollection.square.GameCollectionSquareActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.gamecollection.tag.GameCollectionTagSelectActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.editor.InsertGameCollectionWrapperActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.editor.InsertVideoWrapperActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.toolbox.ToolBoxBlockActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.subject.CommunitySubjectActivity"
android:screenOrientation="portrait" />
<activity
android:name="${applicationId}.wxapi.WXEntryActivity"
android:exported="true"
android:label="@string/app_name"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Translucent.NoTitleBar"></activity>
<!-- <activity-->
<!-- android:name="${applicationId}.douyinapi.DouYinEntryActivity"-->
<!-- android:launchMode="singleTask"-->
<!-- android:taskAffinity="${applicationId}"-->
<!-- android:exported="true" />-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}"
@ -759,24 +514,6 @@
android:resource="@xml/provider_paths" />
</provider>
<provider
android:name="com.gh.gamecenter.provider.GhContentProvider"
android:authorities="${applicationId}.provider"
android:enabled="true"
android:exported="true"/>
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<!-- If you are using androidx.startup to initialize other components -->
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
<receiver
android:name="com.gh.gamecenter.receiver.DownloadReceiver"
android:exported="false">
@ -800,39 +537,42 @@
</intent-filter>
</receiver>
<!-- 梦工厂配置 开始 -->
<!--<meta-data
android:name="MGC_APPID"
android:value="1001276" />
<receiver android:name="com.gh.gamecenter.receiver.UmengMessageReceiver">
<intent-filter>
<action android:name="com.gh.gamecenter.UMENG" />
</intent-filter>
</receiver>
<provider
android:name="com.leto.game.base.provider.LetoFileProvider"
android:authorities="${applicationId}.leto.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/leto_file_path"
tools:replace="android:resource" />
</provider>-->
<!-- 梦工厂配置 结束 -->
<!--魅族push应用定义消息receiver声明 -->
<receiver android:name="com.gh.gamecenter.receiver.MeizuPushReceiver">
<intent-filter>
<!-- 接收push消息 -->
<action android:name="com.meizu.flyme.push.intent.MESSAGE" />
<!-- 接收register消息 -->
<action android:name="com.meizu.flyme.push.intent.REGISTER.FEEDBACK" />
<!-- 接收unregister消息-->
<action android:name="com.meizu.flyme.push.intent.UNREGISTER.FEEDBACK" />
<!-- 兼容低版本Flyme3推送服务配置 -->
<action android:name="com.meizu.c2dm.intent.REGISTRATION" />
<action android:name="com.meizu.c2dm.intent.RECEIVE" />
<!-- 穿山甲配置 开始 -->
<!--<provider
android:name="com.bytedance.sdk.openadsdk.TTFileProvider"
android:authorities="${applicationId}.TTFileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<receiver
android:name="com.gh.common.im.ImReceiver"
android:enabled="true">
<intent-filter android:priority="2147483647">
<action android:name="com.gh.im" />
<action android:name="action_finish" />
</intent-filter>
</receiver>
<service android:name="com.gh.base.GHUmengNotificationService" />
<!--<service android:name = "com.gh.gamecenter.statistics.AppStaticService" />-->
<provider
android:name="com.bytedance.sdk.openadsdk.multipro.TTMultiProvider"
android:authorities="${applicationId}.TTMultiProvider"
android:exported="false" />-->
<!-- 穿山甲配置 结束 -->
</application>
</manifest>

View File

@ -2,20 +2,16 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="normalize.css">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="video-js.min.css">
<!-- <link rel="stylesheet" href="https://static-web.ghzs.com/website-static/lib/video-js.min.css">--> <!--在web页面播放视频-->
<!--<link rel="stylesheet" type="text/css" href="https://resource.ghzs.com/css/halo_app.css">-->
</head>
<body style="overflow-x: hidden; word-break: break-all;">
<body>
<div id="editor" contenteditable="false"></div>
<script type="text/javascript" src="zepto.min.js"></script>
<script type="text/javascript" src="rich_editor.js"></script>
<script type="text/javascript" src="video.min.js"></script>
<!--<script src="https://static-web.ghzs.com/website-static/lib/video.min.js"></script>--> <!--在web页面播放视频-->
<!--<script type="text/javascript" src="content.js"></script>-->
<!--<script type="text/javascript" src="https://resource.ghzs.com/js/halo_app.js"></script>-->
</body>

View File

@ -0,0 +1,40 @@
emoji_kf_1.png,:smile:
emoji_kf_2.png,:smiley:
emoji_kf_3.png,:laughing:
emoji_kf_4.png,:blush:
emoji_kf_5.png,:heart_eyes:
emoji_kf_6.png,:smirk:
emoji_kf_7.png,:flushed:
emoji_kf_8.png,:kissing_heart:
emoji_kf_9.png,:grin:
emoji_kf_10.png,:wink:
emoji_kf_11.png,:stuck_out_tongue_winking_eye:
emoji_kf_12.png,:stuck_out_tongue_closed eyes:
emoji_kf_13.png,:worried:
emoji_kf_14.png,:sleeping:
emoji_kf_15.png,:expressionless:
emoji_kf_16.png,:sweat_smile:
emoji_kf_17.png,:joy:
emoji_kf_18.png,:cold_sweat:
emoji_kf_19.png,:sob:
emoji_kf_20.png,:angry:
emoji_kf_21.png,:mask:
emoji_kf_22.png,:scream:
emoji_kf_23.png,:sunglasses:
emoji_kf_24.png,:heart:
emoji_kf_25.png,:broken_heart:
emoji_kf_26.png,:star:
emoji_kf_27.png,:anger:
emoji_kf_28.png,:exclamation:
emoji_kf_29.png,:question:
emoji_kf_30.png,:zzz:
emoji_kf_31.png,:thumbsup:
emoji_kf_32.png,:thumbsdown:
emoji_kf_33.png,:ok_hand:
emoji_kf_34.png,:punch:
emoji_kf_35.png,:yeah:
emoji_kf_36.png,:clap:
emoji_kf_37.png,:muscle:
emoji_kf_38.png,:pray:
emoji_kf_39.png,:skull:
emoji_kf_40.png,:trollface:

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
{"v":"5.6.4","fr":25,"ip":0,"op":35,"w":1080,"h":214,"nm":"点赞","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"椭圆形 2","sr":1,"ks":{"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.588],"y":[0]},"t":17,"s":[15]},{"t":20,"s":[0]}],"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[468.04,73.68,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.659,0.659,0.333],"y":[0,0,0]},"t":10,"s":[50,50,100]},{"t":19,"s":[150,150,100]}],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":0,"k":[24,24],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"椭圆路径 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"填充 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"椭圆形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":10,"op":1510,"st":10,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"椭圆形 3","sr":1,"ks":{"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.588],"y":[0]},"t":27,"s":[15]},{"t":30,"s":[0]}],"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[468.04,73.68,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.659,0.659,0.333],"y":[0,0,0]},"t":20,"s":[50,50,100]},{"t":28,"s":[140,140,100]}],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":0,"k":[24,24],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"椭圆路径 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"填充 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"椭圆形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":20,"op":1520,"st":20,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"路径备份 2","sr":1,"ks":{"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.602],"y":[0]},"t":0,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.663],"y":[0]},"t":24,"s":[100]},{"t":29,"s":[0]}],"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[531.02,129.675,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.514,0.514,0.333],"y":[0,0,0]},"t":5,"s":[100,100,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.533,0.533,0.333],"y":[0,0,0]},"t":10,"s":[90,90,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.586,0.586,0.333],"y":[0,0,0]},"t":15,"s":[95,95,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.499,0.499,0.333],"y":[0,0,0]},"t":19,"s":[90,90,100]},{"t":24,"s":[100,100,100]}],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-5.33,-8.3],[3.89,0.27],[-4.4,-1.68],[-4.33,-0.67],[-4.08,9.32],[3.33,5.44],[3.39,4.6],[0.87,-3.7],[3.6,-0.86],[1.03,-0.21],[2.34,-0.53],[0.96,1.15],[4.22,5.48],[-1.18,-4.56]],"o":[[1.11,1.71],[-3.89,-0.27],[6.42,2.5],[4.33,0.66],[1.63,-5.32],[-3.34,-5.45],[-1.68,-2.1],[-0.71,3.14],[-3.43,0.95],[-0.57,0.08],[-3.86,1.12],[-3.23,-3.94],[-1.89,-2.28],[2.42,4.64]],"v":[[-5.387,9.698],[-10.717,8.498],[-12.327,15.628],[5.813,21.748],[23.313,11.778],[20.273,-1.202],[11.563,-13.962],[5.393,-12.362],[1.083,-13.722],[-2.087,-9.742],[-5.707,-11.752],[-8.777,-7.572],[-18.297,-20.542],[-23.827,-17.832]],"c":true},"ix":2},"nm":"路径 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"填充 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"路径备份 2","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":1500,"st":0,"bm":0}],"markers":[]}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
{"v":"5.6.9","fr":60,"ip":0,"op":76,"w":90,"h":90,"nm":"loading","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":2,"ty":4,"nm":"圆环1","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[45,45,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"d":1,"ty":"el","s":{"a":0,"k":[63,63],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"椭圆路径 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.75],"y":[0.833]},"o":{"x":[0.25],"y":[0.167]},"t":28,"s":[0]},{"t":76,"s":[96]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.75],"y":[0.833]},"o":{"x":[0.25],"y":[0.167]},"t":0,"s":[4]},{"t":48,"s":[100]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.75],"y":[0.712]},"o":{"x":[0.25],"y":[0.288]},"t":0,"s":[-7.2]},{"t":76,"s":[367.2]}],"ix":3},"m":1,"ix":2,"nm":"修剪路径 1","mn":"ADBE Vector Filter - Trim","hd":false},{"ty":"st","c":{"a":0,"k":[0.141176477075,0.588235318661,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":9,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"描边 1","mn":"ADBE Vector Graphic - Stroke","hd":false}],"ip":0,"op":76,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"圆环2","sr":1,"ks":{"o":{"a":0,"k":40,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[45,45,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"d":1,"ty":"el","s":{"a":0,"k":[63,63],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"椭圆路径 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.75],"y":[0.861]},"o":{"x":[0.25],"y":[0.139]},"t":36,"s":[0]},{"t":76,"s":[96]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.75],"y":[0.806]},"o":{"x":[0.25],"y":[0.194]},"t":0,"s":[4]},{"t":56,"s":[100]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.75],"y":[0.712]},"o":{"x":[0.25],"y":[0.288]},"t":0,"s":[-7.2]},{"t":76,"s":[367.2]}],"ix":3},"m":1,"ix":2,"nm":"修剪路径 1","mn":"ADBE Vector Filter - Trim","hd":false},{"ty":"st","c":{"a":0,"k":[0.141176477075,0.588235318661,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":9,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"描边 1","mn":"ADBE Vector Graphic - Stroke","hd":false}],"ip":0,"op":76,"st":0,"bm":0}],"markers":[{"tm":-5940,"cm":"S:[false]","dr":0},{"tm":0.740234375,"cm":"FOCUSED -- TO SELECTION","dr":0}]}

View File

@ -1 +0,0 @@
{"v":"5.6.9","fr":60,"ip":0,"op":36,"w":120,"h":66,"nm":"开关动画-关闭","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"按钮手柄","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.667,"y":0},"t":0,"s":[87,33,0],"to":[7.682,0,0],"ti":[-13.443,0,0]},{"i":{"x":0.333,"y":1},"o":{"x":0.333,"y":0},"t":18,"s":[31,33,0],"to":[2.306,0,0],"ti":[-1.318,0,0]},{"t":24,"s":[33,33,0]}],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":0,"k":[16,16],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"椭圆路径 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"填充 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"椭圆形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":37,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"指示器-on","sr":1,"ks":{"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.667],"y":[0]},"t":0,"s":[100]},{"t":18,"s":[0]}],"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[33,33,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":1,"k":[{"i":{"x":[0.667,0.667],"y":[1,1]},"o":{"x":[0.667,0.667],"y":[0,0]},"t":0,"s":[6.5,6.5]},{"t":18,"s":[4.5,4.5]}],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"椭圆路径 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"st","c":{"a":0,"k":[0.966666666667,0.966666666667,0.966666666667,0.420000005762],"ix":3},"o":{"a":0,"k":40,"ix":4},"w":{"a":0,"k":1.5,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"描边 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"椭圆形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":37,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"指示器-off","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[87,33,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ty":"rc","d":1,"s":{"a":1,"k":[{"i":{"x":[0.667,0.667],"y":[1,1]},"o":{"x":[0.667,0.667],"y":[0,0]},"t":0,"s":[1.5,4]},{"t":18,"s":[1.5,6]}],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"r":{"a":0,"k":0.75,"ix":4},"nm":"矩形路径 1","mn":"ADBE Vector Shape - Rect","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0,0,1],"ix":4},"o":{"a":0,"k":5,"ix":5},"r":1,"bm":0,"nm":"填充 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":90,"ix":6},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.667],"y":[0]},"t":0,"s":[0]},{"t":18,"s":[100]}],"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"矩形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":37,"st":0,"bm":0},{"ddd":0,"ind":4,"ty":4,"nm":"按钮背景","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[60,33,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"sy":[{"c":{"a":0,"k":[0,0,0,1],"ix":2},"o":{"a":0,"k":5,"ix":3},"a":{"a":0,"k":120,"ix":5},"s":{"a":0,"k":1,"ix":8},"d":{"a":0,"k":0,"ix":6},"ch":{"a":0,"k":100,"ix":7},"bm":{"a":0,"k":5,"ix":1},"no":{"a":0,"k":0,"ix":9},"ty":2,"nm":"内阴影"}],"shapes":[{"ty":"gr","it":[{"ty":"rc","d":1,"s":{"a":0,"k":[40,22],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"r":{"a":0,"k":12,"ix":4},"nm":"矩形路径 1","mn":"ADBE Vector Shape - Rect","hd":false},{"ty":"fl","c":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.667],"y":[0]},"t":0,"s":[0.141176477075,0.588235318661,1,1]},{"t":18,"s":[0.933333337307,0.933333337307,0.933333337307,1]}],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"filling","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0.118,0.006],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"矩形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":37,"st":0,"bm":0}],"markers":[]}

View File

@ -1 +0,0 @@
{"v":"5.6.9","fr":60,"ip":0,"op":36,"w":120,"h":66,"nm":"开关动画-打开","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"按钮手柄","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.667,"y":0},"t":0,"s":[33,33,0],"to":[7.682,0,0],"ti":[-13.443,0,0]},{"i":{"x":0.333,"y":1},"o":{"x":0.333,"y":0},"t":18,"s":[89,33,0],"to":[2.306,0,0],"ti":[-1.318,0,0]},{"t":24,"s":[87,33,0]}],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":0,"k":[16,16],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"椭圆路径 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"填充 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"椭圆形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":37,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"指示器-on","sr":1,"ks":{"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.667],"y":[0]},"t":0,"s":[0]},{"t":18,"s":[100]}],"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[33,33,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":1,"k":[{"i":{"x":[0.667,0.667],"y":[1,1]},"o":{"x":[0.667,0.667],"y":[0,0]},"t":0,"s":[4.5,4.5]},{"t":18,"s":[6.5,6.5]}],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"椭圆路径 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"st","c":{"a":0,"k":[0.966666666667,0.966666666667,0.966666666667,0.420000005762],"ix":3},"o":{"a":0,"k":40,"ix":4},"w":{"a":0,"k":1.5,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"描边 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"椭圆形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":37,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"指示器-off","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[87,33,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ty":"rc","d":1,"s":{"a":1,"k":[{"i":{"x":[0.667,0.667],"y":[1,1]},"o":{"x":[0.667,0.667],"y":[0,0]},"t":0,"s":[1.5,6]},{"t":18,"s":[1.5,4]}],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"r":{"a":0,"k":0.75,"ix":4},"nm":"矩形路径 1","mn":"ADBE Vector Shape - Rect","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0,0,1],"ix":4},"o":{"a":0,"k":5,"ix":5},"r":1,"bm":0,"nm":"填充 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":90,"ix":6},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.667],"y":[0]},"t":0,"s":[100]},{"t":18,"s":[0]}],"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"矩形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":37,"st":0,"bm":0},{"ddd":0,"ind":4,"ty":4,"nm":"按钮背景","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[60,33,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"sy":[{"c":{"a":0,"k":[0,0,0,1],"ix":2},"o":{"a":0,"k":5,"ix":3},"a":{"a":0,"k":120,"ix":5},"s":{"a":0,"k":1,"ix":8},"d":{"a":0,"k":0,"ix":6},"ch":{"a":0,"k":100,"ix":7},"bm":{"a":0,"k":5,"ix":1},"no":{"a":0,"k":0,"ix":9},"ty":2,"nm":"内阴影"}],"shapes":[{"ty":"gr","it":[{"ty":"rc","d":1,"s":{"a":0,"k":[40,22],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"r":{"a":0,"k":12,"ix":4},"nm":"矩形路径 1","mn":"ADBE Vector Shape - Rect","hd":false},{"ty":"fl","c":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.667],"y":[0]},"t":0,"s":[0.933332979679,0.933332979679,0.933332979679,1]},{"t":18,"s":[0.141176477075,0.588235318661,1,1]}],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"filling","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0.118,0.006],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"矩形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":37,"st":0,"bm":0}],"markers":[]}

View File

@ -1 +0,0 @@
{"v":"5.6.9","fr":30,"ip":0,"op":20,"w":66,"h":66,"nm":"bottom bar tab/论坛/选中/E","ddd":0,"assets":[{"id":"comp_0","layers":[{"ddd":0,"ind":1,"ty":4,"nm":"白-修正","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[33,33,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":0,"s":[100,100,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":4,"s":[80,80,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":9,"s":[110,110,100]},{"t":13,"s":[100,100,100]}],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":1,"y":0},"t":0,"s":[{"i":[[0,-0.66],[0,0],[1.38,0],[0,1.38],[0,0],[-0.66,0],[0,0]],"o":[[0,0],[0,1.38],[-1.38,0],[0,0],[0,-0.66],[0,0],[0.66,0]],"v":[[2.5,-1.3],[2.5,0],[0,2.5],[-2.5,0],[-2.5,-1.3],[-1.3,-2.5],[1.3,-2.5]],"c":true}]},{"i":{"x":0,"y":1},"o":{"x":0.333,"y":0},"t":4,"s":[{"i":[[0,-0.66],[0,0],[1.38,0],[0,1.38],[0,0],[-0.66,0],[0,0]],"o":[[0,0],[0,1.38],[-1.38,0],[0,0],[0,-0.66],[0,0],[0.66,0]],"v":[[2.5,-0.102],[2.5,0],[0,2.109],[-2.5,0],[-2.5,-0.102],[-1.3,-1.302],[1.3,-1.302]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":1,"y":0},"t":9,"s":[{"i":[[0,-0.66],[0,0],[1.38,0],[0,1.38],[0,0],[-0.66,0],[0,0]],"o":[[0,0],[0,1.38],[-1.38,0],[0,0],[0,-0.66],[0,0],[0.66,0]],"v":[[2.498,-1.845],[2.5,0],[0,2.734],[-2.5,0],[-2.502,-1.845],[-1.302,-3.045],[1.298,-3.045]],"c":true}]},{"t":13,"s":[{"i":[[0,-0.66],[0,0],[1.38,0],[0,1.38],[0,0],[-0.66,0],[0,0]],"o":[[0,0],[0,1.38],[-1.38,0],[0,0],[0,-0.66],[0,0],[0.66,0]],"v":[[2.5,-1.3],[2.5,0],[0,2.5],[-2.5,0],[-2.5,-1.3],[-1.3,-2.5],[1.3,-2.5]],"c":true}]}],"ix":2},"nm":"路径 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"填充 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"矩形","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":150,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"蓝","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[33,33.76,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-1.8,0.42],[-3.44,-0.79],[-0.09,-1.71],[0,0],[0,0],[1.98,-0.1],[0,0],[0,0],[0,0],[0.62,0.57],[0,0],[0,0],[0,0],[0,0],[0,0],[0.2,1.89],[0,0],[0,0],[0,0]],"o":[[3.44,-0.79],[1.74,0.41],[0,0],[0,0],[0,2],[0,0],[0,0],[0,0],[-0.69,0.52],[0,0],[0,0],[0,0],[0,0],[0,0],[-1.94,0],[0,0],[0,0],[0,0],[0,-1.8]],"v":[[-6.39,-8.971],[6.39,-8.971],[9.49,-5.471],[9.5,-5.271],[9.5,3.249],[5.95,6.989],[5.75,6.999],[3.25,6.999],[0.3,9.209],[-1.95,9.089],[-2.06,8.969],[-2.17,8.849],[-2.21,8.779],[-3.4,6.999],[-5.75,6.999],[-9.48,3.639],[-9.49,3.449],[-9.5,3.249],[-9.5,-5.271]],"c":true},"ix":2},"nm":"路径 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"gf","o":{"a":0,"k":100,"ix":10},"r":1,"bm":0,"g":{"p":3,"k":{"a":0,"k":[0,0.266,0.638,1,0.5,0.242,0.595,1,1,0.217,0.552,1],"ix":9}},"s":{"a":0,"k":[-9.5,-9.561],"ix":5},"e":{"a":0,"k":[9.5,9.561],"ix":6},"t":1,"nm":"color","mn":"ADBE Vector Graphic - G-Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[300,300],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"变换"}],"nm":"路径","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":150,"st":0,"bm":0}]}],"layers":[{"ddd":0,"ind":1,"ty":0,"nm":"预合成 1","refId":"comp_0","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[33,33,0],"ix":2},"a":{"a":0,"k":[33,33,0],"ix":1},"s":{"a":1,"k":[{"i":{"x":[0.833,0.833,0.833],"y":[0.833,0.833,0.833]},"o":{"x":[0.167,0.167,0.167],"y":[0.167,0.167,0.167]},"t":0,"s":[100,100,100]},{"i":{"x":[0.833,0.833,0.833],"y":[0.833,0.833,0.833]},"o":{"x":[0.167,0.167,0.167],"y":[0.167,0.167,0.167]},"t":4,"s":[70,70,100]},{"i":{"x":[0.833,0.833,0.833],"y":[0.833,0.833,0.833]},"o":{"x":[0.167,0.167,0.167],"y":[0.167,0.167,0.167]},"t":9,"s":[110,110,100]},{"i":{"x":[0.833,0.833,0.833],"y":[0.833,0.833,0.833]},"o":{"x":[0.167,0.167,0.167],"y":[0.167,0.167,0.167]},"t":13,"s":[90,90,100]},{"t":16,"s":[100,100,100]}],"ix":6}},"ao":0,"w":66,"h":66,"ip":0,"op":20,"st":0,"bm":0}],"markers":[]}

View File

@ -0,0 +1,5 @@
# This is a simple Microlog configuration file
microlog.level=DEBUG
microlog.appender=LogCatAppender;FileAppender
microlog.formatter=PatternFormatter
microlog.formatter.PatternFormatter.pattern=%c [%P] %m %T

View File

@ -1,132 +0,0 @@
[
{
"login": {
"title": "开启消息通知",
"content": "新游上线、互动回复,重要推送不错过",
"image": "bg_notification_login_style_1",
"styleNo": "样式A",
"scenes": "场景1"
},
"question": {
"title": "开启消息通知",
"content": "及时查看大神回答",
"image": "bg_notification_question_style_1",
"styleNo": "样式A",
"scenes": "场景2"
},
"answer": {
"title": "开启消息通知",
"content": "及时查看点赞与评论",
"image": "bg_notification_answer_style_1",
"styleNo": "样式A",
"scenes": "场景3"
},
"article": {
"title": "开启消息通知",
"content": "及时查看点赞与评论",
"image": "bg_notification_article_style_1",
"styleNo": "样式A",
"scenes": "场景4"
},
"video": {
"title": "开启消息通知",
"content": "实时获取审核与推荐进度",
"image": "bg_notification_video_style_1",
"styleNo": "样式A",
"scenes": "场景5"
},
"rating": {
"title": "开启消息通知",
"content": "成功上墙立即知道",
"image": "bg_notification_rating_style_1",
"styleNo": "样式A",
"scenes": "场景6"
},
"gift": {
"title": "开启消息通知",
"content": "新上礼包不再错过",
"image": "bg_notification_gift_style_1",
"styleNo": "样式A",
"scenes": "场景7"
},
"reserveGame": {
"title": "开启消息通知",
"content": "新游上线即时体验",
"image": "bg_notification_reserve_game_style_1",
"styleNo": "样式A",
"scenes": "场景8"
},
"feedback": {
"title": "开启消息通知",
"content": "及时查看客服回复",
"image": "bg_notification_feedback_style_1",
"styleNo": "样式A",
"scenes": "场景9"
}
},
{
"login": {
"title": "咦!是新的小伙伴耶!",
"content": "打开<font color=\"#1383EB\">通知开关</font>,游戏、礼包、抽奖活动不错过",
"image": "bg_notification_login_style_2",
"styleNo": "样式B",
"scenes": "场景1"
},
"question": {
"title": "发布成功!答案马上来!",
"content": "为了第一时间通知您,需要打开<font color=\"#1383EB\">通知开关</font>",
"image": "bg_notification_question_style_2",
"styleNo": "样式B",
"scenes": "场景2"
},
"answer": {
"title": "精彩的回答!大佬牛啤!",
"content": "打开<font color=\"#1383EB\">通知开关</font>,可以第一时间收获赞美和感谢哟!",
"image": "bg_notification_answer_style_2",
"styleNo": "样式B",
"scenes": "场景3"
},
"article": {
"title": "发布成功!不愧是你!",
"content": "打开<font color=\"#1383EB\">通知开关</font>,可以第一时间收获赞美和互动哟!",
"image": "bg_notification_article_style_2",
"styleNo": "样式B",
"scenes": "场景4"
},
"video": {
"title": "“百万”播放预定!",
"content": "<font color=\"#1383EB\">打开通知!</font>第一时间知道审核结果和互动信息哟!",
"image": "bg_notification_video_style_2",
"styleNo": "样式B",
"scenes": "场景5"
},
"rating": {
"title": "这游戏超好玩,我说的!",
"content": "想知道有多少人吃下安利?<font color=\"#1383EB\">打开通知</font>,马上知道!",
"image": "bg_notification_rating_style_2",
"styleNo": "样式B",
"scenes": "场景6"
},
"gift": {
"title": "获得道具:神奇的游戏礼包!",
"content": "<font color=\"#1383EB\">打开通知!</font>礼包上线,马上知道!",
"image": "bg_notification_gift_style_2",
"styleNo": "样式B",
"scenes": "场景7"
},
"reserveGame": {
"title": "玩最新的游戏,做游戏圈最靓的仔",
"content": "<font color=\"#1383EB\">打开通知!</font>游戏上线,更快知道!",
"image": "bg_notification_reserve_game_style_2",
"styleNo": "样式B",
"scenes": "场景8"
},
"feedback": {
"title": "真是重要的反馈!",
"content": "感恩有你,光环更精彩!<font color=\"#1383EB\">打开通知</font>,客服回复,马上知道!",
"image": "bg_notification_feedback_style_2",
"styleNo": "样式B",
"scenes": "场景9"
}
}
]

File diff suppressed because it is too large Load Diff

View File

@ -280,8 +280,12 @@ RE.replaceAllDfImage = function(imgRuleFlag, gifRuleFlag) {
i--;
} else {
if(img.src.indexOf(".gif") > 0) {
img.src = img.src.split("?")[0] + gifRuleFlag
if(gifRuleFlag.indexOf(",default") > 0) {
img.style.cssText = "max-width: 100%; display:block; margin:8px auto; height: auto;"
img.src = img.src.split("?")[0] + gifRuleFlag
}
} else {
img.style.cssText = "max-width: 100%; display:block; margin:8px auto; height: auto;"
img.src = img.src.split("?")[0] + imgRuleFlag
}
}
@ -297,7 +301,7 @@ RE.hideShowBigPic = function() {
var img = imgs[i];
var imageClassName = img.className;
if (imageClassName == "image-link" || img.className == "poster") continue;
if (img.src.indexOf(".gif") == -1) {
if(img.src.indexOf(",thumbnail") > 0 && img.src.indexOf(".gif") == -1) {
j++;
}
}
@ -323,6 +327,7 @@ RE.replaceDfImageByUrl = function(imgUrl, imgRuleFlag, gifRuleFlag) {
var imageClassName = img.className;
if (imageClassName == "image-link" || img.className == "poster") continue;
if (img.src.indexOf(imgUrl) != -1) {
img.style.cssText = "max-width: 100%; display:block; margin:8px auto; height: auto;"
if(img.src.indexOf(".gif") > 0) {
img.src = img.src.split("?")[0] + gifRuleFlag
} else {
@ -612,25 +617,3 @@ RE.sendElementNameToNative = function() {
}
}
}
// android function to open link
function customLinkgo(self) {
var datas = self.dataset.datas
// console.log(datas)
window.OnLinkClickListener.onClick(datas)
}
// 在web页面播放视频
//RE.initArticleVideo = function(){
// initArticleVideo()
//}
function showNativeDialog(title, message, positive, negative, callback) {
var jsCallbackCode = "(" + function (v) {
window.onNativeDialogCallback(v);
delete window.onNativeDialogCallback;
}.toString() + ")";
window.onNativeDialogCallback = callback;
window.NativeCallBack.showDialog(title, message, positive, negative, jsCallbackCode);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@ -1,159 +0,0 @@
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.swiperefreshlayout.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
/**
* Private class created to work around issues with AnimationListeners being
* called before the animation is actually complete and support shadows on older
* platforms.
*/
class CircleImageView extends ImageView {
private static final int KEY_SHADOW_COLOR = 0x1E000000;
private static final int FILL_SHADOW_COLOR = 0x3D000000;
// PX
private static final float X_OFFSET = 0f;
private static final float Y_OFFSET = 1.75f;
private static final float SHADOW_RADIUS = 3.5f;
private static final int SHADOW_ELEVATION = 4;
private Animation.AnimationListener mListener;
int mShadowRadius;
CircleImageView(Context context, int color) {
super(context);
final float density = getContext().getResources().getDisplayMetrics().density;
final int shadowYOffset = (int) (density * Y_OFFSET);
final int shadowXOffset = (int) (density * X_OFFSET);
mShadowRadius = (int) (density * SHADOW_RADIUS);
ShapeDrawable circle;
if (elevationSupported()) {
circle = new ShapeDrawable(new OvalShape());
ViewCompat.setElevation(this, SHADOW_ELEVATION * density);
} else {
OvalShape oval = new OvalShadow(mShadowRadius);
circle = new ShapeDrawable(oval);
setLayerType(View.LAYER_TYPE_SOFTWARE, circle.getPaint());
circle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset,
KEY_SHADOW_COLOR);
final int padding = mShadowRadius;
// set padding so the inner image sits correctly within the shadow.
setPadding(padding, padding, padding, padding);
}
circle.getPaint().setColor(color);
ViewCompat.setBackground(this, circle);
}
private boolean elevationSupported() {
return android.os.Build.VERSION.SDK_INT >= 21;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!elevationSupported()) {
setMeasuredDimension(getMeasuredWidth() + mShadowRadius * 2, getMeasuredHeight()
+ mShadowRadius * 2);
}
}
public void setAnimationListener(Animation.AnimationListener listener) {
mListener = listener;
}
@Override
public void onAnimationStart() {
super.onAnimationStart();
if (mListener != null) {
mListener.onAnimationStart(getAnimation());
}
}
@Override
public void onAnimationEnd() {
super.onAnimationEnd();
if (mListener != null) {
mListener.onAnimationEnd(getAnimation());
}
}
/**
* Update the background color of the circle image view.
*
* @param colorRes Id of a color resource.
*/
public void setBackgroundColorRes(int colorRes) {
setBackgroundColor(ContextCompat.getColor(getContext(), colorRes));
}
@Override
public void setBackgroundColor(int color) {
if (getBackground() instanceof ShapeDrawable) {
((ShapeDrawable) getBackground()).getPaint().setColor(color);
}
}
private class OvalShadow extends OvalShape {
private RadialGradient mRadialGradient;
private Paint mShadowPaint;
OvalShadow(int shadowRadius) {
super();
mShadowPaint = new Paint();
mShadowRadius = shadowRadius;
updateRadialGradient((int) rect().width());
}
@Override
protected void onResize(float width, float height) {
super.onResize(width, height);
updateRadialGradient((int) width);
}
@Override
public void draw(Canvas canvas, Paint paint) {
final int viewWidth = CircleImageView.this.getWidth();
final int viewHeight = CircleImageView.this.getHeight();
canvas.drawCircle(viewWidth / 2, viewHeight / 2, viewWidth / 2, mShadowPaint);
canvas.drawCircle(viewWidth / 2, viewHeight / 2, viewWidth / 2 - mShadowRadius, paint);
}
private void updateRadialGradient(int diameter) {
mRadialGradient = new RadialGradient(diameter / 2, diameter / 2,
mShadowRadius, new int[] { FILL_SHADOW_COLOR, Color.TRANSPARENT },
null, Shader.TileMode.CLAMP);
mShadowPaint.setShader(mRadialGradient);
}
}
}

View File

@ -1,58 +0,0 @@
package androidx.swiperefreshlayout.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
public class ViewPagerSwipeRefreshLayout extends SwipeRefreshLayout {
private float startY;
private float startX;
// 记录viewPager是否拖拽的标记
private boolean mIsVpDragger;
private final int mTouchSlop;
public ViewPagerSwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// 记录手指按下的位置
startY = ev.getY();
startX = ev.getX();
// 初始化标记
mIsVpDragger = false;
break;
case MotionEvent.ACTION_MOVE:
// 如果viewpager正在拖拽中那么不拦截它的事件直接return false
if(mIsVpDragger) {
return false;
}
// 获取当前手指位置
float endY = ev.getY();
float endX = ev.getX();
float distanceX = Math.abs(endX - startX);
float distanceY = Math.abs(endY - startY);
// 如果X轴位移大于Y轴位移那么将事件交给viewPager处理。
if(distanceX > mTouchSlop && distanceX > distanceY) {
mIsVpDragger = true;
return false;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// 初始化标记
mIsVpDragger = false;
break;
}
// 如果是Y轴位移大于X轴事件交给swipeRefreshLayout处理。
return super.onInterceptTouchEvent(ev);
}
}

View File

@ -5,7 +5,6 @@ import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
@ -26,9 +25,6 @@ import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeoutException;
import io.sentry.Sentry;
public class AppUncaughtHandler implements UncaughtExceptionHandler {
@ -40,26 +36,20 @@ public class AppUncaughtHandler implements UncaughtExceptionHandler {
}
@Override
public void uncaughtException(Thread t, Throwable e) {
if (("FinalizerWatchdogDaemon").equals(t.getName())
&& e instanceof TimeoutException) {
// ignore timeoutException
// detail can be found in this didi tech blog post https://mp.weixin.qq.com/s?__biz=MzU1ODEzNjI2NA==&mid=2247487185&idx=2&sn=cf2d9e10053f625bde0f61d246f14870&source=41#wechat_redirect
} else {
new Thread(() -> {
public void uncaughtException(Thread thread, Throwable ex) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Utils.toast(mContext.getApplicationContext(), "\"光环助手\"发生错误");
Looper.loop();
});
saveLocalLog(mContext, e);
restart(mContext);
Sentry.captureException(e);
}
}
});
saveLocalLog(mContext, ex);
restart(mContext);
}
public static void restart(final Context context) {
// S450 这机器会无限重启循环 : (
if ("S450".equals(Build.MODEL)) return;
// 防止重复奔溃导致助手一直重启20秒内不做处理
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

View File

@ -1,63 +1,26 @@
package com.gh.base;
import static com.gh.common.util.EntranceUtils.KEY_ENTRANCE;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.TransactionTooLargeException;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.content.ContextCompat;
import androidx.core.view.LayoutInflaterCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import com.gh.base.fragment.BaseFragment;
import com.gh.common.constant.Constants;
import com.gh.common.tracker.IBusiness;
import com.gh.common.util.DialogHelper;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.EntranceUtils;
import com.gh.common.util.EnvHelper;
import com.gh.common.util.ExtensionsKt;
import com.gh.common.util.MtaHelper;
import com.gh.common.util.NetworkUtils;
import com.gh.common.util.NightModeUtils;
import com.gh.common.util.PackageFlavorHelper;
import com.gh.common.util.PackageInstaller;
import com.gh.common.util.QuickLoginHelper;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.RunningUtils;
import com.gh.common.util.SPUtils;
import com.gh.common.util.ShareUtils;
import com.gh.common.util.StringUtils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.BuildConfig;
import com.gh.gamecenter.LoginActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.SplashScreenActivity;
import com.gh.gamecenter.eventbus.EBShowDialog;
import com.lightgame.BaseAppCompatActivity;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.FileUtils;
import com.lightgame.utils.Utils;
import com.tencent.tauth.Tencent;
@ -70,32 +33,30 @@ import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.List;
import kotlin.Pair;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.EasyPermissions;
import static com.gh.common.util.EntranceUtils.KEY_ENTRANCE;
/**
* 只提供基础的服务(EventBus/Share/GlobalDialog/Permissions)
* 只提供基础的服务(EventBus/ButterKnife/Share/GlobalDialog/Permissions)
* <p>
* 需要工具栏的页面请继承{@link ToolBarActivity}
*/
public abstract class BaseActivity extends BaseAppCompatActivity implements EasyPermissions.PermissionCallbacks, IBusiness {
public abstract class BaseActivity extends BaseAppCompatActivity implements EasyPermissions.PermissionCallbacks {
// global dialog key
public final static String DOWNLOAD_HIJACK = "hijack";
public final static String LOGIN_EXCEPTION = "loginException";
public final static String PLUGGABLE = "plugin";
public final static String SIGNATURE_CONFLICT = "signature_conflict";
public final static int ID_ROOT_INDICATOR = 999;
public final static int ID_NIGHT_INDICATOR = 998;
public final int MAX_BUNDLE_SIZE = 300;
@NonNull
protected String mEntrance;
private boolean mIsExistLogoutDialog;
protected boolean mNightMode;
public long startPageTime = 0;
protected final Handler mBaseHandler = new BaseHandler(this);
@ -123,24 +84,17 @@ public abstract class BaseActivity extends BaseAppCompatActivity implements Easy
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ExtensionsKt.tryCatchInRelease(() -> {
if (requestCode == com.tencent.connect.common.Constants.REQUEST_QQ_SHARE
|| requestCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE) {
Tencent.onActivityResultData(requestCode, resultCode, data, ShareUtils.getInstance(this).QqShareListener);
}
return null;
});
if (requestCode == com.tencent.connect.common.Constants.REQUEST_QQ_SHARE
|| requestCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE) {
Tencent.onActivityResultData(requestCode, resultCode, data, ShareUtils.getInstance(this).QqShareListener);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if (PackageFlavorHelper.IS_TEST_FLAVOR && isAutoResetViewBackgroundEnabled()) {
LayoutInflaterCompat.setFactory2(getLayoutInflater(), new CustomLayoutInflaterFactory(this));
}
super.onCreate(savedInstanceState);
if (useEventBus()) EventBus.getDefault().register(this);
EventBus.getDefault().register(this);
ButterKnife.bind(this);
mEntrance = getIntent().getStringExtra(KEY_ENTRANCE);
if (TextUtils.isEmpty(mEntrance)) {
mEntrance = Constants.ENTRANCE_UNKNOWN;
@ -149,55 +103,11 @@ public abstract class BaseActivity extends BaseAppCompatActivity implements Easy
if (BuildConfig.DEBUG) {
Utils.log("ACTIVITY_ENTRANCE -> " + mEntrance);
}
disableAutofill();
if (savedInstanceState != null) {
String xapkUnzipActivity = SPUtils.getString(Constants.SP_XAPK_UNZIP_ACTIVITY);
String xapkUrl = SPUtils.getString(Constants.SP_XAPK_URL);
Utils.log("页面重建了--" + xapkUnzipActivity + "--" + xapkUrl);
if (this.getClass().isAssignableFrom(SplashScreenActivity.class)) {
SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "");
SPUtils.setString(Constants.SP_XAPK_URL, "");
return;
}
if (this.getClass().getName().equals(xapkUnzipActivity) && !TextUtils.isEmpty(xapkUrl)) {
DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntityByUrl(xapkUrl);
if (downloadEntity != null) {
PackageInstaller.install(this, downloadEntity, false);
SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "");
SPUtils.setString(Constants.SP_XAPK_URL, "");
}
}
}
mNightMode = NightModeUtils.INSTANCE.isNightMode(this);
}
@Override
protected void onResume() {
super.onResume();
startPageTime = System.currentTimeMillis();
if (BuildConfig.IS_NIGHT_MODE_ON
&& !NightModeUtils.INSTANCE.getSystemMode()
&& mNightMode != NightModeUtils.INSTANCE.isNightMode(this)) {
onNightModeChange();
}
}
@SuppressWarnings("ConstantConditions")
@Override
public void setContentView(View view) {
if (!(this instanceof SplashScreenActivity) && PackageFlavorHelper.IS_TEST_FLAVOR) {
view = getRootViewWithEnvIndicator(view);
}
super.setContentView(view);
}
@Override
protected void onDestroy() {
if (useEventBus()) EventBus.getDefault().unregister(this);
EventBus.getDefault().unregister(this);
mBaseHandler.removeCallbacksAndMessages(null);
super.onDestroy();
}
@ -214,150 +124,21 @@ public abstract class BaseActivity extends BaseAppCompatActivity implements Easy
String icon,
String shareTitle,
String shareSummary,
ShareUtils.ShareEntrance shareEntrance, String id) {
ShareUtils.ShareType shareType) {
ShareUtils.getInstance(this).showShareWindows(this,
getWindow().getDecorView(),
url,
icon,
shareTitle,
shareSummary,
shareEntrance, id);
if (shareEntrance == ShareUtils.ShareEntrance.game || shareEntrance == ShareUtils.ShareEntrance.plugin) {
shareType);
if (shareType == ShareUtils.ShareType.game || shareType == ShareUtils.ShareType.plugin) {
MtaHelper.onEvent("内容分享", "内容分享", shareTitle + shareSummary);
} else {
MtaHelper.onEvent("内容分享", "内容分享", shareTitle);
}
}
/**
* 关闭 editText 自动填充帐号 (我们也用不上),开启的时候有小概率出发 TimeoutException
*/
private void disableAutofill() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getWindow().getDecorView().setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
}
}
private View getRootViewWithEnvIndicator(View view) {
RelativeLayout screenRootView = new RelativeLayout(this);
screenRootView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
LinearLayout ll = new LinearLayout(this);
TextView tv = new TextView(this);
String envText = "正式环境";
tv.setBackground(ContextCompat.getDrawable(this, R.color.theme));
if (EnvHelper.isDevEnv()) {
envText = "测试环境";
tv.setBackground(ContextCompat.getDrawable(this, R.color.theme_red));
}
tv.setText(envText);
tv.setGravity(Gravity.CENTER);
tv.setTextColor(Color.WHITE);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
tv.measure(0, 0);
tv.setAlpha(0.15F);
tv.setId(ID_ROOT_INDICATOR);
int height = tv.getMeasuredHeight();
int width = tv.getMeasuredWidth();
tv.setPadding(DisplayUtils.dip2px(20), 0, DisplayUtils.dip2px(20), 0);
ll.setTranslationX(DisplayUtils.dip2px(20));
ll.setRotation(45);
ll.addView(tv);
ll.setPadding(0, (width - height) / 2, 0, (width - height) / 2);
if (BuildConfig.DEBUG) {
tv.setOnLongClickListener(v -> {
EntranceUtils.saveShortcut(this.getClass().getName(), getIntent().getExtras());
return true;
});
}
screenRootView.addView(view);
screenRootView.addView(ll);
if (BuildConfig.IS_NIGHT_MODE_ON) {
screenRootView.addView(getNightModeIndicatorView());
}
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) ll.getLayoutParams();
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
return screenRootView;
}
private View getNightModeIndicatorView() {
LinearLayout ll = new LinearLayout(this);
TextView tv = new TextView(this);
String envText = NightModeUtils.INSTANCE.isNightMode(this) ? "夜间模式" : "日间模式";
tv.setBackground(ContextCompat.getDrawable(this, R.color.theme));
tv.setText(envText);
tv.setGravity(Gravity.CENTER);
tv.setTextColor(Color.WHITE);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
tv.measure(0, 0);
tv.setAlpha(NightModeUtils.INSTANCE.isNightMode(this) ? 0.8F : 0.15F);
tv.setId(ID_NIGHT_INDICATOR);
int height = tv.getMeasuredHeight();
int width = tv.getMeasuredWidth();
tv.setPadding(DisplayUtils.dip2px(20), 0, DisplayUtils.dip2px(20), 0);
ll.setTranslationX(DisplayUtils.dip2px(-20));
ll.setRotation(-45);
ll.addView(tv);
ll.setPadding(0, (width - height) / 2, 0, (width - height) / 2);
if (PackageFlavorHelper.IS_TEST_FLAVOR) {
tv.setOnClickListener(v -> {
//切换深色模式
String mode;
String positive;
String negative;
if (NightModeUtils.INSTANCE.getSystemMode()) {
mode = "跟随系统模式";
positive = "普通模式";
negative = "深色模式";
} else if (NightModeUtils.INSTANCE.getNightMode()) {
mode = "深色模式";
positive = "跟随系统模式";
negative = "普通模式";
} else {
mode = "普通模式";
positive = "跟随系统模式";
negative = "深色模式";
}
DialogHelper.showCenterDialog(this, "选择模式", "当前为 " + mode, positive, negative, () -> {
if (NightModeUtils.INSTANCE.getSystemMode()) {
NightModeUtils.INSTANCE.setNightMode(false);
NightModeUtils.INSTANCE.setSystemMode(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
} else {
NightModeUtils.INSTANCE.setSystemMode(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
}
NightModeUtils.INSTANCE.initNightMode();
}, () -> {
if (NightModeUtils.INSTANCE.getSystemMode()) {
NightModeUtils.INSTANCE.setNightMode(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
} else {
boolean nightMode = NightModeUtils.INSTANCE.getNightMode();
NightModeUtils.INSTANCE.setNightMode(!NightModeUtils.INSTANCE.getNightMode());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getDelegate().setLocalNightMode(nightMode ? AppCompatDelegate.MODE_NIGHT_NO : AppCompatDelegate.MODE_NIGHT_YES);
}
}
NightModeUtils.INSTANCE.setSystemMode(false);
NightModeUtils.INSTANCE.initNightMode();
});
});
}
return ll;
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(final EBShowDialog showDialog) {
if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)
@ -365,18 +146,12 @@ public abstract class BaseActivity extends BaseAppCompatActivity implements Easy
if (DOWNLOAD_HIJACK.equals(showDialog.getType())) {
DialogUtils.showQqSessionDialog(this);// 建议用户联系客服
} else if (PLUGGABLE.equals(showDialog.getType())) {
DialogHelper.showPluginDialog(this, () -> {
DialogUtils.showPluginDialog(this, () -> {
if (FileUtils.isEmptyFile(showDialog.getPath())) {
toast(R.string.install_failure_hint);
} else {
PackageInstaller.uninstall(BaseActivity.this, showDialog.getPath());
startActivity(PackageUtils.getUninstallIntent(BaseActivity.this, showDialog.getPath()));
}
return null;
});
} else if (SIGNATURE_CONFLICT.equals(showDialog.getType())) {
DialogHelper.showSignatureConflictDialog(this, () -> {
PackageInstaller.uninstall(BaseActivity.this, showDialog.getPath());
return null;
});
} else if (LOGIN_EXCEPTION.equals(showDialog.getType())) {
if (mIsExistLogoutDialog) return;
@ -385,19 +160,12 @@ public abstract class BaseActivity extends BaseAppCompatActivity implements Easy
JSONObject object = new JSONObject(showDialog.getPath());
JSONObject device = object.getJSONObject("device");
String model = device.getString("model");
DialogHelper.showCenterDialog(this, "你的账号已在另外一台设备登录"
DialogUtils.showAlertDialog(this, "你的账号已在另外一台设备登录"
, StringUtils.buildString("", model, "")
, "知道了", "重新登录"
, () -> {
}
, () -> {
if (SPUtils.getBoolean(Constants.SP_HAS_GET_PHONE_INFO) || NetworkUtils.isOpenMobileData(BaseActivity.this)) {
QuickLoginHelper.startLogin(BaseActivity.this, "你的账号已在另外一台设备登录多设备-重新登录");
} else {
startActivity(LoginActivity.getIntent(BaseActivity.this,
"你的账号已在另外一台设备登录多设备-重新登录"));
}
}
, null
, () -> startActivity(LoginActivity.getIntent(BaseActivity.this,
"你的账号已在另外一台设备登录多设备-重新登录"))
);
mBaseHandler.postDelayed(() -> mIsExistLogoutDialog = false, 5000);
} catch (Exception e) {
@ -410,22 +178,11 @@ public abstract class BaseActivity extends BaseAppCompatActivity implements Easy
@Override
protected void onPause() {
super.onPause();
if (isFinishing()) {
onFinish();
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
if (fragment.isAdded() && fragment instanceof BaseFragment) {
((BaseFragment) fragment).onParentActivityFinish();
}
}
}
}
/**
* 此回调可用于确认当前 activity 已经执行了 finish() 方法并处于 isFinishing 状态
*/
protected void onFinish() {
@Override
protected void onResume() {
super.onResume();
}
@Override
@ -478,152 +235,4 @@ public abstract class BaseActivity extends BaseAppCompatActivity implements Easy
return StringUtils.buildString(entrance, "+(", path, ")");
}
protected boolean useEventBus() {
return true;
}
@Override
public Resources getResources() {
Resources resources = super.getResources();
if (resources.getConfiguration().fontScale != 1.0f) {
Configuration configuration = resources.getConfiguration();
configuration.fontScale = 1.0f;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}
return resources;
}
/**
* ActivityThread每次调用onSaveInstanceState时outState大小都会累加最终会导致{@link TransactionTooLargeException}异常
* 解决方案判断每次获取到的outState大小当达到300k时手动clear掉
*/
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (preventRecreateFragmentByFragmentManager()) {
outState = discardFragmentFromSaveInstanceState(outState);
}
long bundleSize = getBundleSize(outState);
if (bundleSize > MAX_BUNDLE_SIZE * 1024) {
outState.clear();
}
}
/**
* 是否停用 Activity 重建时 FragmentManager 根据 saveState 自动重建保存的 Fragment 的功能
*/
protected boolean preventRecreateFragmentByFragmentManager() {
return false;
}
private Bundle discardFragmentFromSaveInstanceState(Bundle outState) {
if (outState != null) {
outState.remove("android:support:fragments");
}
return outState;
}
private long getBundleSize(Bundle bundle) {
long dataSize;
Parcel obtain = Parcel.obtain();
try {
obtain.writeBundle(bundle);
dataSize = obtain.dataSize();
} finally {
obtain.recycle();
}
return dataSize;
}
@Override
public Pair<String, String> getBusinessId() {
return null;
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
onNightModeChange();
}
protected void onNightModeChange() {
if (BuildConfig.IS_NIGHT_MODE_ON) {
mNightMode = NightModeUtils.INSTANCE.isNightMode(this);
TextView tv = findViewById(ID_NIGHT_INDICATOR);
if (tv != null) {
tv.setText(NightModeUtils.INSTANCE.isNightMode(this) ? "夜间模式" : "日间模式");
tv.setAlpha(NightModeUtils.INSTANCE.isNightMode(this) ? 0.8F : 0.15F);
}
if (isAutoResetViewBackgroundEnabled()) {
updateStaticViewBackground(getWindow().getDecorView());
}
}
}
protected boolean isAutoResetViewBackgroundEnabled() {
return false;
}
/**
* 自动重置部分 view 的背景颜色/资源
*
* @param view 父 view
*/
private void updateStaticViewBackground(View view) {
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View child = ((ViewGroup) view).getChildAt(i);
updateStaticViewBackground(child);
}
}
String backgroundString = (String) view.getTag(CustomLayoutInflaterFactory.TAG_BACKGROUND_ID);
String textColorString = (String) view.getTag(CustomLayoutInflaterFactory.TAG_TEXT_COLOR_ID);
if (backgroundString != null) {
if (backgroundString.startsWith("#")) return;
int backgroundId = Integer.parseInt(
backgroundString
.replace("@", "")
.replace("?", "")
);
if (backgroundId != 0) {
try {
TypedValue value = new TypedValue();
getResources().getValue(backgroundId, value, true);
if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
view.setBackgroundColor(ExtensionsKt.toColor(backgroundId, this));
} else {
view.setBackground(ExtensionsKt.toDrawable(backgroundId, this));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (textColorString != null && view instanceof TextView) {
if (textColorString.startsWith("#")) return;
int textColorId = Integer.parseInt(
textColorString
.replace("@", "")
.replace("?", "")
);
if (textColorId != 0) {
try {
final ColorStateList colorStateList = ContextCompat.getColorStateList(this, textColorId);
((TextView) view).setTextColor(colorStateList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -4,8 +4,11 @@ import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.gh.base.adapter.FragmentAdapter;
import com.gh.base.fragment.BaseFragment_TabLayout;
import com.gh.common.view.TabIndicatorView;
import com.gh.gamecenter.R;
import com.google.android.material.tabs.TabLayout;
@ -14,10 +17,7 @@ import com.lightgame.view.NoScrollableViewPager;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
/**
* Created by khy on 15/03/18.
@ -27,10 +27,12 @@ public abstract class BaseActivity_TabLayout extends ToolBarActivity implements
public static final String PAGE_INDEX = "PAGE_INDEX";
@BindView(R.id.activity_tab_layout)
protected TabLayout mTabLayout;
@BindView(R.id.activity_view_pager)
protected NoScrollableViewPager mViewPager;
@BindView(R.id.activity_tab_indicator)
protected TabIndicatorView mTabIndicatorView;
protected View mDividerLineView;
protected List<Fragment> mFragmentsList;
@ -43,7 +45,7 @@ public abstract class BaseActivity_TabLayout extends ToolBarActivity implements
protected abstract void initTabTitleList(List<String> tabTitleList);
protected int provideIndicatorWidth() {
return 20;
return 65;
}
protected View provideTabView(int position, String tabTitle) {
@ -69,20 +71,11 @@ public abstract class BaseActivity_TabLayout extends ToolBarActivity implements
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTabLayout = findViewById(R.id.activity_tab_layout);
mViewPager = findViewById(R.id.activity_view_pager);
mTabIndicatorView = findViewById(R.id.activity_tab_indicator);
mDividerLineView = findViewById(R.id.dividerLine);
if (getIntent() != null) mCheckedIndex = getIntent().getIntExtra(PAGE_INDEX, 0);
mFragmentsList = new ArrayList<>();
initFragmentList(mFragmentsList);
mTabTitleList = new ArrayList<>();
initTabTitleList(mTabTitleList);
mFragmentsList = new ArrayList<>(restoreFragments());
if (mFragmentsList.isEmpty() || mFragmentsList.size() != mTabTitleList.size()) {
mFragmentsList.clear();
initFragmentList(mFragmentsList);
}
mViewPager.setOffscreenPageLimit(mFragmentsList.size());
mViewPager.addOnPageChangeListener(this);
@ -96,28 +89,11 @@ public abstract class BaseActivity_TabLayout extends ToolBarActivity implements
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
if (tab == null) continue;
String tabTitle = tab.getText() != null ? tab.getText().toString() : "";
View tabView = provideTabView(i, tabTitle);
if (tabView == null)
tabView = BaseFragment_TabLayout.createDefaultTabCustomView(this, tabTitle);
View tabView = provideTabView(i, tab.getText() != null ? tab.getText().toString() : "");
if (tabView == null) continue;
tab.setCustomView(tabView);
}
BaseFragment_TabLayout.initTabStyle(mTabLayout, mCheckedIndex);
}
private ArrayList<Fragment> restoreFragments() {
String tag = "android:switcher:" + mViewPager.getId() + ":";
ArrayList<Fragment> fragments = new ArrayList<>();
int childCount = mTabTitleList.size();
for (int index = 0; index < childCount; index++) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag + index);
if (fragment != null) {
fragments.add(fragment);
}
}
return fragments;
}
@Override
@ -134,22 +110,4 @@ public abstract class BaseActivity_TabLayout extends ToolBarActivity implements
public void onPageScrollStateChanged(int state) {
}
@Override
protected void onNightModeChange() {
super.onNightModeChange();
View container = findViewById(R.id.activity_tab_container);
if (container != null) {
container.setBackgroundColor(ContextCompat.getColor(this, R.color.background_white));
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
if (tab != null) {
BaseFragment_TabLayout.updateTabStyle(tab, tab.isSelected());
}
}
}
if (mDividerLineView != null) {
mDividerLineView.setBackgroundColor(ContextCompat.getColor(this, R.color.divider));
}
}
}

View File

@ -3,6 +3,8 @@ package com.gh.base;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import butterknife.ButterKnife;
/**
* 目前仅提供butterknife bind方法
*
@ -18,6 +20,7 @@ public abstract class BaseRecyclerViewHolder<T> extends RecyclerView.ViewHolder
public BaseRecyclerViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
/**

View File

@ -1,6 +1,5 @@
package com.gh.base
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ClipboardManager
@ -10,580 +9,204 @@ import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.webkit.JavascriptInterface
import android.widget.CheckBox
import android.widget.FrameLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import com.gh.common.AppExecutor
import com.gh.common.runOnIoThread
import com.gh.common.util.*
import butterknife.OnClick
import com.gh.common.util.DialogUtils
import com.gh.common.util.MtaHelper
import com.gh.common.view.RichEditor
import com.gh.gamecenter.CropImageActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.qa.editor.*
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.entity.MyVideoEntity
import com.gh.gamecenter.qa.editor.GameActivity
import com.gh.gamecenter.qa.editor.InsertAnswerWrapperActivity
import com.gh.gamecenter.qa.editor.InsertArticleWrapperActivity
import com.gh.gamecenter.qa.editor.VideoActivity
import com.gh.gamecenter.qa.entity.AnswerEntity
import com.gh.gamecenter.qa.entity.ArticleEntity
import com.gh.gamecenter.qa.entity.EditorInsertEntity
import com.gh.gamecenter.video.poster.PosterEditActivity
import com.gh.gamecenter.video.upload.UploadManager
import com.google.gson.JsonObject
import com.halo.assistant.HaloApp
import com.lightgame.utils.Util_System_Keyboard
import com.lightgame.utils.Utils
import com.lightgame.view.CheckableImageView
import io.reactivex.disposables.Disposable
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import kotterknife.bindView
abstract class BaseRichEditorActivity<VM : BaseRichEditorViewModel> : ToolBarActivity(),
KeyboardHeightObserver, UploadVideoListener {
abstract class BaseRichEditorActivity : ToolBarActivity() {
lateinit var mRichEditor: RichEditor
val mRichEditor by bindView<RichEditor>(R.id.rich_editor)
private lateinit var mEditorTextNumTv: TextView
private lateinit var mEditorFont: CheckableImageView
private lateinit var mEditorLink: CheckableImageView
private lateinit var mEditorFontBold: CheckableImageView
private lateinit var mEditorFontItalic: CheckableImageView
private lateinit var mEditorFontStrikeThrough: CheckableImageView
private lateinit var mEditorFontUnderline: CheckableImageView
private lateinit var mEditorParagraphH1: CheckableImageView
private lateinit var mEditorParagraphH2: CheckableImageView
private lateinit var mEditorParagraphH3: CheckableImageView
private lateinit var mEditorParagraphH4: CheckableImageView
private lateinit var mEditorParagraphQuote: CheckableImageView
private lateinit var mEditorFontContainer: View
private lateinit var mEditorParagraphContainer: View
private lateinit var mEditorLinkContainer: View
private lateinit var mEditorInsertDetailContainer: View
private lateinit var mTagsContainer: FrameLayout
private lateinit var mUploadVideoGuideContainer: View
protected lateinit var mOriginalCb: CheckBox
private lateinit var mOriginalTipsContainer: View
private lateinit var mOriginalTipsClose: TextView
private val mEditorFont by bindView<CheckableImageView>(R.id.editor_font)
private val mEditorLink by bindView<CheckableImageView>(R.id.editor_link)
private val mEditorParagraph by bindView<CheckableImageView>(R.id.editor_paragraph)
private val mEditorFontBold by bindView<CheckableImageView>(R.id.editor_font_bold)
private val mEditorFontItalic by bindView<CheckableImageView>(R.id.editor_font_italic)
private val mEditorFontStrikeThrough by bindView<CheckableImageView>(R.id.editor_font_strikethrough)
private val mEditorParagraphH1 by bindView<CheckableImageView>(R.id.editor_paragraph_h1)
private val mEditorParagraphH2 by bindView<CheckableImageView>(R.id.editor_paragraph_h2)
private val mEditorParagraphH3 by bindView<CheckableImageView>(R.id.editor_paragraph_h3)
private val mEditorParagraphH4 by bindView<CheckableImageView>(R.id.editor_paragraph_h4)
private val mEditorParagraphQuote by bindView<CheckableImageView>(R.id.editor_paragraph_quote)
private val mEditorFontContainer by bindView<View>(R.id.editor_font_container)
private val mEditorParagraphContainer by bindView<View>(R.id.editor_paragraph_container)
private val mEditorLinkContainer by bindView<View>(R.id.editor_link_container)
private val mEditorInsertDetail by bindView<View>(R.id.editor_insert_detail)
private var mCurrentParagraphStyle = ""
private var mIsExtendedKeyboardShow = false
private var mAgreePostPic: Boolean = false
private var mGuideDisposable: Disposable? = null
protected lateinit var mViewModel: VM
protected var mIsKeyBoardShow = false
private var mKeyboardHeightProvider: KeyboardHeightProvider? = null
private var mMaxUploadVideoGuideCount = 2
val FILE_HOST = "file:///"
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
DialogUtils.fixWebViewKeyboardNotWorking(this)
if (resultCode != Activity.RESULT_OK) return
val insertData: EditorInsertEntity?
var insertData: EditorInsertEntity? = null
when (requestCode) {
INSERT_ANSWER_CODE -> {
val answer =
data?.getParcelableExtra<AnswerEntity>(AnswerEntity::class.java.simpleName)
if (answer != null) {
mRichEditor.focusEditor()
insertData = EditorInsertEntity.transform(answer)
mRichEditor.insertCustomStyleLink(insertData)
}
val answer = data?.getParcelableExtra<AnswerEntity>(AnswerEntity::class.java.simpleName)
if (answer != null) insertData = EditorInsertEntity.transform(answer)
}
INSERT_ARTICLE_CODE -> {
val article =
data?.getParcelableExtra<ArticleEntity>(ArticleEntity::class.java.simpleName)
if (article != null) {
mRichEditor.focusEditor()
insertData = EditorInsertEntity.transform(article)
mRichEditor.insertCustomStyleLink(insertData)
}
val article = data?.getParcelableExtra<ArticleEntity>(ArticleEntity::class.java.simpleName)
if (article != null) insertData = EditorInsertEntity.transform(article)
}
INSERT_GAME_CODE -> {
val game = data?.getParcelableExtra<GameEntity>(GameEntity::class.java.simpleName)
if (game != null) {
mRichEditor.focusEditor()
insertData = EditorInsertEntity.transform(game)
mRichEditor.insertCustomStyleLink(insertData)
}
if (game != null) insertData = EditorInsertEntity.transform(game)
}
INSERT_GAME_COLLECTION_CODE -> {
val gameCollectionEntity = data?.getParcelableExtra<GamesCollectionEntity>(GamesCollectionEntity::class.java.simpleName)
if (gameCollectionEntity != null) {
mRichEditor.focusEditor()
insertData = EditorInsertEntity.transform(gameCollectionEntity)
mRichEditor.insertCustomStyleLink(insertData)
}
}
REQUEST_CODE_IMAGE -> {
if (data != null) mViewModel.uploadPic(data)
}
INSERT_MEDIA_VIDEO_CODE -> {
val localVideoList = data?.getParcelableArrayListExtra<LocalVideoEntity>(LocalVideoEntity::class.java.name) ?: arrayListOf()
if (localVideoList.isNotEmpty()) {
mRichEditor.focusEditor()
uploadVideo(localVideoList)
}
}
REQUEST_CODE_IMAGE_CROP -> {
val imagePath = data?.getStringExtra(CropImageActivity.RESULT_CLIP_PATH)
if (!imagePath.isNullOrEmpty()) {
mViewModel.uploadPoster(imagePath)
}
}
INSERT_VIDEO_CODE -> {
val videoEntity = data?.getParcelableExtra<MyVideoEntity>(MyVideoEntity::class.java.simpleName)
if (videoEntity != null) {
mRichEditor.focusEditor()
insertData = EditorInsertEntity.transform(videoEntity)
mRichEditor.insertCustomStyleLink(insertData)
}
VideoActivity.INSERT_VIDEO_CODE -> {
val video = data?.getParcelableExtra<MyVideoEntity>(MyVideoEntity::class.java.simpleName)
if (video != null) mRichEditor.insertCustomVideo(video)
return
}
}
closeExtendedKeyboard()
AppExecutor.uiExecutor.executeWithDelay(Runnable {
Util_System_Keyboard.showSoftKeyboard(this)
}, 100)
mRichEditor.insertCustomStyleLink(insertData)
}
private fun uploadVideo(localVideoList: ArrayList<LocalVideoEntity>) {
mViewModel.localVideoList.addAll(localVideoList)
runOnIoThread {
localVideoList.forEach {
if (it.poster.startsWith("http")) {
runOnUiThread {
mRichEditor.focusEditor()
mRichEditor.insertPlaceholderVideo(it.id, it.poster)
}
} else {
val videoThumbnail = BitmapUtils.getVideoThumbnail(it.filePath)
val filePath = "${cacheDir.absolutePath}${File.separator}${it.id}.webp"
BitmapUtils.saveBitmap(videoThumbnail, filePath)
it.poster = filePath
runOnUiThread {
mRichEditor.focusEditor()
mRichEditor.insertPlaceholderVideo(it.id, "$FILE_HOST${it.poster}")
}
}
}
mViewModel.uploadVideo()
}
}
private fun findView() {
mRichEditor = findViewById(R.id.rich_editor)
mEditorTextNumTv = findViewById(R.id.editorTextNumTv)
mEditorFont = findViewById(R.id.editor_font)
mEditorLink = findViewById(R.id.editor_link)
mEditorFontBold = findViewById(R.id.editor_font_bold)
mEditorFontItalic = findViewById(R.id.editor_font_italic)
mEditorFontStrikeThrough = findViewById(R.id.editor_font_strikethrough)
mEditorFontUnderline = findViewById(R.id.editor_font_underline)
mEditorParagraphH1 = findViewById(R.id.editor_paragraph_h1)
mEditorParagraphH2 = findViewById(R.id.editor_paragraph_h2)
mEditorParagraphH3 = findViewById(R.id.editor_paragraph_h3)
mEditorParagraphH4 = findViewById(R.id.editor_paragraph_h4)
mEditorParagraphQuote = findViewById(R.id.editor_paragraph_quote)
mEditorFontContainer = findViewById(R.id.editor_font_container)
mEditorParagraphContainer = findViewById(R.id.editor_paragraph_container)
mEditorLinkContainer = findViewById(R.id.editor_link_container)
mEditorInsertDetailContainer = findViewById(R.id.editor_insert_detail_container)
mTagsContainer = findViewById(R.id.tagsContainer)
mUploadVideoGuideContainer = findViewById(R.id.uploadVideoGuideContainer)
mOriginalCb = findViewById(R.id.originalCb)
mOriginalTipsContainer = findViewById(R.id.originalTipsContainer)
mOriginalTipsClose = findViewById(R.id.originalTipsClose)
}
@SuppressLint("AddJavascriptInterface", "ClickableViewAccessibility")
@SuppressLint("AddJavascriptInterface")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
findView()
onRichClick()
mViewModel = provideViewModel()
mViewModel.setUploadVideoListener(this)
mKeyboardHeightProvider = KeyboardHeightProvider(this)
mRichEditor.post { mKeyboardHeightProvider?.start() }
mRichEditor.setPadding(20, 15, 20, 15)
// 防止个别手机在Js里无法获取粘贴内容
mRichEditor.addJavascriptInterface(OnPasteListener(), "onPasteListener")
mRichEditor.addJavascriptInterface(OnCursorChangeListener(), "OnCursorChangeListener")
mRichEditor.addJavascriptInterface(
OnEditorTextChangeListener(),
"OnEditorTextChangeListener"
)
mRichEditor.addJavascriptInterface(OnVideoListener(), "onVideoListener")
mRichEditor.addJavascriptInterface(
OnQuoteCountChangeListener(),
"OnQuoteCountChangeListener"
)
mRichEditor.setInputEnabled(true)
mRichEditor.setPadding(16, 12, 16, 12)
mRichEditor.setOnTouchListener { _, _ ->
if (mIsExtendedKeyboardShow) {
closeExtendedKeyboard()
Util_System_Keyboard.showSoftKeyboard(this)
//是否消费事件根据mRichEditor是否含有焦点决定mRichEditor没有焦点则不消费事件
mRichEditor.hasFocus()
} else false
}
mOriginalCb.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
mOriginalTipsContainer.alpha = 0f
mOriginalTipsContainer.visibility = View.VISIBLE
ObjectAnimator.ofFloat(mOriginalTipsContainer, "alpha", 0f, 1f).setDuration(200).start()
}
}
observeData()
}
private fun observeData() {
mViewModel.chooseImagesUpload.observe(this, Observer {
mRichEditor.focusEditor()
for (key in it.keys) {
mRichEditor.insertPlaceholderImage(key)
@OnClick(R.id.editor_image, R.id.editor_font, R.id.editor_link, R.id.editor_paragraph,
R.id.editor_font_bold, R.id.editor_font_italic, R.id.editor_font_strikethrough,
R.id.editor_paragraph_h1, R.id.editor_paragraph_h2, R.id.editor_paragraph_h3,
R.id.editor_paragraph_h4, R.id.editor_font_container, R.id.editor_paragraph_container,
R.id.editor_paragraph_quote, R.id.editor_link_answer, R.id.editor_link_article,
R.id.editor_link_game, R.id.editor_link_video)
fun onRichClick(view: View) {
when (view.id) {
R.id.editor_font -> {
mEditorFont.isChecked = !mEditorFont.isChecked
mEditorParagraph.isChecked = false
mEditorLink.isChecked = false
mEditorFontContainer.visibility = if (mEditorFont.isChecked) View.VISIBLE else View.GONE
mEditorParagraphContainer.visibility = if (!mEditorFont.isChecked) View.VISIBLE else View.GONE
mEditorLinkContainer.visibility = if (!mEditorFont.isChecked) View.VISIBLE else View.GONE
mEditorInsertDetail.visibility = mEditorFontContainer.visibility
}
})
mViewModel.chooseImagesUploadSuccess.observe(this, Observer {
val jsonArray = JSONArray()
for (key in it.keys) {
val jsonObject = JSONObject()
jsonObject.put("id", key)
jsonObject.put("url", it[key])
jsonArray.put(jsonObject)
R.id.editor_paragraph -> {
mEditorParagraph.isChecked = !mEditorParagraph.isChecked
mEditorFont.isChecked = false
mEditorLink.isChecked = false
mEditorParagraphContainer.visibility = if (mEditorParagraph.isChecked) View.VISIBLE else View.GONE
mEditorFontContainer.visibility = if (!mEditorParagraph.isChecked) View.VISIBLE else View.GONE
mEditorLinkContainer.visibility = if (!mEditorParagraph.isChecked) View.VISIBLE else View.GONE
mEditorInsertDetail.visibility = mEditorParagraphContainer.visibility
}
mRichEditor.replacePlaceholderImage(jsonArray.toString())
})
}
override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
mIsKeyBoardShow = height > 0
if (height > 0) {
closeExtendedKeyboard()
}
}
fun closeExtendedKeyboard() {
mEditorInsertDetailContainer.visibility = View.GONE
mEditorFont.isChecked = false
mEditorLink.isChecked = false
mIsExtendedKeyboardShow = false
}
protected fun controlEditorInsertContainerEnabled(isEnabled: Boolean) {
mEditorFont.isEnabled = isEnabled
}
private fun onRichClick() {
mEditorFont.setOnClickListener {
controlEditorFontContainer()
}
mEditorLink.setOnClickListener {
controlEditorLinkContainer()
}
mEditorFontBold.setOnClickListener {
mEditorFontBold.isChecked = !mEditorFontBold.isChecked
mRichEditor.setBold()
if (mEditorFontBold.isChecked) {
MtaHelper.onEvent(mtaEventName(), "文字样式", "文字样式-加粗")
R.id.editor_link -> {
mEditorLink.isChecked = !mEditorLink.isChecked
mEditorFont.isChecked = false
mEditorParagraph.isChecked = false
mEditorLinkContainer.visibility = if (mEditorLink.isChecked) View.VISIBLE else View.GONE
mEditorParagraphContainer.visibility = if (!mEditorLink.isChecked) View.VISIBLE else View.GONE
mEditorFontContainer.visibility = if (!mEditorLink.isChecked) View.VISIBLE else View.GONE
mEditorInsertDetail.visibility = mEditorLinkContainer.visibility
}
}
mEditorFontItalic.setOnClickListener {
mEditorFontItalic.isChecked = !mEditorFontItalic.isChecked
mRichEditor.setItalic()
if (mEditorFontItalic.isChecked) {
MtaHelper.onEvent(mtaEventName(), "文字样式", "文字样式-斜体")
}
}
mEditorFontStrikeThrough.setOnClickListener {
mEditorFontStrikeThrough.isChecked = !mEditorFontStrikeThrough.isChecked
mRichEditor.setStrikeThrough()
if (mEditorFontStrikeThrough.isChecked) {
MtaHelper.onEvent(mtaEventName(), "文字样式", "文字样式-删除线")
}
}
mEditorFontUnderline.setOnClickListener {
mEditorFontUnderline.isChecked = !mEditorFontUnderline.isChecked
mRichEditor.setUnderline()
if (mEditorFontUnderline.isChecked) {
MtaHelper.onEvent(mtaEventName(), "文字样式", "文字样式-下滑线")
}
}
mEditorParagraphH1.setOnClickListener {
if (mEditorParagraphH1.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-1级标题")
mRichEditor.setHeading(1)
}
mEditorParagraphH1.isChecked = !mEditorParagraphH1.isChecked
}
mEditorParagraphH2.setOnClickListener {
if (mEditorParagraphH2.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-2级标题")
mRichEditor.setHeading(2)
}
mEditorParagraphH2.isChecked = !mEditorParagraphH2.isChecked
}
mEditorParagraphH3.setOnClickListener {
if (mEditorParagraphH3.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-3级标题")
mRichEditor.setHeading(3)
}
mEditorParagraphH3.isChecked = !mEditorParagraphH3.isChecked
}
mEditorParagraphH4.setOnClickListener {
if (mEditorParagraphH4.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-4级标题")
mRichEditor.setHeading(4)
}
mEditorParagraphH4.isChecked = !mEditorParagraphH4.isChecked
}
mEditorParagraphQuote.setOnClickListener {
if (mEditorParagraphQuote.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-引用")
mRichEditor.setBlockquote()
}
mEditorParagraphQuote.isChecked = !mEditorParagraphQuote.isChecked
}
findViewById<View>(R.id.editor_link_answer).setOnClickListener {
MtaHelper.onEvent(mtaEventName(), "插入链接", "插入链接-回答")
startActivityForResult(
InsertAnswerWrapperActivity.getIntent(this),
INSERT_ANSWER_CODE
)
}
findViewById<View>(R.id.editor_link_article).setOnClickListener {
MtaHelper.onEvent(mtaEventName(), "插入链接", "插入链接-文章")
startActivityForResult(
InsertArticleWrapperActivity.getIntent(this),
INSERT_ARTICLE_CODE
)
}
findViewById<View>(R.id.editor_link_game).setOnClickListener {
MtaHelper.onEvent(mtaEventName(), "插入链接", "插入链接-游戏")
startActivityForResult(
GameActivity.getIntent(this, GameActivity.INSERT_GAME_TITLE),
INSERT_GAME_CODE
)
}
findViewById<View>(R.id.editor_link_video).setOnClickListener {
startActivityForResult(
InsertVideoWrapperActivity.getIntent(this),
INSERT_VIDEO_CODE
)
}
findViewById<View>(R.id.editor_link_game_collection).setOnClickListener {
startActivityForResult(
InsertGameCollectionWrapperActivity.getIntent(this),
INSERT_GAME_COLLECTION_CODE
)
}
findViewById<View>(R.id.editor_video).setOnClickListener {
chooseVideo()
}
findViewById<View>(R.id.editor_image).setOnClickListener {
if (!mAgreePostPic && !NetworkUtils.isWifiOr4GOr3GConnected(this)) {
mAgreePostPic = true
DialogHelper.showDialog(
this,
"警告",
"当前使用移动网络,上传图片会消耗手机流量",
"我知道了", "", { chooseImage() },
extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
)
return@setOnClickListener
}
chooseImage()
NewLogUtils.logChooseMedia(
"view_media",
if (mtaEventName() == "提问帖") "提问帖" else "帖子",
"图片"
)
}
findViewById<View>(R.id.uploadVideoGuideClose).setOnClickListener {
hideUploadVideoGuide()
if (mGuideDisposable != null && !mGuideDisposable!!.isDisposed) {
mGuideDisposable!!.dispose()
mGuideDisposable = null
}
}
findViewById<View>(R.id.originalTipsClose).setOnClickListener {
val animator = ObjectAnimator.ofFloat(mOriginalTipsContainer, "alpha", 1f, 0f).setDuration(200)
animator.doOnEnd {
mOriginalTipsContainer.visibility = View.GONE
}
animator.start()
}
}
private fun chooseVideo() {
MtaHelper.onEvent(mtaEventName(), "插入链接", "插入链接-视频")
val videoCount = mViewModel.quoteCountEntity.videoCount
if (videoCount >= MAX_MEDIA_COUNT) {
toast(R.string.answer_edit_max_video_hint)
return
}
try {
PermissionHelper.checkStoragePermissionBeforeAction(this,
object : EmptyCallback {
override fun onCallback() {
val maxChooseCount = if (videoCount + 3 <= MAX_MEDIA_COUNT) 3 else MAX_MEDIA_COUNT - videoCount
startActivityForResult(
LocalMediaActivity.getIntent(
this@BaseRichEditorActivity,
LocalMediaActivity.ChooseType.VIDEO,
maxChooseCount,
if (mtaEventName() == "提问帖") "发提问帖" else "发帖子"
), INSERT_MEDIA_VIDEO_CODE
)
NewLogUtils.logChooseMedia(
"view_media",
if (mtaEventName() == "提问帖") "提问帖" else "帖子",
"视频"
)
}
})
} catch (e: Exception) {
toast(R.string.media_image_hint)
e.printStackTrace()
}
}
private fun chooseImage() {
MtaHelper.onEvent(mtaEventName(), "插入图片", "插入图片")
val imageCount = mViewModel.quoteCountEntity.imageCount
if (imageCount >= MAX_MEDIA_COUNT) {
toast(R.string.answer_edit_max_img_hint)
return
}
try {
PermissionHelper.checkStoragePermissionBeforeAction(this, object : EmptyCallback {
override fun onCallback() {
val maxChooseCount = if (imageCount + 10 <= MAX_MEDIA_COUNT) 10 else MAX_MEDIA_COUNT - imageCount
val intent = LocalMediaActivity.getIntent(
this@BaseRichEditorActivity,
LocalMediaActivity.ChooseType.IMAGE,
maxChooseCount,
if (mtaEventName() == "提问帖") "发提问帖" else "发帖子"
)
startActivityForResult(intent, REQUEST_CODE_IMAGE)
}
})
} catch (e: Exception) {
toast(R.string.media_image_hint)
e.printStackTrace()
}
}
private fun controlEditorFontContainer() {
mEditorFont.isChecked = !mEditorFont.isChecked
mEditorLink.isChecked = false
val isShouldDelay = if (mEditorFont.isChecked) {
Util_System_Keyboard.hideSoftKeyboard(this)
true
} else {
Util_System_Keyboard.showSoftKeyboard(this)
false
}
mEditorInsertDetailContainer.postDelayed({
mEditorInsertDetailContainer.visibility =
if (mEditorFont.isChecked) View.VISIBLE else View.GONE
mEditorFontContainer.visibility = if (mEditorFont.isChecked) View.VISIBLE else View.GONE
mEditorParagraphContainer.visibility =
if (mEditorFont.isChecked) View.VISIBLE else View.GONE
mEditorLinkContainer.visibility = View.GONE
mTagsContainer.visibility = View.GONE
mIsExtendedKeyboardShow = mEditorFont.isChecked
}, if (isShouldDelay) 200 else 0L)
}
private fun controlEditorLinkContainer() {
mEditorLink.isChecked = !mEditorLink.isChecked
mEditorFont.isChecked = false
val isShouldDelay = if (mEditorLink.isChecked) {
Util_System_Keyboard.hideSoftKeyboard(this)
true
} else {
Util_System_Keyboard.showSoftKeyboard(this)
false
}
mEditorInsertDetailContainer.postDelayed({
mEditorInsertDetailContainer.visibility =
if (mEditorLink.isChecked) View.VISIBLE else View.GONE
mEditorLinkContainer.visibility = if (mEditorLink.isChecked) View.VISIBLE else View.GONE
mEditorFontContainer.visibility = View.GONE
mEditorParagraphContainer.visibility = View.GONE
mTagsContainer.visibility = View.GONE
mIsExtendedKeyboardShow = mEditorLink.isChecked
}, if (isShouldDelay) 200 else 0L)
}
override fun handleBackPressed(): Boolean {
if (mIsExtendedKeyboardShow) {
closeExtendedKeyboard()
return true
}
return super.handleBackPressed()
}
override fun onResume() {
super.onResume()
mKeyboardHeightProvider?.setKeyboardHeightObserver(this)
}
override fun onPause() {
super.onPause()
mKeyboardHeightProvider?.setKeyboardHeightObserver(null)
}
//视频上传功能引导
fun showUploadVideoGuide() {
mUploadVideoGuideContainer.postDelayed({
val count = SPUtils.getInt(getVideoGuideKey(), 0)
if (count >= mMaxUploadVideoGuideCount) return@postDelayed
mUploadVideoGuideContainer.alpha = 0f
mUploadVideoGuideContainer.visibility = View.VISIBLE
mUploadVideoGuideContainer.animate().alpha(1f).setDuration(200).start()
mGuideDisposable = countDownTimer(3) { finish, _ ->
if (finish) {
hideUploadVideoGuide()
R.id.editor_font_bold -> {
mEditorFontBold.isChecked = !mEditorFontBold.isChecked
mRichEditor.setBold()
if (mEditorFontBold.isChecked) {
MtaHelper.onEvent(mtaEventName(), "文字样式", "文字样式-加粗")
}
}
SPUtils.setInt(getVideoGuideKey(), count + 1)
}, 1000)
}
R.id.editor_font_italic -> {
mEditorFontItalic.isChecked = !mEditorFontItalic.isChecked
mRichEditor.setItalic()
if (mEditorFontItalic.isChecked) {
MtaHelper.onEvent(mtaEventName(), "文字样式", "文字样式-斜体")
}
}
R.id.editor_font_strikethrough -> {
mEditorFontStrikeThrough.isChecked = !mEditorFontStrikeThrough.isChecked
mRichEditor.setStrikeThrough()
fun hideUploadVideoGuide() {
val animate = mUploadVideoGuideContainer.animate().alpha(0f).setDuration(200)
animate.doOnEnd {
mUploadVideoGuideContainer.visibility = View.GONE
}
animate.start()
}
override fun onDestroy() {
super.onDestroy()
mKeyboardHeightProvider?.close()
val path = mViewModel.currentUploadingVideo?.filePath
if (path != null && UploadManager.isUploading(path)) {
UploadManager.cancelTask(path)
}
if (mGuideDisposable != null && !mGuideDisposable!!.isDisposed) {
mGuideDisposable!!.dispose()
mGuideDisposable = null
if (mEditorFontStrikeThrough.isChecked) {
MtaHelper.onEvent(mtaEventName(), "文字样式", "文字样式-删除线")
}
}
R.id.editor_paragraph_h1 -> {
if (mEditorParagraphH1.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-1级标题")
mRichEditor.setHeading(1)
}
mEditorParagraphH1.isChecked = !mEditorParagraphH1.isChecked
}
R.id.editor_paragraph_h2 -> {
if (mEditorParagraphH2.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-2级标题")
mRichEditor.setHeading(2)
}
mEditorParagraphH2.isChecked = !mEditorParagraphH2.isChecked
}
R.id.editor_paragraph_h3 -> {
if (mEditorParagraphH3.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-3级标题")
mRichEditor.setHeading(3)
}
mEditorParagraphH3.isChecked = !mEditorParagraphH3.isChecked
}
R.id.editor_paragraph_h4 -> {
if (mEditorParagraphH4.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-4级标题")
mRichEditor.setHeading(4)
}
mEditorParagraphH4.isChecked = !mEditorParagraphH4.isChecked
}
R.id.editor_paragraph_quote -> {
if (mEditorParagraphQuote.isChecked) {
mRichEditor.formatBlock()
} else {
MtaHelper.onEvent(mtaEventName(), "段落样式", "段落样式-引用")
mRichEditor.setBlockquote()
}
mEditorParagraphQuote.isChecked = !mEditorParagraphQuote.isChecked
}
R.id.editor_link_answer -> {
MtaHelper.onEvent(mtaEventName(), "插入链接", "插入链接-回答")
startActivityForResult(InsertAnswerWrapperActivity.getIntent(this), INSERT_ANSWER_CODE)
}
R.id.editor_link_article -> {
MtaHelper.onEvent(mtaEventName(), "插入链接", "插入链接-文章")
startActivityForResult(InsertArticleWrapperActivity.getIntent(this), INSERT_ARTICLE_CODE)
}
R.id.editor_link_game -> {
MtaHelper.onEvent(mtaEventName(), "插入链接", "插入链接-游戏")
startActivityForResult(GameActivity.getIntent(this, "插入游戏"), INSERT_GAME_CODE)
}
R.id.editor_link_video -> {
MtaHelper.onEvent(mtaEventName(), "插入链接", "插入链接-视频")
startActivityForResult(VideoActivity.getIntent(this), VideoActivity.INSERT_VIDEO_CODE)
}
}
}
@ -605,7 +228,6 @@ abstract class BaseRichEditorActivity<VM : BaseRichEditorViewModel> : ToolBarAct
mEditorFontBold.isChecked = elements.contains(ELEMENT_NAME_BOLD)
mEditorFontItalic.isChecked = elements.contains(ELEMENT_NAME_ITALIC)
mEditorFontStrikeThrough.isChecked = elements.contains(ELEMENT_NAME_STRIKE)
mEditorFontUnderline.isChecked = elements.contains(ELEMENT_NAME_UNDERLINE)
mEditorParagraphH1.isChecked = elements.contains(ELEMENT_PARAGRAPH_H1)
mEditorParagraphH2.isChecked = elements.contains(ELEMENT_PARAGRAPH_H2)
mEditorParagraphH3.isChecked = elements.contains(ELEMENT_PARAGRAPH_H3)
@ -619,127 +241,22 @@ abstract class BaseRichEditorActivity<VM : BaseRichEditorViewModel> : ToolBarAct
@JavascriptInterface
fun onPaste() {
val clipboard =
HaloApp.getInstance().application.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
HaloApp.getInstance().application.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clipText = clipboard.text.toString()
if (!TextUtils.isEmpty(clipText)) {
// 替换换行符号否则 插入失败
val text = clipText.replace("[ ]".toRegex(), "&nbsp;")
.replace("[\r\n]".toRegex(), "<br/>")
val text = clipText.replace("[ ]".toRegex(), "&nbsp;").replace("[\r\n]".toRegex(), "<br/>")
mBaseHandler.post { mRichEditor.insertHtml(text) }
}
}
}
private inner class OnEditorTextChangeListener {
@JavascriptInterface
fun onTextChange(count: Int) {
val num = if (count > MAX_INPUT_TEXT_NUM) MAX_INPUT_TEXT_NUM - count else count
mEditorTextNumTv.post {
mEditorTextNumTv.text = num.toString()
mViewModel.quoteCountEntity.textCount = num
}
}
}
private inner class OnQuoteCountChangeListener {
@JavascriptInterface
fun onQuoteCountChange(
imageCount: Int,
articleCount: Int,
answerCount: Int,
videoCount: Int,
gameCount: Int
) {
mEditorTextNumTv.post {
mViewModel.quoteCountEntity.apply {
this.imageCount = imageCount
this.articleCount = articleCount
this.answerCount = answerCount
this.videoCount = videoCount
this.gameCount = gameCount
}
}
}
}
private inner class OnVideoListener {
@JavascriptInterface
fun showDeleteDialog(id: String) {
DialogHelper.showDialog(this@BaseRichEditorActivity, "提示", "确定删除吗?", "确定", "取消", {
runOnUiThread {
mRichEditor.delPlaceholderVideo(id)
mViewModel.deleteVideo(id)
}
})
}
@JavascriptInterface
fun updatePoster(id: String, videoId: String, url: String) {
mViewModel.id = id
mViewModel.videoId = videoId
val videoEntity = VideoEntity(url = url)
val intent =
PosterEditActivity.getIntentByVideo(this@BaseRichEditorActivity, videoEntity)
startActivityForResult(intent, REQUEST_CODE_IMAGE_CROP)
}
@JavascriptInterface
fun deleteUploadingVideo(id: String) {
mViewModel.deleteVideo(id)
}
@JavascriptInterface
fun reUploadVideo(id: String) {
val video = mViewModel.uploadVideoErrorList.find { it.id == id }
if (video != null) {
mViewModel.localVideoList.add(video)
mViewModel.uploadVideoErrorList.remove(video)
mViewModel.uploadVideo()
}
}
}
override fun insertPlaceholderVideo(id: String, poster: String) {
mRichEditor.insertPlaceholderVideo(id, poster)
}
override fun updateVideoProgress(id: String, progress: String) {
mRichEditor.updateVideoProgress(id, progress)
}
override fun videoUploadFinished(id: String, url: String, msg: JsonObject) {
try {
val obj = JSONObject()
obj.put("poster", msg.get("poster").asString)
obj.put("url", msg.get("url").asString)
obj.put("duration", RichEditor.formatVideoDuration(msg.get("length").asLong))
obj.put("id", msg.get("_id").asString)
obj.put("status", "pending")
mRichEditor.videoUploadFinished(id, url, obj.toString())
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
}
override fun changePoster(id: String, poster: String) {
mRichEditor.changePoster(id, poster)
}
override fun videoUploadFailed(id: String) {
mRichEditor.videoUploadFailed(id)
}
open fun getSelectedLabel(): Int = 0
open fun onActivityDialogResult(requestCode: Int, resultCode: Int, data: Intent?) {}
abstract fun mtaEventName(): String
abstract fun provideViewModel(): VM
abstract fun getVideoGuideKey(): String
companion object {
const val ELEMENT_NAME_BOLD = " b "
const val ELEMENT_NAME_ITALIC = " i "
const val ELEMENT_NAME_STRIKE = " strike "
const val ELEMENT_NAME_UNDERLINE = " u "
const val ELEMENT_PARAGRAPH_H1 = " h1 "
const val ELEMENT_PARAGRAPH_H2 = " h2 "
const val ELEMENT_PARAGRAPH_H3 = " h3 "
@ -749,13 +266,5 @@ abstract class BaseRichEditorActivity<VM : BaseRichEditorViewModel> : ToolBarAct
const val INSERT_ANSWER_CODE = 411
const val INSERT_ARTICLE_CODE = 412
const val INSERT_GAME_CODE = 413
const val INSERT_GAME_COLLECTION_CODE = 414
const val INSERT_VIDEO_CODE = 415
const val MAX_INPUT_TEXT_NUM = 10000
const val MAX_MEDIA_COUNT = 20
const val REQUEST_CODE_IMAGE = 120
const val INSERT_MEDIA_VIDEO_CODE = 121
const val REQUEST_CODE_IMAGE_CROP = 122
}
}

View File

@ -1,444 +0,0 @@
package com.gh.base
import android.app.Application
import android.content.Intent
import android.graphics.Bitmap
import android.media.ThumbnailUtils
import android.provider.MediaStore
import android.text.TextUtils
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import com.gh.base.fragment.WaitingDialogFragment
import com.gh.common.runOnUiThread
import com.gh.common.util.*
import com.gh.gamecenter.R
import com.gh.gamecenter.entity.ErrorEntity
import com.gh.gamecenter.entity.LocalVideoEntity
import com.gh.gamecenter.entity.QuoteCountEntity
import com.gh.gamecenter.qa.BbsType
import com.gh.gamecenter.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.retrofit.service.ApiService
import com.gh.gamecenter.video.upload.OnUploadListener
import com.gh.gamecenter.video.upload.UploadManager
import com.google.gson.JsonObject
import com.lightgame.utils.Utils
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.internal.utils.PathUtils
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import retrofit2.HttpException
import java.io.File
import java.io.FileOutputStream
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.LinkedHashMap
import kotlin.collections.List
import kotlin.collections.Map
import kotlin.collections.find
import kotlin.collections.forEach
import kotlin.collections.set
abstract class BaseRichEditorViewModel(application: Application) : AndroidViewModel(application) {
val mApi: ApiService = RetrofitManager.getInstance().api
val processDialog = MediatorLiveData<WaitingDialogFragment.WaitingDialogData>()
val uploadingImage = ArrayList<LinkedHashMap<String, String>>()
val chooseImagesUpload = MutableLiveData<LinkedHashMap<String, String>>()
val chooseImagesUploadSuccess = MutableLiveData<LinkedHashMap<String, String>>()
var uploadImageSubscription: Disposable? = null
val mapImages = HashMap<String, String>()
val localVideoList = ArrayList<LocalVideoEntity>()
val uploadVideoErrorList = ArrayList<LocalVideoEntity>()
var currentUploadingVideo: LocalVideoEntity? = null
var type: String = "" //游戏论坛game_bbs 官方论坛official_bbs
private var mUploadVideoListener: UploadVideoListener? = null
val TITLE_MIN_LENGTH = 6
val MIN_TEXT_LENGTH = 6
val MAX_TEXT_LENGTH = 10000
val FILE_HOST = "file:///"
var id = ""//视频标记
var videoId = ""//更改封面视频id
val quoteCountEntity = QuoteCountEntity()//数据上报用
fun setUploadVideoListener(uploadVideoListener: UploadVideoListener) {
this.mUploadVideoListener = uploadVideoListener
}
//检查图片是否符合规则并上传图片
fun uploadPic(data: Intent) {
val uris = Matisse.obtainResult(data)
val pictureList = ArrayList<String>()
for (uri in uris) {
val picturePath = PathUtils.getPath(getApplication(), uri)
if (picturePath != null) {
if (File(picturePath).length() > ImageUtils.getUploadFileMaxSize()) {
val count = ImageUtils.getUploadFileMaxSize() / 1024 / 1024
val application: Application = getApplication()
Utils.toast(
getApplication(),
application.getString(R.string.pic_max_hint, count)
)
continue
}
Utils.log("picturePath = $picturePath")
pictureList.add(picturePath)
} else {
Utils.log("picturePath is null")
}
}
if (pictureList.size == 0) return
val imageType = when (getRichType()) {
RichType.ARTICLE -> UploadImageUtils.UploadType.community_article
RichType.QUESTION -> UploadImageUtils.UploadType.question
else -> UploadImageUtils.UploadType.poster
}
uploadImageSubscription = UploadImageUtils.compressAndUploadImageList(
imageType,
pictureList,
false,
object : UploadImageUtils.OnUploadImageListListener {
override fun onProgress(total: Long, progress: Long) {}
override fun onCompressSuccess(imageUrls: List<String>) {
val chooseImageMd5Map = LinkedHashMap<String, String>()
imageUrls.forEach {
chooseImageMd5Map[MD5Utils.getUrlMD5(it)] = ""
}
uploadingImage.add(chooseImageMd5Map)
chooseImagesUpload.postValue(chooseImageMd5Map)
}
override fun onSingleSuccess(imageUrl: Map<String, String>) {
val map = LinkedHashMap<String, String>()
for (key in imageUrl.keys) {
map[MD5Utils.getUrlMD5(key)] = FILE_HOST + key.decodeURI()
mapImages[TextUtils.htmlEncode(key).decodeURI()] = imageUrl[key] ?: ""
}
chooseImagesUploadSuccess.postValue(map)
}
override fun onSuccess(
imageUrl: LinkedHashMap<String, String>,
errorMap: Map<String, Exception>
) {
val uploadMap = uploadingImage.find {
it.containsKey(
MD5Utils.getUrlMD5(
imageUrl.entries.iterator().next().key
)
)
}
uploadMap?.let {
uploadingImage.remove(uploadMap)
}
val errorSize = pictureList.size - imageUrl.size
if (errorSize > 0) {
val map = LinkedHashMap<String, String>()
for (key in errorMap.keys) {
map[MD5Utils.getUrlMD5(key)] = ""
}
//value为空会删除PlaceholderImage
chooseImagesUploadSuccess.postValue(map)
for (error in errorMap.values) {
if (error is HttpException && error.code() == 403) {
Utils.toast(getApplication(), errorSize.toString() + "张违规图片上传失败")
return
}
}
Utils.toast(getApplication(), errorSize.toString() + "张图片上传失败")
}
}
override fun onError(errorMap: Map<String, Exception>) {
val errorSize = errorMap.size
if (errorSize > 0) {
val map = LinkedHashMap<String, String>()
for (key in errorMap.keys) {
map[MD5Utils.getUrlMD5(key)] = ""
}
//value为空会删除PlaceholderImage
chooseImagesUploadSuccess.postValue(map)
}
for (error in errorMap.values) {
if (error is HttpException && error.code() == 403) {
val e = error.response()?.errorBody()?.string()?.toObject<ErrorEntity>()
if (e != null && e.code == 403017) {
Utils.toast(
getApplication(),
errorSize.toString() + "张图片的宽或高超过限制,请裁剪后上传"
)
} else {
Utils.toast(getApplication(), errorSize.toString() + "张违规图片上传失败")
}
return
}
}
if (errorSize == 1) {
Utils.toast(getApplication(), "图片上传失败")
} else {
Utils.toast(getApplication(), errorSize.toString() + "张图片上传失败")
}
}
})
}
fun uploadPoster(picturePath: String) {
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("封面上传中...", true))
uploadImageSubscription =
UploadImageUtils.compressAndUploadImage(UploadImageUtils.UploadType.poster,
picturePath,
false,
object : UploadImageUtils.OnUploadImageListener {
override fun onSuccess(imageUrl: String) {
patchVideoPoster(imageUrl)
}
override fun onError(e: Throwable?) {
handleUploadPosterResult(true)
}
override fun onProgress(total: Long, progress: Long) {
}
})
}
private fun patchVideoPoster(poster: String) {
if (id.isEmpty() || videoId.isEmpty()) return
val map = hashMapOf("poster" to poster, "type" to getVideoType())
mApi.patchInsertVideo(videoId, map.toRequestBody())
.compose(observableToMain())
.subscribe(object : Response<ResponseBody>() {
override fun onResponse(response: ResponseBody?) {
super.onResponse(response)
mUploadVideoListener?.changePoster(id, poster)
handleUploadPosterResult(false)
}
override fun onFailure(e: HttpException?) {
super.onFailure(e)
handleUploadPosterResult(true)
}
})
}
private fun handleUploadPosterResult(isFailure: Boolean = false) {
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("封面上传中...", false))
if (isFailure) {
ToastUtils.showToast("封面更改失败")
}
id = ""
videoId = ""
}
fun deleteVideo(id: String) {
if (localVideoList.isNotEmpty()) {
val video = localVideoList.find { it.id == id }
if (video != null) {
if (UploadManager.isUploading(video.filePath)) {
UploadManager.cancelTask(video.filePath)
}
localVideoList.remove(video)
}
}
if (uploadVideoErrorList.isNotEmpty()) {
val video = uploadVideoErrorList.find { it.id == id }
if (video != null) {
uploadVideoErrorList.remove(video)
}
}
if (currentUploadingVideo?.id == id) {
currentUploadingVideo = null
uploadVideo()
}
}
fun uploadVideo() {
if (currentUploadingVideo != null) return
if (localVideoList.isEmpty()) return
currentUploadingVideo = localVideoList[0]
UploadManager.createUploadTask(currentUploadingVideo?.filePath
?: "", object : OnUploadListener {
override fun onProgressChanged(
uploadFilePath: String,
currentSize: Long,
totalSize: Long,
speed: Long
) {
runOnUiThread {
val percent = (currentSize * 100 / totalSize.toFloat()).roundTo(1)
currentUploadingVideo?.id?.let {
mUploadVideoListener?.updateVideoProgress(it, percent.toString())
}
}
}
override fun onUploadSuccess(uploadFilePath: String, url: String) {
if (currentUploadingVideo != null) {
postVideoPosterAndInfo(uploadFilePath, url)
}
}
override fun onUploadFailure(uploadFilePath: String, errorMsg: String) {
uploadVideoFailure()
}
})
}
private fun postVideoPosterAndInfo(uploadFilePath: String, url: String) {
val localVideoPoster =
getApplication<Application>().cacheDir.absolutePath + File.separator + System.currentTimeMillis() + ".jpg"
try {
val bmp = ThumbnailUtils.createVideoThumbnail(
uploadFilePath,
MediaStore.Images.Thumbnails.MINI_KIND
)
// bmp 可能为空
FileOutputStream(localVideoPoster).use { out ->
bmp?.compress(Bitmap.CompressFormat.PNG, 100, out)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
ToastUtils.showToast("视频封面操作失败")
uploadVideoFailure()
return
}
uploadImageSubscription =
UploadImageUtils.compressAndUploadImage(UploadImageUtils.UploadType.poster,
localVideoPoster,
false,
object : UploadImageUtils.OnUploadImageListener {
override fun onSuccess(imageUrl: String) {
postVideoInfo(url, imageUrl)
}
override fun onError(e: Throwable?) {
uploadVideoFailure()
}
override fun onProgress(total: Long, progress: Long) {
}
})
}
private fun postVideoInfo(url: String, poster: String) {
val map = HashMap<String, Any>().apply {
put("poster", poster)
put("url", url)
put("format", currentUploadingVideo?.format ?: "")
put("size", currentUploadingVideo?.size ?: 0)
put("length", (currentUploadingVideo?.duration ?: 0) / 1000)
put("type", getVideoType())
}
val requestBody = map.toRequestBody()
mApi.insertVideo(requestBody)
.compose(observableToMain())
.subscribe(object : Response<JsonObject>() {
override fun onResponse(response: JsonObject?) {
super.onResponse(response)
if (response != null) {
uploadVideoSuccess(poster, url, response)
}
}
override fun onFailure(e: HttpException?) {
super.onFailure(e)
uploadVideoFailure()
}
})
}
private fun uploadVideoSuccess(poster: String, url: String, data: JsonObject) {
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("封面上传中...", false))
currentUploadingVideo?.let {
mUploadVideoListener?.changePoster(it.id, poster)
mUploadVideoListener?.videoUploadFinished(it.id, url, data)
UploadManager.cancelTask(it.filePath)
localVideoList.remove(it)
}
currentUploadingVideo = null
uploadVideo()
}
private fun uploadVideoFailure() {
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("封面上传中...", false))
currentUploadingVideo?.let {
runOnUiThread {
mUploadVideoListener?.videoUploadFailed(it.id)
}
uploadVideoErrorList.add(it)
localVideoList.remove(it)
UploadManager.cancelTask(it.filePath)
}
currentUploadingVideo = null
uploadVideo()
}
fun checkIsAllUploadedAndToast(): Boolean {
if (localVideoList.isNotEmpty() || uploadVideoErrorList.isNotEmpty()) {
ToastUtils.showToast("视频未上传完成,视频内容保存失败")
return false
}
return true
}
private fun getVideoType(): String {
return when (type) {
BbsType.GAME_BBS.value -> {
when (getRichType()) {
RichType.ARTICLE -> BbsType.GAME_BBS_ARTICLE_INSERT.value
RichType.QUESTION -> BbsType.GAME_BBS_QUESTION_INSERT.value
else -> ""
}
}
BbsType.OFFICIAL_BBS.value -> {
when (getRichType()) {
RichType.ARTICLE -> BbsType.OFFICIAL_BBS_ARTICLE_INSERT.value
RichType.QUESTION -> BbsType.OFFICIAL_BBS_QUESTION_INSERT.value
else -> ""
}
}
else -> ""
}
}
abstract fun getRichType(): RichType
}
interface UploadVideoListener {
/**
* 插入视频占位图
*/
fun insertPlaceholderVideo(id: String, poster: String)
/**
* 更新视频进度条
*/
fun updateVideoProgress(id: String, progress: String)
/**
* 上传视频完成
*/
fun videoUploadFinished(id: String, url: String, msg: JsonObject)
/**
* 更换封面图
*/
fun changePoster(id: String, poster: String)
/**
* 上传失败
*/
fun videoUploadFailed(id: String)
}
enum class RichType {
ARTICLE,
QUESTION,
ANSWER
}

View File

@ -1,93 +0,0 @@
package com.gh.base
import android.content.Context
import android.content.SharedPreferences
import com.gh.common.util.SPUtils
import com.halo.assistant.HaloApp
/**
* 用 SP 实现的简单列表持久化结构
*/
abstract class BaseSimpleDao {
// 使用独有的 SP 文件
private val mSp: SharedPreferences by lazy {
HaloApp.getInstance().application.getSharedPreferences("SimpleDao", Context.MODE_PRIVATE)
}
fun add(key: String) {
val originString = SPUtils.getString(mSp, getSPKey())
if (originString.isEmpty()) {
// Insert keyword only for the very first time.
SPUtils.setString(mSp, getSPKey(), key)
} else {
getAll()?.let {
if (getMaxSize() != -1 && it.size > getMaxSize()) {
it.removeAt(it.size - 1)
}
// Move keyword to the very front if it exists.
if (it.contains(key)) {
it.remove(key)
}
it.add(0, key)
val builder = StringBuilder()
for ((index, k) in it.withIndex()) {
builder.append(k)
if (index != it.size - 1) {
builder.append(DIVIDER_KEY)
}
}
SPUtils.setString(mSp, getSPKey(), builder.toString())
}
}
}
fun delete(key: String) {
val originString = SPUtils.getString(mSp, getSPKey())
if (originString.isEmpty()) {
// do nothing
} else {
getAll()?.let {
if (it.contains(key)) {
it.remove(key)
}
val builder = StringBuilder()
for ((index, k) in it.withIndex()) {
builder.append(k)
if (index != it.size - 1) {
builder.append(DIVIDER_KEY)
}
}
SPUtils.setString(mSp, getSPKey(), builder.toString())
}
}
}
fun getAll(): ArrayList<String>? {
val list = SPUtils.getString(mSp, getSPKey()).split(DIVIDER_KEY)
return if (list.size == 1 && list[0].isEmpty()) null else ArrayList(list)
}
fun getRawString(): String = SPUtils.getString(mSp, getSPKey())
fun contains(key: String): Boolean {
return getAll()?.contains(key) == true
}
fun deleteAll() {
SPUtils.setString(mSp, getSPKey(), "")
}
open fun getMaxSize(): Int = -1
abstract fun getSPKey(): String
companion object {
private const val DIVIDER_KEY = "<-||->"
}
}

View File

@ -1,53 +0,0 @@
package com.gh.base
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.gh.gamecenter.R
class CustomLayoutInflaterFactory(
private val mAppCompatActivity: AppCompatActivity
) : LayoutInflater.Factory2 {
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet
): View? {
val view: View?
try {
view = mAppCompatActivity.delegate.createView(parent, name, context, attrs)
?: mAppCompatActivity.onCreateView(parent, name, context, attrs)
?: mAppCompatActivity.layoutInflater.createView(name, null, attrs)
} catch (e: Exception) {
return null
}
val n = attrs.attributeCount
for (i in 0 until n) {
val attributeName = attrs.getAttributeName(i).toString()
if (attributeName.contains("background")) {
view?.setTag(TAG_BACKGROUND_ID, attrs.getAttributeValue(i))
} else if (attributeName.contains("textColor")) {
view?.setTag(TAG_TEXT_COLOR_ID, attrs.getAttributeValue(i))
}
}
return view
}
override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {
return mAppCompatActivity.onCreateView(name, context, attrs)
}
companion object {
const val TAG_BACKGROUND_ID = R.string.background_id
const val TAG_TEXT_COLOR_ID = R.string.text_color_id
}
}

View File

@ -0,0 +1,71 @@
package com.gh.base;
import android.app.Activity;
import android.app.Application.ActivityLifecycleCallbacks;
import android.os.Bundle;
import com.gh.common.im.ImManager;
import com.gh.common.notifier.Notifier;
import com.gh.common.util.DataUtils;
import com.gh.download.DownloadManager;
import com.lightgame.utils.AppManager;
/**
* 1、写点针对生命周期的统计代码
* 2、写点通用的逻辑
* 3、接口解耦
*
* @author CsHeng
* @Date 09/05/2017
* @Time 6:22 PM
*/
public class GHActivityLifecycleCallbacksImpl implements ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
AppManager.getInstance().addActivity(activity);
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
DataUtils.onResume(activity);
CurrentActivityHolder.getActivitySet().add(activity);
ImManager.updateFloatingWindow();
//FIXME 这里应该只是部分Activity需要
try {
// 初始化gameMap
DownloadManager.getInstance(activity).initGameMap();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onActivityPaused(Activity activity) {
DataUtils.onPause(activity);
CurrentActivityHolder.getActivitySet().remove(activity);
}
@Override
public void onActivityStopped(Activity activity) {
Notifier.hide();
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
AppManager.getInstance().finishActivity(activity);
}
}

View File

@ -1,17 +0,0 @@
package com.gh.base
import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicInteger
class GHThreadFactory(threadNamePrefix: String) : ThreadFactory {
private val THREAD_NAME_STEM = "${threadNamePrefix}_%d"
private val mThreadId = AtomicInteger(0)
override fun newThread(r: Runnable?): Thread {
val t = Thread(r)
t.name = String.format(THREAD_NAME_STEM, mThreadId.getAndIncrement())
return t
}
}

View File

@ -1,229 +1,231 @@
//package com.gh.base
//
//import android.app.Notification
//import android.app.NotificationChannel
//import android.app.NotificationManager
//import android.app.PendingIntent
//import android.content.Context
//import android.content.Intent
//import android.os.Build
//import android.os.Bundle
//import android.preference.PreferenceManager
//import android.text.TextUtils
//import android.view.View
//import androidx.core.app.NotificationCompat
//import androidx.core.text.htmlEncode
//import com.gh.common.notifier.Notifier
//import com.gh.common.util.*
//import com.gh.gamecenter.R
//import com.gh.gamecenter.entity.PushEntity
//import com.gh.gamecenter.entity.PushMessageEntity
//import com.gh.gamecenter.entity.PushMessageUnreadEntity
//import com.gh.gamecenter.entity.PushNotificationEntity
//import com.gh.gamecenter.manager.UserManager
//import com.gh.gamecenter.message.MessageUnreadRepository
//import com.gh.gamecenter.qa.answer.detail.AnswerDetailActivity
//import com.gh.gamecenter.receiver.UmengMessageReceiver
//import com.gh.gamecenter.receiver.UmengMessageReceiver.Companion.TYPE_CLICK
//import com.gh.gamecenter.receiver.UmengMessageReceiver.Companion.TYPE_REMOVE
//import com.gh.gamecenter.retrofit.Response
//import com.gh.gamecenter.retrofit.RetrofitManager
//import com.google.gson.Gson
//import com.umeng.message.UmengMessageService
//import io.reactivex.android.schedulers.AndroidSchedulers
//import io.reactivex.schedulers.Schedulers
//import okhttp3.MediaType
//import okhttp3.RequestBody
//import okhttp3.ResponseBody
//import org.android.agoo.common.AgooConstants
//import org.json.JSONObject
//import retrofit2.HttpException
//import java.util.*
//
//class GHUmengNotificationService : UmengMessageService() {
//
// companion object {
// const val ACTION_UMENG = "com.gh.gamecenter.UMENG"
// const val MESSAGE_FROM_SYSTEM = "message_from_system"
// const val HALO_MESSAGE_DIALOG = "HALO_MESSAGE_DIALOG"
// const val HALO_MESSAGE_CENTER = "HALO_MESSAGE_CENTER"
// const val ANSWER = "answer"
// const val FOLLOW_QUESTION = "follow_question"
// const val NOTIFICATION_ID = 2015
// const val DISPLAY_TYPE_NOTIFICATION = "notification"
// const val DISPLAY_TYPE_CUSTOM = "custom"
// const val MESSAGE_ID = "message_id"
// const val NOTIFICATION_MESSAGE_ID = "notification_message_id" // 通知中心消息 ID
// const val PUSH_ID = "push_id"
// }
//
// val notificationTags = arrayOf("GH_UMENG_TAG_1", "GH_UMENG_TAG_2", "GH_UMENG_TAG_3")
// val gson = Gson()
//
// override fun onMessage(context: Context, intent: Intent) {
// val message = intent.getStringExtra(AgooConstants.MESSAGE_BODY)
// val isMessageFromSystem = intent.getBooleanExtra(MESSAGE_FROM_SYSTEM, false)
//
// try {
// val pushData = message.toObject<PushEntity>()
// pushData?.let { handlePushData(context, it, message, isMessageFromSystem) }
// } catch (e: Exception) {
// e.printStackTrace()
// }
// }
//
// private fun handlePushData(context: Context, pushData: PushEntity, message: String, isMessageFromSystem: Boolean) {
// val notificationManager = context.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//
// if (pushData.displayType == DISPLAY_TYPE_NOTIFICATION) {
// // 其它类型的透传信息
// // 显示到通知栏
// val msg = message.toObject<PushNotificationEntity>()
// val data = msg?.extra?.data
//
// // 系统推送(非自定义信息),直接处理跳转
// if (isMessageFromSystem) {
// val intent = Intent()
// intent.setClass(context, UmengMessageReceiver::class.java)
// intent.putExtra(EntranceUtils.KEY_DATA, data?.link)
// intent.putExtra(EntranceUtils.KEY_TYPE, UmengMessageReceiver.DIRECT_ONLY)
// intent.putExtra(EntranceUtils.KEY_MESSAGE, message)
// intent.putExtra(NOTIFICATION_MESSAGE_ID, data?.messageId)
// context.sendBroadcast(intent)
// return
// }
//
// // 用户未登录的情况下不生成消息中心通知,避免用户掉登录了还收到跳转至消息中心的通知
// if (data != null
// && data.link?.link == "system"
// && !UserManager.getInstance().isLoggedIn) {
// return
// }
//
// val clickIntent = Intent()
// val removeIntent = Intent()
//
// clickIntent.setClass(context, UmengMessageReceiver::class.java)
// clickIntent.putExtra(EntranceUtils.KEY_DATA, data?.link)
// clickIntent.putExtra(EntranceUtils.KEY_MESSAGE, message)
// clickIntent.putExtra(MESSAGE_ID, msg?.msgId)
// clickIntent.putExtra(PUSH_ID, data?.pushId)
// clickIntent.putExtra(NOTIFICATION_MESSAGE_ID, data?.messageId)
// clickIntent.putExtra(EntranceUtils.KEY_TYPE, TYPE_CLICK)
//
// removeIntent.setClass(context, UmengMessageReceiver::class.java)
// removeIntent.putExtra(EntranceUtils.KEY_TYPE, TYPE_REMOVE)
// removeIntent.putExtra(EntranceUtils.KEY_MESSAGE, message)
//
// val clickPendingIntent = PendingIntent.getBroadcast(context, System.currentTimeMillis().toInt(),
// clickIntent, PendingIntent.FLAG_UPDATE_CURRENT)
//
// val deletePendingIntent = PendingIntent.getBroadcast(context, System.currentTimeMillis().toInt() + 1,
// removeIntent, PendingIntent.FLAG_UPDATE_CURRENT)
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// val channel = NotificationChannel("Halo_Push", "Halo_Push", NotificationManager.IMPORTANCE_DEFAULT)
// notificationManager.createNotificationChannel(channel)
// }
//
// val notification = NotificationCompat.Builder(context, "Halo_Push")
// .setSmallIcon(R.drawable.ic_notification)
// .setTicker(pushData.body?.ticker)
// .setContentTitle(pushData.body?.title)
// .setContentText(pushData.body?.text?.fromHtml())
// .setContentIntent(clickPendingIntent)
// .setDeleteIntent(deletePendingIntent)
// .build()
// notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL
//
// notificationManager.notify(getNotificationTag(context), NOTIFICATION_ID, notification)
// } else {
// if (UserManager.getInstance().isLoggedIn &&
// HALO_MESSAGE_DIALOG == pushData.body?.custom &&
// MessageUnreadRepository.unreadLiveData.value != null) {
// // 回答了问题或者关注了问题的消息
// val msg = gson.fromJson(message, PushMessageEntity::class.java)
// val data = msg?.extra?.data
//
// val type = if (ANSWER == data?.type) {
// "回答了你的问题"
// } else {
// "回答了你关注的问题"
// }
//
// val userName = StringUtils.shrinkStringWithDot(data?.userEntity?.name, 8)
// val displayText = userName + type
//
// if (Notifier.isActivityValid(CurrentActivityHolder.getCurrentActivity()) &&
// Notifier.shouldShowNotifier(data?.answer?.id + displayText)) {
// Notifier.create(CurrentActivityHolder.getCurrentActivity())
// .setText(displayText)
// .setDuration(5000)
// .setIcon(data?.userEntity?.icon)
// .setOnClickListener(View.OnClickListener {
// val bundle = Bundle()
// bundle.putString(EntranceUtils.KEY_ANSWER_ID, data?.answer?.id)
// bundle.putString(EntranceUtils.KEY_ENTRANCE, EntranceUtils.ENTRANCE_UMENG)
// bundle.putString(EntranceUtils.KEY_TO, AnswerDetailActivity::class.java.name)
// EntranceUtils.jumpActivity(context, bundle)
//
// MtaHelper.onEvent("消息弹窗", type, "Does not contains any parameter.")
//
// // 标记已读
// val jsonObject = JSONObject()
// jsonObject.put("type", type)
// val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
//
// RetrofitManager.getInstance().api.postMessageRead(UserManager.getInstance().userId, data?.id, body)
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(object : Response<ResponseBody>() {
// override fun onResponse(response: ResponseBody?) {
// super.onResponse(response)
// MessageUnreadRepository.loadMessageUnreadData()
// }
//
// override fun onFailure(e: HttpException?) {
// e?.printStackTrace()
// }
// })
// Notifier.hide()
// })
// .show(false)
// Notifier.tagNotifierAsShowed(data?.answer?.id + displayText)
// }
// } else if (HALO_MESSAGE_CENTER == pushData.body?.custom) {
// // 消息中心逻辑
// val msg = gson.fromJson(message, PushMessageUnreadEntity::class.java)
// val data = msg?.extra?.data
// data?.let { MessageUnreadRepository.loadMessageUnreadData() }
// }
// }
// }
//
// /**
// * 规则:最多三条消息,以旧换新
// *
// * @return NotificationTag
// */
// private fun getNotificationTag(context: Context): String {
// val sp = PreferenceManager.getDefaultSharedPreferences(context)
// val edit = sp.edit()
//
// val timeTagMap = HashMap<Long, String>()
// for (tag in notificationTags) {
// val time = sp.getLong(tag, 0)
// if (time == 0L) {
// edit.putLong(tag, System.currentTimeMillis()).apply()
// return tag
// } else {
// timeTagMap[time] = tag
// }
// }
//
// val minTime = Collections.min(timeTagMap.keys)
// val tag = timeTagMap[minTime]
// edit.putLong(tag, System.currentTimeMillis()).apply()
// return if (TextUtils.isEmpty(tag)) notificationTags[0] else tag!!
// }
//}
package com.gh.base
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.preference.PreferenceManager
import android.text.TextUtils
import android.view.View
import androidx.core.app.NotificationCompat
import com.gh.common.notifier.Notifier
import com.gh.common.util.EntranceUtils
import com.gh.common.util.MtaHelper
import com.gh.common.util.StringUtils
import com.gh.common.util.toObject
import com.gh.gamecenter.R
import com.gh.gamecenter.entity.PushEntity
import com.gh.gamecenter.entity.PushMessageEntity
import com.gh.gamecenter.entity.PushMessageUnreadEntity
import com.gh.gamecenter.entity.PushNotificationEntity
import com.gh.gamecenter.manager.UserManager
import com.gh.gamecenter.message.MessageUnreadRepository
import com.gh.gamecenter.qa.answer.detail.AnswerDetailActivity
import com.gh.gamecenter.receiver.UmengMessageReceiver
import com.gh.gamecenter.receiver.UmengMessageReceiver.Companion.TYPE_CLICK
import com.gh.gamecenter.receiver.UmengMessageReceiver.Companion.TYPE_REMOVE
import com.gh.gamecenter.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.google.gson.Gson
import com.umeng.message.UmengMessageService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.android.agoo.common.AgooConstants
import org.json.JSONObject
import retrofit2.HttpException
import java.util.*
class GHUmengNotificationService : UmengMessageService() {
companion object {
const val ACTION_UMENG = "com.gh.gamecenter.UMENG"
const val MESSAGE_FROM_SYSTEM = "message_from_system"
const val HALO_MESSAGE_DIALOG = "HALO_MESSAGE_DIALOG"
const val HALO_MESSAGE_CENTER = "HALO_MESSAGE_CENTER"
const val ANSWER = "answer"
const val FOLLOW_QUESTION = "follow_question"
const val NOTIFICATION_ID = 2015
const val DISPLAY_TYPE_NOTIFICATION = "notification"
const val DISPLAY_TYPE_CUSTOM = "custom"
const val MESSAGE_ID = "message_id"
const val NOTIFICATION_MESSAGE_ID = "notification_message_id" // 通知中心消息 ID
const val PUSH_ID = "push_id"
}
val notificationTags = arrayOf("GH_UMENG_TAG_1", "GH_UMENG_TAG_2", "GH_UMENG_TAG_3")
val gson = Gson()
override fun onMessage(context: Context, intent: Intent) {
val message = intent.getStringExtra(AgooConstants.MESSAGE_BODY)
val isMessageFromSystem = intent.getBooleanExtra(MESSAGE_FROM_SYSTEM, false)
try {
val pushData = message.toObject<PushEntity>()
pushData?.let { handlePushData(context, it, message, isMessageFromSystem) }
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun handlePushData(context: Context, pushData: PushEntity, message: String, isMessageFromSystem: Boolean) {
val notificationManager = context.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (pushData.displayType == DISPLAY_TYPE_NOTIFICATION) {
// 其它类型的透传信息
// 显示到通知栏
val msg = message.toObject<PushNotificationEntity>()
val data = msg?.extra?.data
// 系统推送(非自定义信息),直接处理跳转
if (isMessageFromSystem) {
val intent = Intent()
intent.setClass(context, UmengMessageReceiver::class.java)
intent.putExtra(EntranceUtils.KEY_DATA, data?.link)
intent.putExtra(EntranceUtils.KEY_TYPE, UmengMessageReceiver.DIRECT_ONLY)
intent.putExtra(EntranceUtils.KEY_MESSAGE, message)
intent.putExtra(NOTIFICATION_MESSAGE_ID, data?.messageId)
context.sendBroadcast(intent)
return
}
// 用户未登录的情况下不生成消息中心通知,避免用户掉登录了还收到跳转至消息中心的通知
if (data != null
&& data.link?.target == "system"
&& !UserManager.getInstance().isLoggedIn) {
return
}
val clickIntent = Intent()
val removeIntent = Intent()
clickIntent.setClass(context, UmengMessageReceiver::class.java)
clickIntent.putExtra(EntranceUtils.KEY_DATA, data?.link)
clickIntent.putExtra(EntranceUtils.KEY_MESSAGE, message)
clickIntent.putExtra(MESSAGE_ID, msg?.msgId)
clickIntent.putExtra(PUSH_ID, data?.pushId)
clickIntent.putExtra(NOTIFICATION_MESSAGE_ID, data?.messageId)
clickIntent.putExtra(EntranceUtils.KEY_TYPE, TYPE_CLICK)
removeIntent.setClass(context, UmengMessageReceiver::class.java)
removeIntent.putExtra(EntranceUtils.KEY_TYPE, TYPE_REMOVE)
removeIntent.putExtra(EntranceUtils.KEY_MESSAGE, message)
val clickPendingIntent = PendingIntent.getBroadcast(context, System.currentTimeMillis().toInt(),
clickIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val deletePendingIntent = PendingIntent.getBroadcast(context, System.currentTimeMillis().toInt() + 1,
removeIntent, PendingIntent.FLAG_UPDATE_CURRENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel("Halo_Push", "Halo_Push", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
val notification = NotificationCompat.Builder(context, "Halo_Push")
.setSmallIcon(R.drawable.ic_notification)
.setTicker(pushData.body?.ticker)
.setContentTitle(pushData.body?.title)
.setContentText(pushData.body?.text)
.setContentIntent(clickPendingIntent)
.setDeleteIntent(deletePendingIntent)
.build()
notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL
notificationManager.notify(getNotificationTag(context), NOTIFICATION_ID, notification)
} else {
if (UserManager.getInstance().isLoggedIn &&
HALO_MESSAGE_DIALOG == pushData.body?.custom &&
MessageUnreadRepository.unreadLiveData.value != null) {
// 回答了问题或者关注了问题的消息
val msg = gson.fromJson(message, PushMessageEntity::class.java)
val data = msg?.extra?.data
val type = if (ANSWER == data?.type) {
"回答了你的问题"
} else {
"回答了你关注的问题"
}
val userName = StringUtils.shrinkStringWithDot(data?.userEntity?.name, 8)
val displayText = userName + type
if (Notifier.isActivityValid(CurrentActivityHolder.getCurrentActivity()) &&
Notifier.shouldShowNotifier(data?.answer?.id + displayText)) {
Notifier.create(CurrentActivityHolder.getCurrentActivity())
.setText(displayText)
.setDuration(5000)
.setIcon(data?.userEntity?.icon)
.setOnClickListener(View.OnClickListener {
val bundle = Bundle()
bundle.putString(EntranceUtils.KEY_ANSWER_ID, data?.answer?.id)
bundle.putString(EntranceUtils.KEY_ENTRANCE, EntranceUtils.ENTRANCE_UMENG)
bundle.putString(EntranceUtils.KEY_TO, AnswerDetailActivity::class.java.name)
EntranceUtils.jumpActivity(context, bundle)
MtaHelper.onEvent("消息弹窗", type, "Does not contains any parameter.")
// 标记已读
val jsonObject = JSONObject()
jsonObject.put("type", type)
val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
RetrofitManager.getInstance(application).api.postMessageRead(UserManager.getInstance().userId, data?.id, body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Response<ResponseBody>() {
override fun onResponse(response: ResponseBody?) {
super.onResponse(response)
MessageUnreadRepository.loadMessageUnreadData()
}
override fun onFailure(e: HttpException?) {
e?.printStackTrace()
}
})
Notifier.hide()
})
.show(false)
Notifier.tagNotifierAsShowed(data?.answer?.id + displayText)
}
} else if (HALO_MESSAGE_CENTER == pushData.body?.custom) {
// 消息中心逻辑
val msg = gson.fromJson(message, PushMessageUnreadEntity::class.java)
val data = msg?.extra?.data
data?.let { MessageUnreadRepository.loadMessageUnreadData() }
}
}
}
/**
* 规则:最多三条消息,以旧换新
*
* @return NotificationTag
*/
private fun getNotificationTag(context: Context): String {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
val edit = sp.edit()
val timeTagMap = HashMap<Long, String>()
for (tag in notificationTags) {
val time = sp.getLong(tag, 0)
if (time == 0L) {
edit.putLong(tag, System.currentTimeMillis()).apply()
return tag
} else {
timeTagMap[time] = tag
}
}
val minTime = Collections.min(timeTagMap.keys)
val tag = timeTagMap[minTime]
edit.putLong(tag, System.currentTimeMillis()).apply()
return if (TextUtils.isEmpty(tag)) notificationTags[0] else tag!!
}
}

View File

@ -1,97 +0,0 @@
package com.gh.base
import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.gh.common.notifier.Notifier
import com.gh.common.util.DataUtils
import com.gh.common.util.FloatingBackViewManager
import com.gh.download.DownloadManager
import com.gh.gamecenter.MainActivity
import com.gh.gamecenter.SplashScreenActivity
import com.gh.gamecenter.energy.EnergyCenterActivity
import com.gh.gamecenter.forum.detail.ForumDetailActivity
import com.gh.gamecenter.forum.list.ForumListActivity
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity
import com.gh.gamecenter.qa.video.detail.ForumVideoDetailActivity
import com.halo.assistant.HaloApp
import com.lightgame.utils.AppManager
class GlobalActivityLifecycleObserver : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
AppManager.getInstance().addActivity(activity)
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityResumed(activity: Activity) {
CurrentActivityHolder.activitySet.add(activity)
// 判断是否需要显示或隐藏返回小浮窗
if (FloatingBackViewManager.getType().isNotEmpty()) {
if (activity is EnergyCenterActivity
&& FloatingBackViewManager.getType() == FloatingBackViewManager.TYPE_TASK
) {
FloatingBackViewManager.disableBackView()
} else if (!shouldShowActivityBackView(activity)
&& FloatingBackViewManager.getType() == FloatingBackViewManager.TYPE_ACTIVITY
) {
FloatingBackViewManager.disableBackView()
} else {
FloatingBackViewManager.showBackView(activity)
}
}
if (HaloApp.isUserAcceptPrivacyPolicy(activity)) {
DataUtils.onResume(activity)
// FIXME 这里应该只是部分Activity需要
try {
// 初始化gameMap
if (activity !is SplashScreenActivity) {
DownloadManager.getInstance().initGameMap()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun shouldShowActivityBackView(activity: Activity): Boolean {
return (activity is MainActivity
|| activity is ArticleDetailActivity
|| activity is ForumVideoDetailActivity
|| activity is ForumDetailActivity
|| activity is ForumListActivity
|| activity is NewQuestionDetailActivity)
}
override fun onActivityPaused(activity: Activity) {
CurrentActivityHolder.activitySet.remove(activity)
FloatingBackViewManager.dismissBackView()
if (HaloApp.isUserAcceptPrivacyPolicy(activity)) {
DataUtils.onPause(activity)
}
if (activity.isFinishing) {
AppManager.getInstance().finishActivity(activity)
}
}
override fun onActivityStopped(activity: Activity) {
Notifier.hide()
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityDestroyed(activity: Activity) {
AppManager.getInstance().finishActivity(activity)
}
}

View File

@ -12,26 +12,12 @@ import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.ActionMenuView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.common.constant.Constants;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.SPUtils;
import com.gh.common.view.GameIconView;
import com.gh.common.util.MtaHelper;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.R;
@ -48,49 +34,39 @@ import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
/**
* 需要用到工具栏的页面使用
* <p>
* 特殊页面请参考{@link BaseActivity}
*/
public abstract class ToolBarActivity extends BaseActivity implements ToolbarController, ActionMenuView.OnMenuItemClickListener {
public abstract class ToolBarActivity extends BaseActivity implements ToolbarController, Toolbar.OnMenuItemClickListener {
@Nullable
private PackageViewModel mPackageViewModel;
protected View mToolbarContainer;
protected Toolbar mToolbar;
protected TextView mTitleTv;
protected LinearLayout mTitleContainer;
protected LinearLayout mIconTitleContainer;
protected FrameLayout mBackContainer;
protected ActionMenuView mActionMenuView;
protected View mBackBtn;
protected GameIconView mGameIconView;
protected SimpleDraweeView mUserAvatarIv;
protected TextView mIconTitle;
@Nullable
private TextView mDownloadCountHint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStatusBarDarkMode(true, this);
initToolbar();
if (!SPUtils.getBoolean(Constants.SP_TEENAGER_MODE) && showDownloadMenu()) {
if (showDownloadMenu()) {
mPackageViewModel = ViewModelProviders.of(this, new PackageViewModel.Factory()).get(PackageViewModel.class);
mPackageViewModel.getFilterSameUpdateLiveData().observe(this, this::updateDownloadCountHint);
}
@ -112,23 +88,12 @@ public abstract class ToolBarActivity extends BaseActivity implements ToolbarCon
}
private void initToolbar() {
mToolbarContainer = findViewById(R.id.normal_toolbar_container);
mToolbar = findViewById(R.id.normal_toolbar);
mTitleTv = findViewById(R.id.normal_title);
mActionMenuView = findViewById(R.id.actionMenuView);
mTitleContainer = findViewById(R.id.titleContainer);
mIconTitleContainer = findViewById(R.id.iconTitleContainer);
mBackContainer = findViewById(R.id.backContainer);
mBackBtn = findViewById(R.id.backBtn);
mGameIconView = findViewById(R.id.gameIv);
mUserAvatarIv = findViewById(R.id.userAvatar);
mIconTitle = findViewById(R.id.iconTitle);
if (mToolbar != null) {
// setSupportActionBar(mToolbar); // 替换actionBar后 toolBar无法控制
// mToolbar.setNavigationIcon(provideNavigationIcon());
// mToolbar.setNavigationOnClickListener(provideNavigationItemClickListener());
if (mBackBtn != null) mBackBtn.setOnClickListener(provideNavigationItemClickListener());
if (mBackContainer != null) mBackContainer.setOnClickListener(provideNavigationItemClickListener());
mToolbar.setNavigationIcon(provideNavigationIcon());
mToolbar.setNavigationOnClickListener(provideNavigationItemClickListener());
if (mTitleTv != null) {
mTitleTv.setOnClickListener(view -> {
final List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
@ -150,7 +115,6 @@ public abstract class ToolBarActivity extends BaseActivity implements ToolbarCon
@Override
public void setNavigationTitle(String title) {
if (mTitleTv != null) mTitleTv.setText(title);
if (mIconTitle != null) mIconTitle.setText(title);
}
@Override
@ -167,20 +131,15 @@ public abstract class ToolBarActivity extends BaseActivity implements ToolbarCon
@Override
public void setToolbarMenu(int res) {
if (mActionMenuView == null) return;
// 青少年模式下要隐藏下载按钮
if (SPUtils.getBoolean(Constants.SP_TEENAGER_MODE) && res == R.menu.menu_download) return;
// mToolbar.inflateMenu(res);
// mToolbar.setOnMenuItemClickListener(this);
getMenuInflater().inflate(res, mActionMenuView.getMenu());
mActionMenuView.setOnMenuItemClickListener(this);
if (mToolbar == null) return;
mToolbar.inflateMenu(res);
mToolbar.setOnMenuItemClickListener(this);
if (showDownloadMenu()) {
createDownloadMenu(res);
}
Menu menu = mActionMenuView.getMenu();
Menu menu = mToolbar.getMenu();
for (int i = 0; i < menu.size(); i++) {
MenuItem menuItem = menu.getItem(i);
// menu设置actionLayout后无法捕捉点击事件以icon为tag如果icon is null 手动设置menuItem点击事件
@ -191,61 +150,51 @@ public abstract class ToolBarActivity extends BaseActivity implements ToolbarCon
}
}
if (showToolbarAtLeft() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mTitleTv != null) {
mTitleTv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
// 限制标题实际宽度 防止标题挡住toolbar menu按钮
if (menu.size() > 2 && mTitleTv != null) {
ViewGroup.LayoutParams layoutParams = mTitleTv.getLayoutParams();
if (layoutParams instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) layoutParams;
if (showToolbarAtLeft()) {
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.CENTER_VERTICAL);
params.setMargins(DisplayUtils.dip2px(55), 0, DisplayUtils.dip2px(48 * menu.size()), 0);
} else {
params.setMargins(DisplayUtils.dip2px(90), 0, DisplayUtils.dip2px(90), 0);
}
mTitleTv.setLayoutParams(params);
}
} else {
if (showToolbarAtLeft()) {
ViewGroup.LayoutParams layoutParams = mTitleTv.getLayoutParams();
if (layoutParams instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) layoutParams;
params.addRule(RelativeLayout.CENTER_VERTICAL);
params.setMargins(DisplayUtils.dip2px(55), 0, DisplayUtils.dip2px(48 * menu.size()), 0);
mTitleTv.setLayoutParams(params);
}
}
}
setTitleCenter();
}
@Override
protected void onResume() {
super.onResume();
setTitleCenter();
}
// 设置标题居中
public void setTitleCenter() {
if (mActionMenuView != null && mTitleContainer != null && mBackContainer != null && !showToolbarAtLeft()) {
mActionMenuView.post(() -> {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mTitleContainer.getLayoutParams();
params.setMargins(mActionMenuView.getWidth() - mBackContainer.getWidth(), 0, 0, 0);
mTitleContainer.setLayoutParams(params);
});
}
}
public void setGameIconToolbar(String icon, String iconSubscript) {
mTitleContainer.setVisibility(View.GONE);
mGameIconView.displayGameIcon(icon, iconSubscript);
mGameIconView.setVisibility(View.VISIBLE);
mIconTitleContainer.setVisibility(View.VISIBLE);
}
public void setUserAvatarIconToolbar(String icon) {
mTitleContainer.setVisibility(View.GONE);
ImageUtils.display(mUserAvatarIv, icon);
mUserAvatarIv.setVisibility(View.VISIBLE);
mIconTitleContainer.setVisibility(View.VISIBLE);
}
private void createDownloadMenu(int res) {
if (res != R.menu.menu_download) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_download, mActionMenuView.getMenu());
inflater.inflate(R.menu.menu_download, mToolbar.getMenu());
}
if (mPackageViewModel != null) {
updateDownloadCountHint(mPackageViewModel.getFilterSameUpdateLiveData().getValue());
}
View downloadMenuView = mActionMenuView.getMenu().findItem(R.id.menu_download).getActionView();
View downloadMenuView = mToolbar.getMenu().findItem(R.id.menu_download).getActionView();
mDownloadCountHint = downloadMenuView.findViewById(R.id.menu_download_count_hint);
}
private void updateDownloadCountHint(List<GameUpdateEntity> updateList) {
if (mDownloadCountHint == null) return;
String count = DownloadManager.getInstance().getDownloadOrUpdateCount(updateList);
String count = DownloadManager.getInstance(getApplicationContext()).getDownloadOrUpdateCount(updateList);
if (count != null) {
mDownloadCountHint.setVisibility(View.VISIBLE);
mDownloadCountHint.setText(count);
@ -266,7 +215,7 @@ public abstract class ToolBarActivity extends BaseActivity implements ToolbarCon
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(EBDownloadStatus status) {
if (!SPUtils.getBoolean(Constants.SP_TEENAGER_MODE) && showDownloadMenu() && mPackageViewModel != null) {
if (showDownloadMenu() && mPackageViewModel != null) {
updateDownloadCountHint(mPackageViewModel.getFilterSameUpdateLiveData().getValue());
}
}
@ -274,24 +223,23 @@ public abstract class ToolBarActivity extends BaseActivity implements ToolbarCon
@Override
public MenuItem getMenuItem(int res) {
if (mToolbar == null) return null; //后续页面做好判断
return mActionMenuView.getMenu().findItem(res);
return mToolbar.getMenu().findItem(res);
}
public void clearMenu() {
if (mToolbar != null) {
mActionMenuView.getMenu().clear();
setTitleCenter();
mToolbar.getMenu().clear();
}
}
public Menu getMenu() {
return mActionMenuView.getMenu();
return mToolbar.getMenu();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.menu_download) {
// MtaHelper.onEvent("下载管理", "下载管理入口", getActivityNameInChinese());
MtaHelper.onEvent("下载管理", "下载管理入口", getActivityNameInChinese());
Intent intent = DownloadManagerActivity.getDownloadMangerIntent(this, mEntrance);
startActivity(intent);
}
@ -305,32 +253,4 @@ public abstract class ToolBarActivity extends BaseActivity implements ToolbarCon
protected boolean showDownloadMenu() {
return false;
}
@Override
public void hideToolbar(boolean isHide) {
if (mToolbarContainer != null) {
mToolbarContainer.setVisibility(isHide ? View.GONE : View.VISIBLE);
}
}
@Override
protected void onNightModeChange() {
super.onNightModeChange();
if (mToolbar != null) {
mToolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.background_white));
}
if (mBackBtn != null) {
if (mBackBtn instanceof ImageView) {
((ImageView) mBackBtn).setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_bar_back));
} else if (mBackBtn instanceof TextView) {
((TextView) mBackBtn).setTextColor(ContextCompat.getColor(this, R.color.text_subtitle));
}
}
if (mTitleTv != null) {
mTitleTv.setTextColor(ContextCompat.getColor(this, R.color.text_black));
}
if (showDownloadMenu() && getMenuItem(R.id.menu_download) != null) {
((ImageView) getMenuItem(R.id.menu_download).getActionView().findViewById(R.id.menu_download_iv)).setImageDrawable(ContextCompat.getDrawable(this, R.drawable.toolbar_download));
}
}
}

View File

@ -1,27 +1,19 @@
package com.gh.base.fragment;
import android.app.Dialog;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.Lifecycle;
import com.gh.common.util.ClickUtils;
import com.gh.common.util.NightModeUtils;
import com.gh.gamecenter.R;
import com.lightgame.utils.RuntimeUtils;
import com.lightgame.utils.Utils;
import java.lang.reflect.Field;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;
/**
* @author CsHeng
* @Date 17/05/2017
@ -30,18 +22,10 @@ import androidx.lifecycle.Lifecycle;
public class BaseDialogFragment extends DialogFragment {
protected boolean mNightMode;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNightMode = NightModeUtils.INSTANCE.isNightMode(requireContext());
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = new Dialog(getActivity(), getThemeRes());
final Dialog dialog = new Dialog(getActivity(), R.style.DialogWindowTransparent);
dialog.setCanceledOnTouchOutside(false);
dialog.setOnKeyListener((dialog1, keyCode, event) -> {
if (keyCode == KeyEvent.KEYCODE_BACK && !ClickUtils.isFastDoubleClick()) {
@ -53,10 +37,6 @@ public class BaseDialogFragment extends DialogFragment {
return dialog;
}
public int getThemeRes() {
return R.style.DialogWindowTransparent;
}
public void toast(@StringRes int res) {
if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
toast(getString(res));
@ -78,43 +58,6 @@ public class BaseDialogFragment extends DialogFragment {
public boolean onBack() {
return false;
}
@Override
public void show(@NonNull FragmentManager manager, @Nullable String tag) {
Fragment fragment = manager.findFragmentByTag(tag);
if (fragment != null) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.show(fragment);
transaction.commit();
} else {
try {
Class<?> clazz = DialogFragment.class;
Field dismissed = clazz.getDeclaredField("mDismissed");
dismissed.setAccessible(true);
dismissed.set(this, false);
Field shownByMe = clazz.getDeclaredField("mShownByMe");
shownByMe.setAccessible(true);
shownByMe.set(this, true);
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(this, tag);
transaction.commitAllowingStateLoss();
} catch (Exception e) {
super.show(manager, tag);
e.printStackTrace();
}
}
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
onNightModeChange();
}
protected void onNightModeChange() {
mNightMode = NightModeUtils.INSTANCE.isNightMode(requireContext());
}
}

View File

@ -1,7 +1,6 @@
package com.gh.base.fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
@ -9,25 +8,11 @@ import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.gh.base.OnListClickListener;
import com.gh.base.OnRequestCallBackListener;
import com.gh.common.constant.Constants;
import com.gh.common.syncpage.ISyncAdapterHandler;
import com.gh.common.syncpage.SyncDataEntity;
import com.gh.common.syncpage.SyncPageRepository;
import com.gh.common.util.NightModeUtils;
import com.gh.gamecenter.BuildConfig;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBMiPush;
import com.lightgame.OnTitleClickListener;
import com.lightgame.utils.RuntimeUtils;
@ -38,13 +23,18 @@ import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import kotlin.Pair;
import static com.gh.common.util.EntranceUtils.KEY_ENTRANCE;
@ -61,12 +51,8 @@ public abstract class BaseFragment<T> extends Fragment implements OnRequestCallB
protected boolean isEverPause;
protected boolean mNightMode;
@NonNull
protected String mEntrance = "";
public long startPageTime = 0;
protected String mEntrance;
protected final Handler mBaseHandler = new BaseFragment.BaseHandler(this);
@ -115,12 +101,6 @@ public abstract class BaseFragment<T> extends Fragment implements OnRequestCallB
protected void initView(View view) {
View mBackBtn = view.findViewById(R.id.backBtn);
View mBackContainer = view.findViewById(R.id.backContainer);
if (mBackBtn != null && mBackContainer != null) {
mBackBtn.setOnClickListener(v -> requireActivity().onBackPressed());
mBackContainer.setOnClickListener(v -> requireActivity().onBackPressed());
}
}
protected void postRunnable(Runnable runnable) {
@ -153,61 +133,14 @@ public abstract class BaseFragment<T> extends Fragment implements OnRequestCallB
EventBus.getDefault().register(this);
// For data binding.
mCachedView = getInflatedLayout();
if (mCachedView == null) {
if (getInflatedLayout() != null) {
mCachedView = getInflatedLayout();
} else {
mCachedView = View.inflate(getContext(), getLayoutId(), null);
}
ButterKnife.bind(this, mCachedView);
initView(mCachedView);
if (addSyncPageObserver()) {
initSyncPageObserver();
}
if (BuildConfig.IS_NIGHT_MODE_ON) {
mNightMode = NightModeUtils.INSTANCE.isNightMode(requireContext());
} else {
mNightMode = false;
}
}
private void initSyncPageObserver() {
SyncPageRepository.INSTANCE.getSyncPageLiveData().observe(this, syncDataEntities -> {
try {
Utils.log("SyncPageRepository initSyncPageObserver->" + syncDataEntities);
List<SyncDataEntity> readyRemoveList = new ArrayList<>();
if (syncDataEntities == null || syncDataEntities.isEmpty()) return;
RecyclerView.Adapter adapter = provideSyncAdapter();
if (!(adapter instanceof ISyncAdapterHandler)) return;
for (int i = 0; i < adapter.getItemCount(); i++) {
Pair<String, Object> syncKey = ((ISyncAdapterHandler) adapter).getSyncData(i);
if (syncKey == null) continue;
for (SyncDataEntity syncDataEntity : syncDataEntities) {
if (syncDataEntity.getSyncId().equals(syncKey.getFirst())) {
boolean isSuccess = SyncPageRepository.INSTANCE.handleSyncData(syncKey.getSecond(), syncDataEntity);
if (isSuccess) {
if (BuildConfig.DEBUG) {
Utils.log("SyncPageRepository notify position->" + i);
}
adapter.notifyItemChanged(i);
if (syncDataEntity.getRemove()) {
readyRemoveList.add(syncDataEntity);
}
}
}
}
}
mBaseHandler.postDelayed(() -> SyncPageRepository.removeSyncData(readyRemoveList), 2000);
} catch (Exception e) {
if (BuildConfig.DEBUG) {
throw e;
} else {
e.printStackTrace();
}
}
});
}
// 必须的有subscribe才能register
@ -221,32 +154,14 @@ public abstract class BaseFragment<T> extends Fragment implements OnRequestCallB
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (container != null) {
container.removeView(mCachedView);
// TODO 页面重建 (framgent 的重新获取) 有大问题,这里只是修修补补
if (mCachedView != null && mCachedView.getParent() instanceof ViewGroup) {
((ViewGroup) mCachedView.getParent()).removeView(mCachedView);
}
}
return mCachedView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mCachedView = null;
}
@Override
public void onResume() {
super.onResume();
isEverPause = false;
startPageTime = System.currentTimeMillis();
if (BuildConfig.IS_NIGHT_MODE_ON
&& !NightModeUtils.INSTANCE.getSystemMode()
&& mNightMode != NightModeUtils.INSTANCE.isNightMode(requireContext())) {
onNightModeChange();
}
}
@Override
@ -268,7 +183,11 @@ public abstract class BaseFragment<T> extends Fragment implements OnRequestCallB
}
public void toast(String msg) {
Utils.toast(getContext(), msg);
try {
Utils.toast(getContext(), msg);
} catch (Exception ignore) {
}
}
public void toastLong(@StringRes int msg) {
@ -332,34 +251,8 @@ public abstract class BaseFragment<T> extends Fragment implements OnRequestCallB
// 为 fragment 附加 bundle (setArgument())
public BaseFragment with(Bundle bundle) {
if (!isStateSaved()) {
this.setArguments(bundle);
}
this.setArguments(bundle);
return this;
}
public void onParentActivityFinish() {
}
@Nullable
protected RecyclerView.Adapter provideSyncAdapter() {
return null;
}
protected boolean addSyncPageObserver() {
return false;
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (BuildConfig.IS_NIGHT_MODE_ON) {
onNightModeChange();
}
}
protected void onNightModeChange() {
mNightMode = NightModeUtils.INSTANCE.isNightMode(requireContext());
}
}

View File

@ -1,32 +1,25 @@
package com.gh.base.fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import com.gh.base.adapter.FragmentAdapter;
import com.gh.common.view.TabIndicatorView;
import com.gh.gamecenter.R;
import com.gh.gamecenter.normal.NormalFragment;
import com.google.android.material.tabs.TabLayout;
import com.halo.assistant.HaloApp;
import com.lightgame.utils.Utils;
import com.lightgame.view.NoScrollableViewPager;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
/**
* Created by khy on 15/03/18.
*/
@ -35,11 +28,12 @@ public abstract class BaseFragment_TabLayout extends NormalFragment implements V
public static final String PAGE_INDEX = "PAGE_INDEX";
@BindView(R.id.fragment_tab_layout)
protected TabLayout mTabLayout;
@BindView(R.id.fragment_view_pager)
protected NoScrollableViewPager mViewPager;
@BindView(R.id.fragment_tab_indicator)
protected TabIndicatorView mTabIndicatorView;
@Nullable
protected View mDividerLineView;
protected List<Fragment> mFragmentsList;
@ -52,7 +46,7 @@ public abstract class BaseFragment_TabLayout extends NormalFragment implements V
protected abstract void initTabTitleList(List<String> tabTitleList);
protected int provideIndicatorWidth() {
return 20;
return 65;
}
protected View provideTabView(int position, String tabTitle) {
@ -75,38 +69,19 @@ public abstract class BaseFragment_TabLayout extends NormalFragment implements V
}
}
private ArrayList<Fragment> restoreFragments() {
String tag = "android:switcher:" + mViewPager.getId() + ":";
ArrayList<Fragment> fragments = new ArrayList<>();
int childCount = mTabTitleList.size();
for (int index = 0; index < childCount; index++) {
Fragment fragment = getChildFragmentManager().findFragmentByTag(tag + index);
if (fragment != null) {
fragments.add(fragment);
}
}
return fragments;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) mCheckedIndex = getArguments().getInt(PAGE_INDEX, 0);
mFragmentsList = new ArrayList<>();
initFragmentList(mFragmentsList);
mTabTitleList = new ArrayList<>();
initTabTitleList(mTabTitleList);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mTabLayout = view.findViewById(R.id.fragment_tab_layout);
mViewPager = view.findViewById(R.id.fragment_view_pager);
mTabIndicatorView = view.findViewById(R.id.fragment_tab_indicator);
mDividerLineView = view.findViewById(R.id.dividerLine);
if (getArguments() != null) mCheckedIndex = getArguments().getInt(PAGE_INDEX, 0);
mTabTitleList = new ArrayList<>();
initTabTitleList(mTabTitleList);
mFragmentsList = new ArrayList<>(restoreFragments());
if (mFragmentsList.isEmpty() || mFragmentsList.size() != mTabTitleList.size()) {
mFragmentsList.clear();
initFragmentList(mFragmentsList);
}
mViewPager.setOffscreenPageLimit(mFragmentsList.size());
mViewPager.addOnPageChangeListener(this);
mViewPager.setAdapter(new FragmentAdapter(getChildFragmentManager(), mFragmentsList, mTabTitleList));
@ -119,72 +94,11 @@ public abstract class BaseFragment_TabLayout extends NormalFragment implements V
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
if (tab == null) continue;
String tabTitle = tab.getText() != null ? tab.getText().toString() : "";
View tabView = provideTabView(i, tabTitle);
if (tabView == null) tabView = createDefaultTabCustomView(requireContext(), tabTitle);
View tabView = provideTabView(i, tab.getText() != null ? tab.getText().toString() : "");
if (tabView == null) continue;
tab.setCustomView(tabView);
}
initTabStyle(mTabLayout, mCheckedIndex);
}
public static void initTabStyle(TabLayout tabLayout, int currentItem) {
// 默认选择addOnTabSelectedListener不会回调
int tabCount = tabLayout.getTabCount();
if (tabCount > 0) {
TabLayout.Tab tab = tabLayout.getTabAt(currentItem);
if (tab != null) updateTabStyle(tab, true);
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
updateTabStyle(tab, true);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
updateTabStyle(tab, false);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
updateTabStyle(tab, true);
}
});
}
public static void updateTabStyle(TabLayout.Tab tab, boolean isChecked) {
View tabView = tab.getCustomView();
if (tabView == null) {
Utils.log("TabLayout->Tab样式不是通用样式,请检查");
return;
}
TextView tabTitle;
if (tabView instanceof TextView) {
tabTitle = (TextView) tabView;
} else {
tabTitle = tabView.findViewById(R.id.tab_title);
}
if (tabTitle == null) {
Utils.log("TabLayout->Tab样式不是通用样式,请检查");
return;
}
tabTitle.setTypeface(isChecked ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
tabTitle.setTextColor(ContextCompat.getColorStateList(tabTitle.getContext(), R.color.text_tabbar_style));
}
// 如果不设置View的话无法动态设置字体样式
@NonNull
public static View createDefaultTabCustomView(Context context, String title) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_item, null);
View tabTitle = view.findViewById(R.id.tab_title);
if (tabTitle instanceof CheckedTextView) {
((CheckedTextView) tabTitle).setText(title);
}
return view;
}
@Override
@ -201,22 +115,4 @@ public abstract class BaseFragment_TabLayout extends NormalFragment implements V
public void onPageScrollStateChanged(int state) {
}
@Override
protected void onNightModeChange() {
super.onNightModeChange();
View container = requireView().findViewById(R.id.fragment_tab_container);
if (container != null) {
container.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.background_white));
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
if (tab != null) {
updateTabStyle(tab, tab.isSelected());
}
}
}
if (mDividerLineView != null) {
mDividerLineView.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.divider));
}
}
}

View File

@ -11,14 +11,12 @@ package com.gh.base.fragment;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import com.gh.gamecenter.normal.NormalFragment;
@ -55,21 +53,19 @@ public abstract class BaseFragment_ViewPager extends NormalFragment implements D
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mViewPager = view.findViewById(getViewPagerId());
mFragmentsList = restoreFragments();
if (mFragmentsList.size() == 0) {
initFragmentList(mFragmentsList);
}
mFragmentsList = new ArrayList<>();
initFragmentList(mFragmentsList);
mAdapter = BaseFragmentPagerAdapter.newInstance(getChildFragmentManager(), mFragmentsList);
final Bundle args = getArguments();
if (args != null) {
mCheckedIndex = args.getInt(ARGS_INDEX);
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mViewPager = (ViewPager) view.findViewById(getViewPagerId());
mViewPager.setOffscreenPageLimit(mFragmentsList.size());
mViewPager.setAdapter(mAdapter);
if (mCheckedIndex < mFragmentsList.size()) {
@ -120,24 +116,9 @@ public abstract class BaseFragment_ViewPager extends NormalFragment implements D
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
public ArrayList<Fragment> restoreFragments() {
String tag = "android:switcher:" + mViewPager.getId() + ":";
ArrayList<Fragment> fragments = new ArrayList<>();
int childCount = getChildCount();
for (int index = 0; index < childCount; index++) {
Fragment fragment = getChildFragmentManager().findFragmentByTag(tag + index);
if (fragment != null) {
fragments.add(fragment);
}
}
return fragments;
}
public abstract int getChildCount();
public int getCurrentItem() {
return mViewPager != null ? mViewPager.getCurrentItem() : 0;
}

View File

@ -12,10 +12,10 @@ abstract class BaseLazyFragment : NormalFragment() {
private var isViewCreated = false
protected var isSupportVisible = false
private var isSupportVisible = false
/**
* 用于分发可见时间的时候获取 fragment 是否隐藏
* 用于分发可见时间的时候获取 fragment 是否隐藏
*
* @return true fragment 不可见, false 父 fragment 可见
*/
@ -104,13 +104,6 @@ abstract class BaseLazyFragment : NormalFragment() {
isSupportVisible = visible
if (visible) {
// TODO 当 fragment 重建时这里的被调用很奇怪onActivityCreated 回调触发,但此时的 view 是空的,原因是 createView 还没被调用
// TODO 这样就造成了 onFragmentResume 里可能用到 view 的地方出现空指针异常,所以这里遇到 view 为空的时候 return 等下一次被调用才进去
if (view == null) {
return
}
if (mIsFirstVisible) {
mIsFirstVisible = false
onFragmentFirstVisible()
@ -118,11 +111,8 @@ abstract class BaseLazyFragment : NormalFragment() {
onFragmentResume()
dispatchChildVisibleState(true)
} else {
// 当 fragment 重建时,这个代码块可能在第一次 view 为空的 visible 后调用导致在 onFragmentPause 里可能用到 view 的地方出现空指针异常
if (!mIsFirstVisible) {
dispatchChildVisibleState(false)
onFragmentPause()
}
dispatchChildVisibleState(false)
onFragmentPause()
}
}

View File

@ -1,142 +0,0 @@
package com.gh.base.fragment
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.gh.base.adapter.FragmentAdapter
import com.gh.common.view.TabIndicatorView
import com.gh.gamecenter.R
import com.google.android.material.tabs.TabLayout
import com.lightgame.view.NoScrollableViewPager
abstract class BaseLazyTabFragment : BaseLazyFragment(), ViewPager.OnPageChangeListener {
lateinit var mTabLayout: TabLayout
lateinit var mViewPager: NoScrollableViewPager
lateinit var mTabIndicatorView: TabIndicatorView
var mFragmentsList: MutableList<Fragment> = arrayListOf()
var mTabTitleList: MutableList<String> = arrayListOf()
var mCheckedIndex = 0
abstract fun initFragmentList(fragments: MutableList<Fragment>)
abstract fun initTabTitleList(tabTitleList: MutableList<String>)
protected open fun provideIndicatorWidth(): Int {
return 20
}
protected open fun provideTabView(position: Int, tabTitle: String?): View? {
return null
}
override fun getLayoutId(): Int {
return R.layout.fragment_tablayout_viewpager
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val fragments = childFragmentManager.fragments
if (fragments != null) {
for (fragment in fragments) {
fragment.onActivityResult(requestCode, resultCode, data)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) mCheckedIndex = requireArguments().getInt(PAGE_INDEX, 0)
}
open fun providePagerAdapter(): PagerAdapter? {
return null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mTabLayout = view.findViewById(R.id.fragment_tab_layout)
mViewPager = view.findViewById(R.id.fragment_view_pager)
mTabIndicatorView = view.findViewById(R.id.fragment_tab_indicator)
}
override fun onFragmentFirstVisible() {
super.onFragmentFirstVisible()
mTabTitleList.clear()
mFragmentsList.clear()
initTabTitleList(mTabTitleList)
mFragmentsList.addAll(restoreFragments())
if (mFragmentsList.isEmpty() || mFragmentsList.size != mTabTitleList.size) {
mFragmentsList.clear()
initFragmentList(mFragmentsList)
}
mViewPager.offscreenPageLimit = mFragmentsList.size
mViewPager.addOnPageChangeListener(this)
mViewPager.adapter = providePagerAdapter()
?: FragmentAdapter(childFragmentManager, mFragmentsList, mTabTitleList)
mViewPager.currentItem = mCheckedIndex
mTabLayout.setupWithViewPager(mViewPager)
mTabIndicatorView.setupWithTabLayout(mTabLayout)
mTabIndicatorView.setupWithViewPager(mViewPager)
mTabIndicatorView.setIndicatorWidth(provideIndicatorWidth())
for (i in 0 until mTabLayout.tabCount) {
val tab = mTabLayout.getTabAt(i) ?: continue
val tabTitle = if (tab.text != null) tab.text.toString() else ""
var tabView = provideTabView(i, tabTitle)
if (tabView == null) tabView = BaseFragment_TabLayout.createDefaultTabCustomView(requireContext(), tabTitle)
tab.customView = tabView
}
BaseFragment_TabLayout.initTabStyle(mTabLayout, mCheckedIndex)
}
private fun restoreFragments(): ArrayList<Fragment> {
val tag = "android:switcher:${mViewPager.id}:"
val fragments = ArrayList<Fragment>()
val childCount = mTabTitleList.size
for (index in 0 until childCount) {
val fragment = childFragmentManager.findFragmentByTag("$tag$index")
if (fragment != null) {
restoreFragment(fragment)
fragments.add(fragment)
}
}
return fragments
}
open fun restoreFragment(fragment: Fragment) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {}
override fun onPageScrollStateChanged(state: Int) {}
override fun onNightModeChange() {
super.onNightModeChange()
val container = requireView().findViewById<View>(R.id.fragment_tab_container)
if (container != null) {
container.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.background_white))
for (i in 0 until mTabLayout.tabCount) {
val tab = mTabLayout.getTabAt(i)
if (tab != null) {
BaseFragment_TabLayout.updateTabStyle(tab, tab.isSelected)
}
}
}
}
companion object {
const val PAGE_INDEX = "PAGE_INDEX"
}
}

View File

@ -1,99 +0,0 @@
package com.gh.base.fragment
import android.os.Bundle
import android.view.View
import android.view.ViewStub
import com.gh.gamecenter.R
/**
* 这是在 BaseLazyFragment 之上添加了一些通用功能的抽象类
*
* 怎么将一个已有的 fragment 转化为懒加载 (延迟渲染) 的 fragment 呢?
* (继承 ListFragment 的类请改为继承 LazyListFragment)
*
* 0. 删掉旧的 getInflatedLayout() 的代码,现在由 getStubLayoutId() 提供 Stub 布局 (默认为 R.layout.fragment_stub若重写请注意提供 id 为 stub 的 ViewStub
* 1. 重写 getRealLayoutId(),提供实际要延迟渲染的 layout Id
* 1. 将原有在 onCreate() 的代码移动到 onFragmentFirstVisible()
* 2. 将原有在 onViewCreated() 的代码移动到 initRealView()
* 注意initRealView() 在 onFragmentFirstVisible() 中被调用,如果要初始化 viewModel 等非 UI 对象请在 super.onFragmentVisible() 调用)
* 3. 如需使用 ViewBinding ,在 onRealLayoutInflated() 的回调中初始化 ViewBinding 即可
* 4. onResume() 的代码移动到 onFragmentResume()onPause() 的代码移动到 onFragmentPause()
* 5. Done!
*/
abstract class LazyFragment : BaseLazyFragment() {
// ViewStub + ViewBinding 有莫名的 bug语法上没问题但编译时通不过。
private var mViewStub: ViewStub? = null
private var mIsRecreatedByFragmentManager = false
override fun onCreate(savedInstanceState: Bundle?) {
if (savedInstanceState != null) {
mIsRecreatedByFragmentManager = true
}
super.onCreate(savedInstanceState)
}
@Deprecated(
"使用了 LazyFragment 以后不要 override getLayoutId(),建议 override getRealLayoutId() 或者 getStubLayoutId()",
ReplaceWith("LazyFragment.getRealLayoutId()")
)
override fun getLayoutId() = if (isRecreatedByFragmentManager()) {
getRealLayoutId()
} else {
getStubLayoutId()
}
override fun initView(view: View?) {
super.initView(view)
if (!isRecreatedByFragmentManager()) {
mViewStub = mCachedView.findViewById(R.id.stub)
}
}
override fun onFragmentFirstVisible() {
super.onFragmentFirstVisible()
inflateRealView()
initRealView()
}
/**
* 真正 inflate View 的地方
*/
protected open fun inflateRealView() {
if (isRecreatedByFragmentManager()) {
onRealLayoutInflated(mCachedView)
} else {
mViewStub?.layoutResource = getRealLayoutId()
mViewStub?.setOnInflateListener { _, inflatedView -> onRealLayoutInflated(inflatedView) }
mViewStub?.inflate()?.let { mCachedView = it }
}
}
protected fun isRecreatedByFragmentManager() = mIsRecreatedByFragmentManager
/**
* 请在这个方法之后获取初始化后的各种 view
*
* 替换旧 fragment 实现时,等同于 onViewCreated
*/
protected open fun initRealView() {}
/**
* 提供要 stub inflate 的 layout
*/
protected abstract fun getRealLayoutId(): Int
/**
* 提供含有 stub 的 layout
*/
protected open fun getStubLayoutId(): Int {
return R.layout.fragment_stub
}
/**
* 真实 layout inflate 完成的回调,可用于 viewBinding
*/
protected open fun onRealLayoutInflated(inflatedView: View) {}
}

View File

@ -4,15 +4,12 @@ import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.ExtensionsKt;
import com.gh.gamecenter.R;
/**
@ -55,14 +52,6 @@ public class WaitingDialogFragment extends BaseDialogFragment {
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
WindowManager.LayoutParams layoutParams = getDialog().getWindow().getAttributes();
layoutParams.width = DisplayUtils.dip2px(160);
getDialog().getWindow().setAttributes(layoutParams);
}
@Override
public void show(FragmentManager manager, String tag) {
try {
@ -92,17 +81,8 @@ public class WaitingDialogFragment extends BaseDialogFragment {
@Override
public void dismiss() {
dismissAllowingStateLoss();
}
@Override
public void dismissAllowingStateLoss() {
mBackListener = null;
try {
super.dismissAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
}
super.dismiss();
}
public static class WaitingDialogData {

View File

@ -2,51 +2,14 @@ package com.gh.common
import android.os.Handler
import android.os.Looper
import com.gh.base.GHThreadFactory
import com.gh.common.AppExecutor.heavyWeightIoExecutor
import com.gh.common.AppExecutor.ioExecutor
import com.gh.common.AppExecutor.lightWeightIoExecutor
import com.gh.common.AppExecutor.logExecutor
import com.gh.common.AppExecutor.uiExecutor
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.*
import java.util.concurrent.Executor
import java.util.concurrent.Executors
/**
* APP 线程池管理类
*
* [ioExecutor] 是一个最大线程数固定的线程池,较为繁重的 IO 任务可以交给它
* [uiExecutor] 是主线程的包裹,需要切换至主线程执行可以用它
* [lightWeightIoExecutor] 是一个单线程的线程池,轻量级且需要保证同一线程的 IO 任务可以交给它
* [heavyWeightIoExecutor] 重量级的线程池,一些高频调用但不用保证结果的任务可以交给它
* [logExecutor] 只为上传 log 而使用的线程池
*/
object AppExecutor {
private val mCoreSize = Runtime.getRuntime().availableProcessors()
private val mMinimumPoolSize = 6.coerceAtLeast(mCoreSize)
private val mMaximumPoolSize = 24.coerceAtLeast(mCoreSize * 3)
@JvmStatic
val uiExecutor by lazy { MainThreadExecutor() }
var ioExecutor = Executors.newSingleThreadExecutor()
@JvmStatic
val lightWeightIoExecutor: ExecutorService by lazy { Executors.newSingleThreadExecutor(GHThreadFactory("GH_LIGHT_WEIGHT_IO_THREAD")) }
@JvmStatic
val heavyWeightIoExecutor: ExecutorService by lazy { Executors.newFixedThreadPool(2, GHThreadFactory("GH_HEAVY_WEIGHT_IO_THREAD")) }
@JvmStatic
val logExecutor: ExecutorService by lazy { Executors.newSingleThreadExecutor(GHThreadFactory("GH_LOG_THREAD")) }
@JvmStatic
val ioExecutor = ThreadPoolExecutor(
mMinimumPoolSize,
mMaximumPoolSize,
20L, TimeUnit.SECONDS,
LinkedBlockingQueue(256),
GHThreadFactory("GH_IO_THREAD"))
val cachedScheduler by lazy { Schedulers.from(ioExecutor) }
var uiExecutor = MainThreadExecutor()
class MainThreadExecutor : Executor {
private val mainThreadHandler = Handler(Looper.getMainLooper())
@ -61,14 +24,10 @@ object AppExecutor {
}
}
fun runOnIoThread(isLightWeightTask: Boolean = false, isHeavyWightTask: Boolean = false, f: () -> Unit) {
when {
isLightWeightTask -> lightWeightIoExecutor.execute(f)
isHeavyWightTask -> heavyWeightIoExecutor.execute(f)
else -> ioExecutor.execute(f)
}
fun runOnIoThread(f: () -> Unit) {
AppExecutor.ioExecutor.execute(f)
}
fun runOnUiThread(f: () -> Unit) {
uiExecutor.execute(f)
AppExecutor.uiExecutor.execute(f)
}

View File

@ -1,41 +1,30 @@
package com.gh.common
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.Base64
import android.webkit.JavascriptInterface
import androidx.annotation.Keep
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import com.gh.base.CurrentActivityHolder
import com.gh.common.constant.Constants
import com.gh.common.loghub.LoghubUtils
import com.gh.common.tracker.Tracker
import com.gh.common.util.*
import com.gh.common.view.dsbridge.CompletionHandler
import com.gh.gamecenter.*
import com.gh.gamecenter.energy.EnergyCenterActivity
import com.gh.gamecenter.energy.EnergyHouseActivity
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.help.QaFeedbackDialogFragment
import com.gh.gamecenter.LoginActivity
import com.gh.gamecenter.ViewImageActivity
import com.gh.gamecenter.entity.Badge
import com.gh.gamecenter.manager.UserManager
import com.gh.gamecenter.personalhome.border.AvatarBorderActivity
import com.gh.gamecenter.security.BindPhoneActivity
import com.gh.gamecenter.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.room.AppDatabase
import com.gh.gamecenter.user.LoginTag
import com.gh.gamecenter.user.UserRepository
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.json.JSONObject
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.util.*
import retrofit2.HttpException
import wendu.dsbridge.CompletionHandler
class DefaultJsApi(var context: Context) {
private var mLoginHandler: CompletionHandler<Any>? = null
@JavascriptInterface
fun isGhzs(msg: Any): String {
return "true"
@ -55,7 +44,7 @@ class DefaultJsApi(var context: Context) {
@JavascriptInterface
fun getUserInfo(msg: Any): String {
return UserManager.getInstance().userInfoEntity?.toJson() ?: ""
return UserManager.getInstance().userInfoEntity.toJson()
}
@JavascriptInterface
@ -65,12 +54,8 @@ class DefaultJsApi(var context: Context) {
@JavascriptInterface
fun login(msg: Any) {
if (SPUtils.getBoolean(Constants.SP_HAS_GET_PHONE_INFO) || NetworkUtils.isOpenMobileData(context)) {
QuickLoginHelper.startLogin(context, "浏览器")
} else {
val intent = LoginActivity.getIntent(context, "浏览器")
context.startActivity(intent)
}
val intent = LoginActivity.getIntent(context, "浏览器")
context.startActivity(intent)
}
@JavascriptInterface
@ -78,11 +63,12 @@ class DefaultJsApi(var context: Context) {
val userInfoEntity = UserManager.getInstance().userInfoEntity
if (msg.toString().isNotEmpty()) {
val badge = msg.toString().toObject() ?: Badge()
userInfoEntity?.badge = badge
userInfoEntity.badge = badge
} else {
userInfoEntity?.badge = null
userInfoEntity.badge = null
}
UserManager.getInstance().userInfoEntity = userInfoEntity
AppDatabase.getInstance(context).userInfoDao().updateUserInfo(userInfoEntity)
}
@JavascriptInterface
@ -90,16 +76,6 @@ class DefaultJsApi(var context: Context) {
return HaloApp.getInstance().channel
}
@JavascriptInterface
fun getAppVersion(msg: Any): String {
return BuildConfig.VERSION_NAME
}
@JavascriptInterface
fun getAppVersionCode(msg: Any): Int {
return PackageUtils.getGhVersionCode()
}
@JavascriptInterface
fun bindWechat(msg: Any, handler: CompletionHandler<Any>) {
context.ifLogin("浏览器") {
@ -113,39 +89,35 @@ class DefaultJsApi(var context: Context) {
wechatLoginInfoMap["access_token"] = jsonContent.getString("access_token")
wechatLoginInfoMap["refresh_token"] = jsonContent.getString("refresh_token")
WechatBindHelper.bindWechat(wechatLoginInfoMap, object : BiCallback<Boolean, Boolean> {
override fun onFirst(first: Boolean) {
EnergyTaskHelper.postEnergyTask("bind_wechat")
handler.complete(true)
}
RetrofitManager.getInstance(HaloApp.getInstance().application)
.api
.postBindWechat(wechatLoginInfoMap.createRequestBody())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : BiResponse<ResponseBody>() {
override fun onSuccess(data: ResponseBody) {
handler.complete(true)
}
override fun onSecond(second: Boolean) {
handler.complete(false)
}
})
LoginHelper.unregisterCallback()
override fun onFailure(exception: Exception) {
handler.complete(false)
if (exception is HttpException) {
ErrorHelper.handleError(HaloApp.getInstance().application, exception.response().errorBody()?.string())
}
}
})
}
override fun onLoginFailure(loginType: LoginTag, error: String) {
handler.complete(false)
LoginHelper.unregisterCallback()
}
})
}
}
@JavascriptInterface
fun refreshWechatBindData(msg: Any) {
WechatBindHelper.getWechatConfig(null)
}
@JavascriptInterface
fun copyText(msg: Any) {
runOnUiThread {
msg.toString().copyTextAndToast()
}
msg.toString().copyTextAndToast()
}
@JavascriptInterface
@ -160,21 +132,7 @@ class DefaultJsApi(var context: Context) {
val context = CurrentActivityHolder.getCurrentActivity()
context?.startActivity(ImageViewerActivity.getIntent(context, imageEvent.imageList, imageEvent.position, "浏览器"))
}
@JavascriptInterface
fun isInstalled(event: Any): String {
val localInstalledPackageList = PackageUtils.getAllPackageName(HaloApp.getInstance().application)
val packageNameList: ArrayList<String> = event.toString().toObject() ?: ArrayList()
for (packageName in packageNameList) {
if (!localInstalledPackageList.contains(packageName)) {
return "false"
}
}
return "true"
context?.startActivity(ViewImageActivity.getViewImageIntent(context, imageEvent.imageList, imageEvent.position, "浏览器"))
}
@JavascriptInterface
@ -183,268 +141,13 @@ class DefaultJsApi(var context: Context) {
Base64ImageHolder.image = event.toString()
context?.startActivity(ImageViewerActivity.getBase64Intent(context, true))
context?.startActivity(ViewImageActivity.getBase64ViewImageIntent(context, true))
}
@JavascriptInterface
fun openNotificationSetting(msg: Any) {
NotificationHelper.show(context as AppCompatActivity, NotificationUgc.LOGIN)
}
@JavascriptInterface
fun useDarkStatusBarText(msg: Any) {
runOnUiThread {
DisplayUtils.transparentStatusBar(context as AppCompatActivity)
DisplayUtils.setLightStatusBar(context as AppCompatActivity, msg.toString() == "true")
}
}
@JavascriptInterface
fun exitWebView(msg: Any) {
runOnUiThread { (context as Activity).finish() }
}
@JavascriptInterface
fun updateRegulationTestStatus(msg: Any) {
if (msg.toString().toLowerCase(Locale.getDefault()) == "pass") {
EnergyTaskHelper.postEnergyTask("finish_etiquette_exam")
SPUtils.setString(Constants.SP_REGULATION_TEST_PASS_STATUS, "pass")
}
}
@JavascriptInterface
fun getStatusBarHeight(msg: Any): String {
val statusBarHeight = DisplayUtils.getStatusBarHeight(context.resources)
return "$statusBarHeight"
}
@JavascriptInterface
fun getGid(msg: Any): String {
return HaloApp.getInstance().gid
}
@JavascriptInterface
fun showIncompatibleVersionDialog(msg: Any) {
DialogHelper.showUpgradeDialog(context)
}
@JavascriptInterface
fun shareBase64Image(event: Any) {
val imageShareEvent = event.toString().toObject() ?: ImageShareEvent()
val context = CurrentActivityHolder.getCurrentActivity()
Base64ImageHolder.image = imageShareEvent.image.run {
if (this.startsWith("data:image/png;base64")) this.split(",")[1] else this
}
MessageShareUtils.getInstance(context).shareFromWeb(context, imageShareEvent.type)
}
@JavascriptInterface
fun inviteFriends(event: Any) {
val inviteEvent = event.toString().toObject() ?: InviteFriendsEvent()
val context = CurrentActivityHolder.getCurrentActivity()
if ("poster" == inviteEvent.type) {
Base64ImageHolder.image = inviteEvent.poster.run {
if (this.startsWith("data:image/png;base64")) this.split(",")[1] else this
}
MessageShareUtils.getInstance(context).shareInviteFriends(context, inviteEvent.way)
} else {
ShareUtils.getInstance(context).shareInviteFriends(context, inviteEvent.url, inviteEvent.way)
}
}
@JavascriptInterface
fun bindPhone(msg: Any) {
val intent = BindPhoneActivity.getNormalIntent(context, false)
context.startActivity(intent)
}
@JavascriptInterface
fun updateTitle(msg: Any) {
if (context is WebActivity) {
runOnUiThread { (context as WebActivity).setNavigationTitle(msg.toString()) }
}
}
@JavascriptInterface
fun logoutExitWebViewAndRedirectToLogin() {
UserRepository.getInstance().logout()
if (context is Activity) {
AppExecutor.uiExecutor.executeWithDelay(Runnable {
context.ifLogin("内部网页")
(context as Activity).finish()
}, 100)
}
}
@JavascriptInterface
fun openInNewWebview(url: Any) {
runOnUiThread { DirectUtils.directToWebView(context, url.toString(), "内部网页") }
}
@JavascriptInterface
fun postWearBadgeTask(msg: Any) {
EnergyTaskHelper.postEnergyTask("wear_badge")
}
@JavascriptInterface
fun startEnergyCenter(msg: Any) {
context.startActivity(EnergyCenterActivity.getIntent(context))
}
@JavascriptInterface
fun startEnergyHouse(msg: Any) {
context.startActivity(EnergyHouseActivity.getIntent(context))
}
@JavascriptInterface
fun showQaFeedbackDialog(msg: Any) {
QaFeedbackDialogFragment.show(context as AppCompatActivity, msg.toString())
}
@JavascriptInterface
fun getMetaObject(msg: Any): String {
return LogUtils.getMetaObject().toString()
}
@JavascriptInterface
fun getLaunchId(msg: Any): String {
return Tracker.launchId
}
@JavascriptInterface
fun getSessionId(msg: Any): String {
return Tracker.sessionId
}
@JavascriptInterface
fun postLogEvent(event: Any) {
val logEvent = event.toString().toObject() ?: LogEvent()
debugOnly {
Utils.log("LogUtils->${logEvent.jsonString}")
}
LoghubUtils.log(logEvent.jsonString, logEvent.logStore, false)
}
@JavascriptInterface
fun startAvatarBorderPage(msg: Any) {
context.startActivity(AvatarBorderActivity.getIntent(context, msg.toString()))
}
@JavascriptInterface
fun isNetworkConnected(): Boolean {
return NetworkUtils.isNetworkConnected(context)
}
@JavascriptInterface
fun isWifiConnected(): Boolean {
return NetworkUtils.isWifiConnected(context)
}
@JavascriptInterface
fun enableBackToActivity(msg: Any) {
FloatingBackViewManager.enableBackView(FloatingBackViewManager.TYPE_ACTIVITY, msg.toString())
}
@JavascriptInterface
fun startBBSStayTimeCount(msg: Any) {
BbsStayTimeHelper.enableStayTimeCount(msg.toString().toInt())
}
@JavascriptInterface
fun saveBase64ImageToGallery(msg: Any) {
val base64StringData = msg.toString()
runOnUiThread {
(context as? FragmentActivity)?.checkStoragePermissionBeforeAction {
runOnIoThread {
val base64String = base64StringData.replace("data:image/png;base64", "")
tryWithDefaultCatch {
val imageFile = File(HaloApp.getInstance().cacheDir.absolutePath + File.separator + System.currentTimeMillis() + ".png")
val decodedString = Base64.decode(base64String, Base64.DEFAULT)
val bos = BufferedOutputStream(FileOutputStream(imageFile))
bos.write(decodedString)
bos.flush()
bos.close()
ImageUtils.saveImageToFile(imageFile, "", true)
}
}
}
}
}
@JavascriptInterface
fun loginWithCallback(msg: Any, handler: CompletionHandler<Any>) {
mLoginHandler = handler
login(msg)
}
fun onLogin() {
mLoginHandler?.complete(true)
mLoginHandler = null
}
@JavascriptInterface
fun openInNewFullWebview(url: Any) {
runOnUiThread { DirectUtils.directToFullScreenWebPage(context, url.toString(), true) }
}
@JavascriptInterface
fun startGameCollectionSquareBrowseTask(event: Any) {
val browseTimeEvent = event.toString().toObject() ?: BrowseTaskEvent()
GameCollectionSquareBrowseTaskHelper.enableBrowseTimeCount(
browseTimeEvent.timeout.toInt(),
browseTimeEvent.isFinished == "true"
)
}
@JavascriptInterface
fun checkUpdateGhzs(msg: Any) {
context.startActivity(AboutActivity.getIntent(context, true))
}
@JavascriptInterface
public fun clickGameActivityDownloadBtn(event: Any) {
val gameActivityEvent = event.toString().toObject() ?: GameActivityEvent()
GameActivityDownloadHelper.start(context, gameActivityEvent)
}
@JavascriptInterface
fun isGameActivityTaskCompleted(event: Any, handler: CompletionHandler<Any>) {
val gameActivityEvent = event.toString().toObject() ?: GameActivityEvent()
GameActivityDownloadHelper.checkTaskComplete(context, gameActivityEvent, handler)
}
@JavascriptInterface
fun postGameActivityExposureEvent(event: Any) {
val gameActivityEvent = event.toString().toObject() ?: GameActivityEvent()
GameActivityDownloadHelper.postExposureEvent(gameActivityEvent)
}
@Keep
internal data class MtaEvent(var name: String = "", var key: String = "", var value: String = "")
@Keep
internal data class ImageEvent(var imageList: ArrayList<String> = arrayListOf(), var position: Int = 0)
@Keep
internal data class ImageShareEvent(var image: String = "", var type: String = "")
@Keep
internal data class InviteFriendsEvent(
var type: String = "",
var way: String = "",
var url: String = "",
var poster: String = ""
)
@Keep
internal data class LogEvent(var jsonString: String = "", var logStore: String = "")
@Keep
internal data class BrowseTaskEvent(var timeout: String = "", var isFinished: String = "")
@Keep
data class GameActivityEvent(
var gameId: String = "",
var activityTitle: String = "",
var activityId: String = "",
var platform: String = ""
)
}

View File

@ -1,592 +0,0 @@
package com.gh.common
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Base64
import com.gh.base.CurrentActivityHolder
import com.gh.common.constant.Constants
import com.gh.common.util.*
import com.gh.common.util.DirectUtils.directToFeedback
import com.gh.common.util.DirectUtils.directToGameDetailVideoStreaming
import com.gh.common.util.DirectUtils.directToGameServerCalendar
import com.gh.common.util.DirectUtils.directToGameVideo
import com.gh.common.util.DirectUtils.directToLegacyVideoDetail
import com.gh.common.util.DirectUtils.directToLinkPage
import com.gh.common.util.DirectUtils.directToQa
import com.gh.common.util.GsonUtils.gson
import com.gh.gamecenter.LibaoDetailActivity
import com.gh.gamecenter.MainActivity
import com.gh.gamecenter.NewsDetailActivity
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.gamecollection.publish.GameCollectionEditActivity
import com.gh.gamecenter.qa.BbsType
import com.gh.gamecenter.qa.video.publish.VideoPublishActivity
import com.gh.gamecenter.subject.SubjectActivity
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel
import com.lightgame.utils.Utils
import java.nio.charset.Charset
object DefaultUrlHandler {
@JvmStatic
fun interceptUrl(context: Context, url: String, entrance: String): Boolean {
return interceptUrl(context, url, entrance, false)
}
/**
* @param bringAppToFront 是否需要在不匹配 host 的时候把 APP 调回到前台 (如微信调起)
*/
@JvmStatic
fun interceptUrl(context: Context, url: String, entrance: String, bringAppToFront: Boolean = false): Boolean {
val uri = Uri.parse(url)
if ("ghzhushou" == uri.scheme) {
Utils.log("url = $url")
Utils.log("url = " + uri.scheme!!)
val host = uri.host
val path = uri.path
var id = ""
if (!TextUtils.isEmpty(path)) {
id = path!!.substring(1)
}
if (TextUtils.isEmpty(id)) {
id = uri.getQueryParameter("id") ?: ""
}
val intent: Intent
when (host) {
"article" -> context.startActivity(NewsDetailActivity.getIntentById(context, id, entrance))
"game" -> DirectUtils.directToGameDetail(
context,
id = id,
tab = uri.getQueryParameter("to"),
autoDownload = uri.getQueryParameter("auto_download") == "true",
entrance = entrance
)
"column" -> SubjectActivity.startSubjectActivity(context, id, uri.getQueryParameter("name"), false, entrance)
"libao" -> context.startActivity(LibaoDetailActivity.getIntentById(context, id, entrance))
"qq" -> try {
DirectUtils.directToQqConversation(context, id)
} catch (e: Throwable) {
Utils.toast(context, "请检查是否已经安装手机QQ")
e.printStackTrace()
}
EntranceUtils.HOST_QQ_QUN -> {
val key = uri.getQueryParameter("key")
if (!DirectUtils.directToQqGroup(context, key)) {
Utils.toast(context, "请检查是否已经安装手机QQ")
}
}
"inurl" -> {
DirectUtils.directToWebView(context, uri.getQueryParameter("url") ?: "")
}
"outurl" -> {
intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.data = Uri.parse(uri.getQueryParameter("url"))
try {
context.startActivity(intent)
} catch (e: Exception) {
Utils.toast(context, "请检查是否已经安装手机浏览器")
e.printStackTrace()
}
}
"question" -> DirectUtils.directToQuestionDetail(context, id, entrance, "文章链接")
"community" -> {
val community = CommunityEntity()
community.id = id
community.name = uri.getQueryParameter("name") ?: ""
DirectUtils.directToCommunity(context, community)
}
"community_column" -> {
val community = CommunityEntity()
community.id = uri.getQueryParameter("community_id") ?: ""
community.name = uri.getQueryParameter("community_name") ?: ""
val columnId = uri.getQueryParameter("column_id") ?: ""
DirectUtils.directToCommunityColumn(context, community, columnId, entrance, "文章链接")
}
"answer" -> DirectUtils.directToAnswerDetail(context, id, entrance, "文章链接")
"communities" -> {
// ghzhushou://communities/5a32405b2397ab000f688de3/articles/5c99d262c140b321564f04e3
var communityId = ""
var type = ""
var typeId = ""
val split = id.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (text in split) {
if (TextUtils.isEmpty(communityId)) {
communityId = text
continue
}
if (TextUtils.isEmpty(type)) {
type = text
continue
}
if (TextUtils.isEmpty(typeId)) {
typeId = text
}
}
if ("articles" == type) {
DirectUtils.directToCommunityArticle(
context, typeId, communityId,
entrance, "文章链接"
)
}
}
EntranceUtils.HOST_UPLOAD_VIDEO -> {
val titleParameter = uri.getQueryParameter("title")
val title = if (titleParameter.isNullOrEmpty()) "" else "#$titleParameter#"
val categoryId = uri.getQueryParameter("category_id") ?: ""
val link = uri.getQueryParameter("link") ?: ""
val gameId = uri.getQueryParameter("gameId") ?: ""
val gameName = uri.getQueryParameter("gameName") ?: ""
val tagActivityId = uri.getQueryParameter("tagActivityId") ?: ""
val tagActivityName = uri.getQueryParameter("tagActivityName") ?: ""
val linkEntity = VideoLinkEntity(title, categoryId, link, tagActivityId, tagActivityName)
val simpleGameEntity = SimpleGameEntity(gameId, gameName)
CheckLoginUtils.checkLogin(context, null, true, EntranceUtils.ENTRANCE_BROWSER) {
DirectUtils.directToVideoManager(context, linkEntity, simpleGameEntity, EntranceUtils.ENTRANCE_BROWSER, "")
}
}
EntranceUtils.HOST_USERHOME -> {
val position = uri.getQueryParameter("position")
val subtype = uri.getQueryParameter("sub_type") ?: ""
DirectUtils.directToHomeActivity(context, id, subtype, if (position.isNullOrEmpty()) -1 else position.toInt(), entrance, "")
}
EntranceUtils.HOST_VIDEO_MORE -> {
val referer = uri.getQueryParameter("referer") ?: ""
val type = uri.getQueryParameter("type") ?: ""
val act = uri.getQueryParameter("act") ?: ""
val gameId = uri.getQueryParameter("gameId") ?: ""
val fieldId = uri.getQueryParameter("fieldId") ?: ""
val sectionName = uri.getQueryParameter("sectionName") ?: ""
val paginationType = uri.getQueryParameter("paginationType")
?: "page"//活动分页方式 page filter
val location = if (!TextUtils.isEmpty(act)) {
VideoDetailContainerViewModel.Location.VIDEO_ACTIVITY.value
} else if (!TextUtils.isEmpty(fieldId)) {
VideoDetailContainerViewModel.Location.GAME_ZONE.value
} else {
id
}
directToLegacyVideoDetail(
context,
id,
location,
false,
gameId,
entrance,
"",
referer,
type,
act,
paginationType,
fieldId,
sectionName
)
}
EntranceUtils.HOST_VIDEO_DETAIL -> {
DirectUtils.directToVideoDetail(context, id, entrance, path)
}
EntranceUtils.HOST_VIDEO_SINGLE -> {
val referer = uri.getQueryParameter("referer") ?: ""
DirectUtils.directToVideoDetail(
context, id, VideoDetailContainerViewModel.Location.SINGLE_VIDEO.value,
false, "", entrance, "", if (TextUtils.isEmpty(referer)) "" else referer
)
}
EntranceUtils.HOST_VIDEO_STREAMING_HOME -> {
intent = Intent(context, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
intent.putExtra(MainActivity.SWITCH_TO_VIDEO, true)
context.startActivity(intent)
}
EntranceUtils.HOST_VIDEO_STREAMING_DESC -> {
directToGameDetailVideoStreaming(context, id, entrance)
}
EntranceUtils.HOST_VIDEO_COLLECTION -> {
directToGameVideo(context, id, entrance, "")
}
EntranceUtils.HOST_CATEGORY -> {
val title = uri.getQueryParameter("title")
DirectUtils.directCategoryDirectory(context, id, title ?: "", entrance, "")
}
EntranceUtils.HOST_COLUMN_COLLECTION -> {
val name = uri.getQueryParameter("name")
DirectUtils.directToColumnCollection(context, id, -1, entrance, name ?: "")
}
EntranceUtils.HOST_COLUMN -> {
DirectUtils.directToSubject(context, id, uri.getQueryParameter(EntranceUtils.KEY_NAME), entrance)
}
EntranceUtils.HOST_COMMUNITY_QUESTION_LABEL_DETAIL -> {
val community = CommunityEntity()
community.id = uri.getQueryParameter("community_id") ?: ""
community.name = uri.getQueryParameter("community_name") ?: ""
val tag = uri.getQueryParameter("tag") ?: ""
DirectUtils.directAskColumnLabelDetail(context, tag, community, entrance, "")
}
EntranceUtils.HOST_COMMUNITY_COLUMN_DETAIL -> {
val community = CommunityEntity()
community.id = uri.getQueryParameter("community_id") ?: ""
community.name = uri.getQueryParameter("community_name") ?: ""
val columnId = uri.getQueryParameter("column_id") ?: ""
DirectUtils.directAskColumnDetail(context, columnId, community, entrance, "")
}
EntranceUtils.HOST_BLOCK -> {
val name = uri.getQueryParameter("name")
?: ""
val entity = SubjectRecommendEntity(link = id, name = name, text = name)
DirectUtils.directToBlock(context, entity, entrance)
}
EntranceUtils.HOST_SERVER_BLOCK -> {
DirectUtils.directToGameServers(context, entrance = entrance, path = "")
}
EntranceUtils.HOST_AMWAY_BLOCK -> {
DirectUtils.directToAmway(context, entrance = entrance, path = "")
}
EntranceUtils.HOST_HELP -> {
val name = uri.getQueryParameter("name")
?: ""
DirectUtils.directToQa(context, name, id)
}
EntranceUtils.HOST_HELP_COLLECTION -> {
val name = uri.getQueryParameter("name")
?: ""
DirectUtils.directToQaCollection(context, name, id)
}
EntranceUtils.HOST_GAME_UPLOAD -> {
DirectUtils.directGameUpload(context, entrance = entrance, path = "")
}
EntranceUtils.HOST_GAME_ZONE -> {
val zoneUrl = uri.getQueryParameter("url") ?: ""
DirectUtils.directGameZone(context, id, zoneUrl, entrance)
}
EntranceUtils.HOST_LINK -> {
try {
val dataString = uri.getQueryParameter("data")
if (!TextUtils.isEmpty(dataString)) {
val linkData = Base64.decode(dataString, Base64.DEFAULT)
val linkDataString = String(linkData, Charset.defaultCharset())
val le = gson.fromJson(linkDataString, LinkEntity::class.java)
directToLinkPage(context, le, entrance, "")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
EntranceUtils.HOST_GAME_NEWS -> {
DirectUtils.directToGameNews(
context,
uri.getQueryParameter(EntranceUtils.KEY_GAME_ID),
uri.getQueryParameter(EntranceUtils.KEY_GAME_NAME),
entrance
);
}
EntranceUtils.HOST_GAME_CALENDAR -> {
directToGameServerCalendar(context, uri.getQueryParameter(EntranceUtils.KEY_GAME_ID))
}
EntranceUtils.HOST_HISTORY_APK -> {
DirectUtils.directToHistoryApk(context, uri.getQueryParameter(EntranceUtils.KEY_GAME_ID))
}
EntranceUtils.HOST_FORUM_DETAIL -> {
DirectUtils.directForumDetail(context, id, entrance)
}
EntranceUtils.HOST_GAME_RATING_DETAIL -> {
DirectUtils.directToGameRatingDetail(
context,
uri.getQueryParameter(EntranceUtils.KEY_GAME_ID),
uri.getQueryParameter(EntranceUtils.KEY_COMMENT_ID),
EntranceUtils.ENTRANCE_BROWSER
)
}
EntranceUtils.HOST_FORUM -> {
val position = uri.getQueryParameter(EntranceUtils.KEY_POSITION)?.toInt()
DirectUtils.directToForum(context, position ?: 0)
}
EntranceUtils.HOST_UPLOAD_VIDEO_NEW -> {
val activityName = uri.getQueryParameter("activity_name") ?: ""
val activityId = uri.getQueryParameter("activity_id") ?: ""
val original = uri.getQueryParameter("original") ?: ""
val forumName = uri.getQueryParameter("forum_name") ?: ""
val forumId = uri.getQueryParameter("forum_id") ?: ""
val forumIcon = uri.getQueryParameter("forum_icon") ?: ""
val forumType = uri.getQueryParameter("forum_type") ?: BbsType.OFFICIAL_BBS.value
val gameId = uri.getQueryParameter("game_id") ?: ""
val gameName = uri.getQueryParameter("game_name") ?: ""
val icon = uri.getQueryParameter("game_icon") ?: ""
val iconSubscript = uri.getQueryParameter("game_icon_subscript") ?: ""
val gameEntity =
if (forumType == BbsType.OFFICIAL_BBS.value && gameId.isNotEmpty() && gameName.isNotEmpty() && icon.isNotEmpty()) {
GameEntity(id = gameId, mName = gameName, mIcon = icon, mIconSubscript = iconSubscript)
} else null
val activityLabelEntity = if (activityId.isNotEmpty() && activityName.isNotEmpty()) {
ActivityLabelEntity(id = activityId, name = activityName, original = original.ifEmpty { "false" }.toBoolean())
} else null
val communityEntity = if (forumId.isNotEmpty() && forumName.isNotEmpty() && forumIcon.isNotEmpty()) {
CommunityEntity(id = forumId, name = forumName, icon = forumIcon)
} else null
context.startActivity(
VideoPublishActivity.getIntent(
context,
communityEntity,
gameEntity,
activityLabelEntity,
forumType,
disableForumSelection = false,
isFromCommunityActivity = true,
entrance,
""
)
)
}
EntranceUtils.HOST_SUGGESTION -> {
val platform = uri.getQueryParameter(EntranceUtils.KEY_PLATFORM)
val platformName = PlatformUtils.getInstance(context).getPlatformName(platform)
val gameId = uri.getQueryParameter(EntranceUtils.KEY_GAMEID)
val packageMd5 = uri.getQueryParameter(EntranceUtils.KEY_PACKAGE_MD5)
val isQaFeedback = uri.getQueryParameter(EntranceUtils.KEY_IS_QA_FEEDBACK) == "true"
val content = if (TextUtils.isEmpty(gameId) || TextUtils.isEmpty(packageMd5)) String.format(
"%s-%s-V%s",
uri.getQueryParameter(EntranceUtils.KEY_GAME_NAME),
if (TextUtils.isEmpty(platformName)) platform else platformName,
uri.getQueryParameter(EntranceUtils.KEY_VERSION)
) else String.format(
"%s-%s-V%s\n游戏ID%s\n游戏包MD5%s\n",
uri.getQueryParameter(EntranceUtils.KEY_GAME_NAME),
if (TextUtils.isEmpty(platformName)) platform else platformName,
uri.getQueryParameter(EntranceUtils.KEY_VERSION), gameId, packageMd5
)
val qaId = uri.getQueryParameter("qa_id") ?: ""
val qaContentId = uri.getQueryParameter(EntranceUtils.KEY_QA_CONTENT_ID) ?: ""
val qaTitle = uri.getQueryParameter(EntranceUtils.KEY_QA_TITLE)
if (!TextUtils.isEmpty(qaId)) {
directToQa(context, qaTitle, qaId)
} else {
directToFeedback(context, content, null, isQaFeedback, qaContentId, EntranceUtils.ENTRANCE_BROWSER)
}
}
EntranceUtils.HOST_HELP_AND_FEEDBACK -> {
val position = uri.getQueryParameter("position") ?: ""
DirectUtils.directToHelpAndFeedback(context, position.toInt())
}
EntranceUtils.HOST_HELP_DETAIL -> {
var url = uri.getQueryParameter("url")
if (!url.isNullOrEmpty()) {
context.startActivity(WebActivity.getIntent(context, url, false))
} else {
url = if (EnvHelper.isDevEnv) {
Constants.HELP_ADDRESS_DEV
} else {
Constants.HELP_ADDRESS
}
val id = uri.getQueryParameter("id")
val name = uri.getQueryParameter("name")
val qaCollectionId = uri.getQueryParameter("collection_id")
context.startActivity(WebActivity.getIntent(context, "$url$id", name, true, !qaCollectionId.isNullOrEmpty()))
}
}
EntranceUtils.HOST_GAME_COLLECTION_DETAIL -> {
DirectUtils.directToGameCollectionDetail(context, id, entrance)
}
EntranceUtils.HOST_GAME_COLLECTION_SQUARE -> {
DirectUtils.directToGameCollectionSquare(context, entrance)
}
EntranceUtils.HOST_GAME_COLLECTION_EDIT -> {
context.startActivity(GameCollectionEditActivity.getIntent(context, entrance))
}
else -> {
if (bringAppToFront) {
DirectUtils.directToMainActivity(context)
if (!TextUtils.isEmpty(host)) {
AppExecutor.uiExecutor.executeWithDelay({
CurrentActivityHolder.getCurrentActivity()?.let {
DialogHelper.showUpgradeDialog(it)
}
}, 200)
}
} else {
DialogHelper.showUpgradeDialog(context)
}
}
}
return true
} else if ("zhiqu" == uri.scheme) {
if (PackageUtils.isInstalled(context, "com.beieryouxi.zqyxh")) {
val intent = Intent()
intent.data = Uri.parse(url)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
} else {
Utils.toast(context, "请安装指趣游戏盒")
}
}
if (url.startsWith("alipays:") || url.startsWith("alipay")) {
try {
context.startActivity(Intent("android.intent.action.VIEW", Uri.parse(url)))
} catch (e: Exception) {
ToastUtils.showToast("请安装支付宝客户端")
}
return true
} else if (url.startsWith("weixin")) {
try {
context.startActivity(Intent("android.intent.action.VIEW", Uri.parse(url)))
} catch (e: Exception) {
ToastUtils.showToast("请安装微信客户端")
}
return true
} else if (url.startsWith("mqqwpa")) {
try {
context.startActivity(Intent("android.intent.action.VIEW", Uri.parse(url)))
} catch (e: Exception) {
ToastUtils.showToast("请安装QQ客户端")
}
return true
}
// 处理内部页面逻辑
if (transformNormalScheme(context, url, entrance)) {
return true
}
if ("http" != uri.scheme && "https" != uri.scheme) return true
return false
}
@JvmStatic
fun transformNormalScheme(context: Context, url: String, entrance: String): Boolean {
val uri = Uri.parse(url)
if (uri.host == "www.ghzs666.com"
|| uri.host == "www.ghzs.com"
|| uri.host == "ask.ghzs.com"
|| uri.host == "m.ghzs.com"
|| uri.host == "m.ghzs666.com"
) {
Utils.log(uri.path)
uri.path?.apply {
when {
contains("game") -> {
val gameId = uri.getQueryParameter("gameId") ?: uri.pathSegments.last()
?: ""
DirectUtils.directToGameDetail(context, gameId, entrance, autoDownload = false, traceEvent = null)
}
contains("question") -> {
val questionId = split("/")[2]
val answerId = uri.getQueryParameter("answer")
if (answerId.isNullOrEmpty()) {
DirectUtils.directToQuestionDetail(context, questionId, entrance, "")
} else {
DirectUtils.directToAnswerDetail(context, answerId, entrance, "")
}
}
((contains("bbs")) && contains("article") ||
(contains("communities")) && contains("article")) -> {
var communityId = ""
var type = ""
var typeId = ""
val split =
replace("/communities", "").replace("/bbs", "").replace(".html", "").split("/".toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray()
for (text in split) {
if (TextUtils.isEmpty(communityId)) {
communityId = text
continue
}
if (TextUtils.isEmpty(type)) {
type = text
continue
}
if (TextUtils.isEmpty(typeId)) {
typeId = text
}
}
if ("articles" == type || "article" == type) {
DirectUtils.directToCommunityArticle(
context, typeId, communityId,
entrance, "文章链接"
)
}
}
contains("article") -> {
val articleId = split("/")[2].replace(".html", "")
if (entrance == "隐私政策") {
DirectUtils.directToArticle(context, articleId, true, entrance)
} else {
DirectUtils.directToArticle(context, articleId, entrance)
}
}
contains("columns") -> {
val columnsId = split("/")[3]
val id = uri.getQueryParameter("communityId") ?: ""
val name = uri.getQueryParameter("communityName") ?: ""
DirectUtils.directToCommunityColumn(context, CommunityEntity(id, name), columnsId, entrance, "")
}
contains("zone") && split("/").size > 2 -> {
val gameId = split("/")[2]
DirectUtils.directGameZone(context, gameId, url, entrance)
}
else -> return false
}
}
return true
}
return false
}
/**
* 将 url 转换为 LinkEntity (实际只有 type 和 link 两个字段,仅供日志,不保证能用)
*/
fun urlToLinkEntity(url: String): LinkEntity? {
val uri = Uri.parse(url)
if ("ghzhushou" == uri.scheme) {
Utils.log("url = $url")
Utils.log("url = " + uri.scheme!!)
val host = uri.host
val path = uri.path
var id = ""
if (!TextUtils.isEmpty(path)) {
id = path!!.substring(1)
}
return LinkEntity(type = host, link = id)
}
return null
}
}

View File

@ -0,0 +1,133 @@
package com.gh.common
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import com.gh.common.util.CheckLoginUtils
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.EntranceUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.LibaoDetailActivity
import com.gh.gamecenter.NewsDetailActivity
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.entity.CommunityEntity
import com.gh.gamecenter.entity.VideoLinkEntity
import com.gh.gamecenter.subject.SubjectActivity
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
object DefaultWebViewUrlHandler {
@JvmStatic
fun interceptUrl(context: Context, url: String, entrance: String): Boolean {
val uri = Uri.parse(url)
if ("ghzhushou" == uri.scheme) {
Utils.log("url = $url")
Utils.log("url = " + uri.scheme!!)
val host = uri.host
val path = uri.path
var id = ""
if (!TextUtils.isEmpty(path)) {
id = path!!.substring(1)
}
val intent: Intent
when (host) {
"article" -> context.startActivity(NewsDetailActivity.getIntentById(context, id, entrance))
"game" -> GameDetailActivity.startGameDetailActivity(context, id, entrance)
"column" -> SubjectActivity.startSubjectActivity(context, id, uri.getQueryParameter("name"), false, entrance)
"libao" -> context.startActivity(LibaoDetailActivity.getIntentById(context, id, entrance))
"qq" -> try {
DirectUtils.directToQqConversation(context, id)
} catch (e: Exception) {
Utils.toast(context, "请检查是否已经安装手机QQ")
e.printStackTrace()
}
"qqqun" -> {
val key = uri.getQueryParameter("key")
if (!DirectUtils.directToQqGroup(context, key)) {
Utils.toast(context, "请检查是否已经安装手机QQ")
}
}
"inurl" -> {
intent = Intent(context, WebActivity::class.java)
intent.putExtra(EntranceUtils.KEY_URL, uri.getQueryParameter("url"))
context.startActivity(intent)
}
"outurl" -> {
intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.data = Uri.parse(uri.getQueryParameter("url"))
try {
context.startActivity(intent)
} catch (e: Exception) {
Utils.toast(context, "请检查是否已经安装手机浏览器")
e.printStackTrace()
}
}
"question" -> DirectUtils.directToQuestionDetail(context, id, entrance, "文章链接")
"community" -> {
val community = CommunityEntity()
community.id = id
community.name = uri.getQueryParameter("name")
DirectUtils.directToCommunity(context, community)
}
"answer" -> DirectUtils.directToAnswerDetail(context, id, entrance, "文章链接")
"communities" -> {
// ghzhushou://communities/5a32405b2397ab000f688de3/articles/5c99d262c140b321564f04e3
var communityId = ""
var type = ""
var typeId = ""
val split = id.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (text in split) {
if (TextUtils.isEmpty(communityId)) {
communityId = text
continue
}
if (TextUtils.isEmpty(type)) {
type = text
continue
}
if (TextUtils.isEmpty(typeId)) {
typeId = text
}
}
if ("articles" == type) {
DirectUtils.directToCommunityArticle(
context, typeId, communityId,
entrance, "文章链接")
}
}
EntranceUtils.HOST_UPLOAD_VIDEO -> {
val titleParameter = uri.getQueryParameter("title")
val title = if (titleParameter.isNullOrEmpty()) "" else "#$titleParameter#"
val categoryId = uri.getQueryParameter("category_id") ?: ""
val link = uri.getQueryParameter("link") ?: ""
val linkEntity = VideoLinkEntity(title, categoryId, link)
if (!CheckLoginUtils.isLogin()) {
HaloApp.put(EntranceUtils.HOST_UPLOAD_VIDEO, linkEntity)
}
CheckLoginUtils.checkLogin(context, EntranceUtils.ENTRANCE_BROWSER) {
DirectUtils.directToVideoManager(context, linkEntity, EntranceUtils.ENTRANCE_BROWSER, "")
}
}
else -> DialogUtils.showLowVersionDialog(context)
}
return true
}
if ("http" != uri.scheme && "https" != uri.scheme) return true
return false
}
}

View File

@ -1,83 +0,0 @@
package com.gh.common
import com.gh.common.exposure.ExposureManager
import com.gh.common.filter.RegionSettingHelper
import com.gh.common.loghub.LoghubUtils
import com.gh.common.util.doOnMainProcessOnly
import com.gh.common.util.tryCatchInRelease
import com.gh.common.videolog.VideoRecordUtils
import com.gh.download.DownloadDataHelper
import com.gh.gamecenter.entity.TimeEntity
import com.gh.gamecenter.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.schedulers.Schedulers
import kotlin.concurrent.fixedRateTimer
object FixedRateJobHelper {
private const val CHECKER_PERIOD: Long = 15 * 1000L
private const val TIME_PERIOD: Long = 600 * 1000L
private const val LOGHUB_PERIOD: Long = 120 * 1000L
private const val EXPOSURE_PERIOD: Long = 300 * 1000L
private const val REGION_SETTING_PERIOD: Long = 300 * 1000L
private const val VIDEO_RECORD_PERIOD: Long = 60 * 1000L
private const val DOWNLOAD_HEARTBEAT_PERIOD: Long = 60 * 1000L
private const val DOWNLOAD_HEARTBEAT_SHEET_PERIOD: Long = 15 * 1000L
private var mExecuteCount: Int = 0
var timeDeltaBetweenServerAndClient: Long = 0
@JvmStatic
fun begin() {
doOnMainProcessOnly {
fixedRateTimer("Global-Fixed-Rate-Timer", initialDelay = 100, period = CHECKER_PERIOD) {
// 时间校对10分钟一次
if ((mExecuteCount * CHECKER_PERIOD) % TIME_PERIOD == 0L) {
RetrofitManager.getInstance().api.time
.subscribeOn(Schedulers.io())
.subscribe(object : Response<TimeEntity>() {
override fun onResponse(response: TimeEntity?) {
val serverTime = response?.time
serverTime?.let { timeDeltaBetweenServerAndClient = it * 1000 - System.currentTimeMillis() }
}
})
}
// 提交曝光数据
if ((mExecuteCount * CHECKER_PERIOD) % EXPOSURE_PERIOD == 0L) {
ExposureManager.commitSavedExposureEvents(true)
}
// 分片检测下载进度
if ((mExecuteCount * CHECKER_PERIOD) % DOWNLOAD_HEARTBEAT_SHEET_PERIOD == 0L) {
tryCatchInRelease {
val upload = (mExecuteCount * CHECKER_PERIOD) % DOWNLOAD_HEARTBEAT_PERIOD == 0L
DownloadDataHelper.uploadDownloadHeartbeat(upload)
}
}
// 提交普通 loghub 数据
if ((mExecuteCount * CHECKER_PERIOD) % LOGHUB_PERIOD == 0L) {
LoghubUtils.commitSavedLoghubEvents()
}
// 更新游戏屏蔽信息
if ((mExecuteCount * CHECKER_PERIOD) % REGION_SETTING_PERIOD == 0L) {
if (HaloApp.getInstance().isRunningForeground) {
RegionSettingHelper.getRegionSetting()
}
}
// 提交视频浏览记录数据
if ((mExecuteCount * CHECKER_PERIOD) % VIDEO_RECORD_PERIOD == 0L) {
VideoRecordUtils.commitVideoRecord()
}
// ExposureUtils.logADownloadCompleteExposureEvent(GameEntity(id = mExecuteCount.toString(), name = "测试曝光上传"), platform = "", trace = null, downloadType = ExposureUtils.DownloadType.DOWNLOAD)
mExecuteCount++
}
}
}
}

View File

@ -1,39 +1,39 @@
//package com.gh.common
//
//import android.content.BroadcastReceiver
//import android.content.Context
//import android.content.Intent
//import com.gh.common.im.ImManager
//import com.gh.gamecenter.manager.UserManager
//import com.gh.gamecenter.retrofit.RetrofitManager
//import com.halo.assistant.HaloApp
//import com.m7.imkfsdk.chat.ChatActivity
//import io.reactivex.schedulers.Schedulers
//
///**
// * 可使用 [LocalBroadcastManager] 来进行简单的模块间消息通知
// */
//
//class LocalBroadcastReceiver : BroadcastReceiver() {
//
// override fun onReceive(context: Context?, intent: Intent?) {
// intent?.let {
// when (intent.action) {
// ChatActivity.ACTION_DISMISS_FLOATING_WINDOW -> {
// ImManager.dismissFloatingWindow()
//
// RetrofitManager.getInstance().api.postImEnding(UserManager.getInstance().userId)
// .subscribeOn(Schedulers.io())
// .subscribe()
// }
//
// ChatActivity.ACTION_HIDE_UNREAD_DOT -> {
// ImManager.updateShouldShowFloatingWindowDot(false)
// }
//
// else -> return
// }
// }
// }
//
//}
package com.gh.common
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.gh.common.im.ImManager
import com.gh.gamecenter.manager.UserManager
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.m7.imkfsdk.chat.ChatActivity
import io.reactivex.schedulers.Schedulers
/**
* 可使用 [LocalBroadcastManager] 来进行简单的模块间消息通知
*/
class LocalBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let {
when (intent.action) {
ChatActivity.ACTION_DISMISS_FLOATING_WINDOW -> {
ImManager.dismissFloatingWindow()
RetrofitManager.getInstance(HaloApp.getInstance().application).api.postImEnding(UserManager.getInstance().userId)
.subscribeOn(Schedulers.io())
.subscribe()
}
ChatActivity.ACTION_HIDE_UNREAD_DOT -> {
ImManager.updateShouldShowFloatingWindowDot(false)
}
else -> return
}
}
}
}

View File

@ -1,8 +1,28 @@
package com.gh.common
import android.annotation.SuppressLint
import android.preference.PreferenceManager
import com.gh.base.GHUmengNotificationService
import com.gh.common.constant.Config
import com.gh.common.exposure.meta.MetaUtil
import com.gh.common.util.edit
import com.gh.common.util.toJson
import com.gh.common.util.toObject
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.entity.AliasEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import com.umeng.commonsdk.UMConfigure
import com.umeng.message.IUmengRegisterCallback
import com.umeng.message.PushAgent
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import org.android.agoo.huawei.HuaWeiRegister
import org.android.agoo.mezu.MeizuRegister
import org.android.agoo.xiaomi.MiPushRegistar
import org.json.JSONObject
object PushManager {
@ -15,103 +35,106 @@ object PushManager {
@JvmStatic
fun init(channel: String) {
// tryWithDefaultCatch {
// //初始化友盟推送
// UMConfigure.init(mApplication, Config.UMENG_APPKEY, channel, UMConfigure.DEVICE_TYPE_PHONE, Config.UMENG_MESSAGE_SECRET)
//
// val pushAgent = PushAgent.getInstance(mApplication)
//
// runOnIoThread { registerDevice() }
//
// // 注册小米、华为和魅族通道
// MiPushRegistar.register(mApplication, Config.MIPUSH_APPID, Config.MIPUSH_APPKEY)
// HuaWeiRegister.register(mApplication)
// MeizuRegister.register(mApplication, BuildConfig.MEIZUPUSH_APPID, BuildConfig.MEIZUPUSH_APPKEY)
//
// val aliasInSp = PreferenceManager.getDefaultSharedPreferences(mApplication).getString(SP_PUSH_ALIAS, "")
// mPreviousAlias = aliasInSp?.toObject()
//
// if (mPreviousAlias == null) {
// getAndSetAlias()
// }
//
// // 完全自定义处理(透传)
// pushAgent.setPushIntentServiceClass(GHUmengNotificationService::class.java)
// }
//初始化友盟推送
UMConfigure.init(mApplication,
Config.UMENG_APPKEY, channel,
UMConfigure.DEVICE_TYPE_PHONE,
Config.UMENG_MESSAGE_SECRET)
// 注册小米、华为和魅族通道
MiPushRegistar.register(mApplication, Config.MIPUSH_APPID, Config.MIPUSH_APPKEY)
HuaWeiRegister.register(mApplication)
MeizuRegister.register(mApplication, BuildConfig.MEIZUPUSH_APPID, BuildConfig.MEIZUPUSH_APPKEY)
//友盟推送
val pushAgent = PushAgent.getInstance(mApplication)
pushAgent.onAppStart() // 开启App统计
//注册推送服务每次调用register方法都会回调该接口
registerDevice()
val aliasInSp = PreferenceManager.getDefaultSharedPreferences(mApplication).getString(SP_PUSH_ALIAS, "")
mPreviousAlias = aliasInSp?.toObject()
if (mPreviousAlias == null) {
getAndSetAlias()
}
// 完全自定义处理(透传)
pushAgent.setPushIntentServiceClass(GHUmengNotificationService::class.java)
}
private fun registerDevice() {
// PushAgent.getInstance(mApplication).register(object : IUmengRegisterCallback {
// override fun onSuccess(dToken: String) {
// //注册成功会返回device token
// deviceToken = dToken
// getAndSetAlias()
// Utils.log("deviceToken::$dToken")
// }
//
// override fun onFailure(s: String, s1: String) {
// Utils.log("deviceToken::" + "注册失败")
// }
// })
PushAgent.getInstance(mApplication).register(object : IUmengRegisterCallback {
override fun onSuccess(dToken: String) {
//注册成功会返回device token
deviceToken = dToken
getAndSetAlias()
Utils.log("deviceToken::$dToken")
}
override fun onFailure(s: String, s1: String) {
Utils.log("deviceToken::" + "注册失败")
}
})
}
@SuppressLint("CheckResult")
@JvmStatic
fun getAndSetAlias() {
// if (deviceToken.isNullOrEmpty()) {
// registerDevice()
// return
// }
//
// val meta = MetaUtil.getMeta()
//
// val jsonObject = JSONObject()
// jsonObject.put("device_token", deviceToken)
// jsonObject.put("imei", meta.imei)
// jsonObject.put("android_id", meta.android_id)
// jsonObject.put("model", meta.model)
// jsonObject.put("manufacturer", meta.manufacturer)
// jsonObject.put("os", meta.os)
// jsonObject.put("os_version", meta.android_version)
// jsonObject.put("mac", meta.mac)
// jsonObject.put("gid", meta.gid)
//
// val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
//
// RetrofitManager.getInstance().api.getAlias(body)
// .subscribeOn(Schedulers.io())
// .subscribe(
// { setAlias(it) },
// { it.printStackTrace() }
// )
if (deviceToken.isNullOrEmpty()) {
registerDevice()
return
}
val meta = MetaUtil.getMeta()
val jsonObject = JSONObject()
jsonObject.put("device_token", deviceToken)
jsonObject.put("imei", meta.imei)
jsonObject.put("android_id", meta.android_id)
jsonObject.put("model", meta.model)
jsonObject.put("manufacturer", meta.manufacturer)
jsonObject.put("os", meta.os)
jsonObject.put("os_version", meta.android_version)
jsonObject.put("mac", meta.mac)
val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
RetrofitManager.getInstance(mApplication).api.getAlias(body)
.subscribeOn(Schedulers.io())
.subscribe(
{ setAlias(it) },
{ it.printStackTrace() }
)
}
@JvmStatic
fun setAlias(alias: AliasEntity) {
// val pushAgent = PushAgent.getInstance(mApplication)
//
// mPreviousAlias = alias
// PreferenceManager.getDefaultSharedPreferences(mApplication).edit {
// putString(SP_PUSH_ALIAS, mPreviousAlias?.toJson())
// }
//
// pushAgent.setAlias(alias.alias, alias.aliasType) { b, s ->
// Utils.log("注册别名 $b + $s")
// }
val pushAgent = PushAgent.getInstance(mApplication)
mPreviousAlias = alias
PreferenceManager.getDefaultSharedPreferences(mApplication).edit {
putString(SP_PUSH_ALIAS, mPreviousAlias?.toJson())
}
pushAgent.setAlias(alias.alias, alias.aliasType) { b, s ->
Utils.log("注册别名 $b + $s")
}
}
@JvmStatic
fun deleteAlias() {
// val pushAgent = PushAgent.getInstance(mApplication)
//
// mPreviousAlias?.let {
// pushAgent.deleteAlias(it.alias, it.aliasType) { b, s ->
// Utils.log("删除别名 $b + $s")
// }
// }
// PreferenceManager.getDefaultSharedPreferences(mApplication).edit {
// putString(SP_PUSH_ALIAS, "")
// }
// mPreviousAlias = null
val pushAgent = PushAgent.getInstance(mApplication)
mPreviousAlias?.let {
pushAgent.deleteAlias(it.alias, it.aliasType) { b, s ->
Utils.log("删除别名 $b + $s")
}
}
PreferenceManager.getDefaultSharedPreferences(mApplication).edit {
putString(SP_PUSH_ALIAS, "")
}
mPreviousAlias = null
}
}

View File

@ -5,13 +5,11 @@ import android.app.Application
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.gh.base.GHThreadFactory
import com.halo.assistant.HaloApp
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* 统计用户在当前 Fragment/Activity 的停留时间,在 onViewDestroy 或 onDestroy 里获取 elapsedTime 即可,单位为秒
* 统计用户在当前 Fragment 的停留时间,在 onViewDestroy 或 onDestroy 里获取 elapsedTime 即可,单位为秒
*/
class TimeElapsedHelper(val fragment: Fragment?, val activity: Activity?) {
@ -30,31 +28,31 @@ class TimeElapsedHelper(val fragment: Fragment?, val activity: Activity?) {
init {
activity?.application?.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityStarted(a: Activity) {
override fun onActivityStarted(a: Activity?) {
}
override fun onActivitySaveInstanceState(a: Activity, outState: Bundle) {
override fun onActivitySaveInstanceState(a: Activity?, outState: Bundle?) {
}
override fun onActivityStopped(a: Activity) {
override fun onActivityStopped(a: Activity?) {
}
override fun onActivityCreated(a: Activity, savedInstanceState: Bundle?) {
override fun onActivityCreated(a: Activity?, savedInstanceState: Bundle?) {
}
override fun onActivityPaused(a: Activity) {
override fun onActivityPaused(a: Activity?) {
if (activity == a) {
pauseCounting()
}
}
override fun onActivityResumed(a: Activity) {
override fun onActivityResumed(a: Activity?) {
if (activity == a) {
resumeCounting()
}
}
override fun onActivityDestroyed(a: Activity) {
override fun onActivityDestroyed(a: Activity?) {
if (activity == a) {
HaloApp.getInstance().application.unregisterActivityLifecycleCallbacks(this)
}
@ -115,7 +113,7 @@ class TimeElapsedHelper(val fragment: Fragment?, val activity: Activity?) {
}
object TimeElapsedThreadHolder {
val threadService: ExecutorService by lazy { Executors.newSingleThreadExecutor(GHThreadFactory("TIME_ELAPSED_THREAD")) }
val threadService = Executors.newSingleThreadExecutor()
}
interface TimeoutCallback {

View File

@ -1,3 +0,0 @@
package com.gh.common
typealias OnFastClickListener = (isSuccess: Boolean) -> Unit

View File

@ -1,16 +0,0 @@
package com.gh.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标记那些不需要检查的同步字段
*
* 同步字段冲突时使用
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SyncIgnore {
}

View File

@ -1,12 +0,0 @@
package com.gh.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SyncPage {
String[] syncNames();
}

View File

@ -1,31 +0,0 @@
package com.gh.common.avoidcallback;
import android.content.Intent;
public class ActivityResultInfo {
private int resultCode;
private Intent data;
public ActivityResultInfo(int resultCode, Intent data) {
this.resultCode = resultCode;
this.data = data;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public Intent getData() {
return data;
}
public void setData(Intent data) {
this.data = data;
}
}

View File

@ -1,48 +0,0 @@
package com.gh.common.avoidcallback
import android.content.Intent
import android.os.Bundle
import android.util.SparseArray
import androidx.fragment.app.Fragment
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
class AvoidOnResultFragment : Fragment() {
private val mSubjects = SparseArray<PublishSubject<ActivityResultInfo>>()
private val mCallbacks = SparseArray<Callback>()
private var requestCode = 1000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
}
fun startForResult(intent: Intent): Observable<ActivityResultInfo> {
val subject = PublishSubject.create<ActivityResultInfo>()
return subject.doOnSubscribe {
mSubjects.put(requestCode, subject)
startActivityForResult(intent, requestCode)
requestCode++
}
}
fun startForResult(intent: Intent, callback: Callback) {
mCallbacks.put(requestCode, callback)
startActivityForResult(intent, requestCode)
requestCode++
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val subject = mSubjects.get(requestCode)
if (subject != null) {
subject.onNext(ActivityResultInfo(resultCode, data))
subject.onComplete()
}
mSubjects.remove(requestCode)
val callback = mCallbacks.get(requestCode)
callback?.onActivityResult(resultCode, data)
mCallbacks.remove(requestCode)
}
}

View File

@ -1,64 +0,0 @@
package com.gh.common.avoidcallback
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import io.reactivex.Observable
class AvoidOnResultManager {
val TAG = "AvoidOnResultManager"
private var mAvoidOnResultFragment: AvoidOnResultFragment
private constructor(activity: AppCompatActivity) {
mAvoidOnResultFragment = getAvoidOnResultFragment(activity)
}
private constructor(fragment: Fragment) : this(fragment.activity as AppCompatActivity)
companion object {
fun getInstance(activity: AppCompatActivity): AvoidOnResultManager {
return AvoidOnResultManager(activity)
}
fun getInstance(fragment: Fragment): AvoidOnResultManager {
return AvoidOnResultManager(fragment)
}
}
private fun getAvoidOnResultFragment(activity: AppCompatActivity): AvoidOnResultFragment {
var avoidOnResultFragment = findAvoidOnResultFragment(activity)
if (avoidOnResultFragment == null) {
avoidOnResultFragment = AvoidOnResultFragment()
val fragmentManager = activity.supportFragmentManager
fragmentManager
.beginTransaction()
.add(avoidOnResultFragment, TAG)
.commitAllowingStateLoss()
fragmentManager.executePendingTransactions()
}
return avoidOnResultFragment
}
private fun findAvoidOnResultFragment(activity: AppCompatActivity): AvoidOnResultFragment? {
return activity.supportFragmentManager.findFragmentByTag(TAG) as? AvoidOnResultFragment
}
fun startForResult(intent: Intent, callback: Callback) {
mAvoidOnResultFragment.startForResult(intent, callback)
}
fun startForResult(clazz: Class<*>, callback: Callback) {
val intent = Intent(mAvoidOnResultFragment.activity, clazz)
mAvoidOnResultFragment.startForResult(intent, callback)
}
fun startForResult(intent: Intent): Observable<ActivityResultInfo> {
return mAvoidOnResultFragment.startForResult(intent)
}
fun startForResult(clazz: Class<*>): Observable<ActivityResultInfo> {
val intent = Intent(mAvoidOnResultFragment.activity, clazz)
return mAvoidOnResultFragment.startForResult(intent)
}
}

View File

@ -1,7 +0,0 @@
package com.gh.common.avoidcallback
import android.content.Intent
interface Callback {
fun onActivityResult(resultCode: Int, data: Intent?)
}

View File

@ -1,49 +1,38 @@
package com.gh.common.constant;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import com.gh.common.util.EnvHelper;
import androidx.annotation.Nullable;
import com.gh.common.util.GsonUtils;
import com.gh.common.util.PackageHelper;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.SPUtils;
import com.gh.gamecenter.BuildConfig;
import com.gh.gamecenter.SuggestionActivity;
import com.gh.gamecenter.entity.GameGuidePopupEntity;
import com.gh.gamecenter.entity.NewSettingsEntity;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.entity.SettingsEntity;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.retrofit.BiResponse;
import com.gh.gamecenter.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.halo.assistant.HaloApp;
import com.lightgame.utils.Utils;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import androidx.annotation.Nullable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
public class Config {
// 这个 API_HOST 在测试包里会随着选择的环境切换,正式包里会一直保持正式 host
public static final String API_HOST = EnvHelper.getHost();
public static final String NEW_API_HOST = EnvHelper.getNewHost();
public static final String API_HOST = BuildConfig.API_HOST;
public static final String COMMENT_HOST = BuildConfig.COMMENT_HOST;
public static final String DATA_HOST = BuildConfig.DATA_HOST;
/**
* 需要配置的请使用{@link PreferenceManager#getDefaultSharedPreferences(Context)}
@ -54,20 +43,22 @@ public class Config {
public static final String WECHAT_SECRET = BuildConfig.WECHAT_SECRET;
public static final String TENCENT_APPID = BuildConfig.TENCENT_APPID;
public static final String WEIBO_APPKEY = BuildConfig.WEIBO_APPKEY;
public static final String QUICK_LOGIN_APPID = BuildConfig.QUICK_LOGIN_APPID;
public static final String QUICK_LOGIN_APPKEY = BuildConfig.QUICK_LOGIN_APPKEY;
public static final String MIPUSH_APPID = BuildConfig.MIPUSH_APPID;
public static final String MIPUSH_APPKEY = BuildConfig.MIPUSH_APPKEY;
public static final String MTA_APPKEY = BuildConfig.MTA_APPKEY;
public static final String TALKINGDATA_APPID = BuildConfig.TD_APPID;// TalkingData
public static final String UMENG_APPKEY = BuildConfig.UMENG_APPKEY;
public static final String UMENG_MESSAGE_SECRET = BuildConfig.UMENG_MESSAGE_SECRET;
public static final String BUGLY_APPID = BuildConfig.BUGLY_APPID;
// http://www.ghzs666.com/article/${articleId}.html
public static final String URL_ARTICLE = "http://www.ghzs666.com/article/"; // ghzs/ghzs666 统一
public static final String PATCHES = "patches";
public static final String DEFAULT_CHANNEL = "GH_TEST3";
public static final String DEFAULT_CHANNEL_FOR_RELEASE = "GH_LOST"; // 正式包的缺省渠道,避免因渠道丢失而回落到测试渠道
public static final String DEFAULT_CHANNEL = "GH_TEST";
private static String SETTINGS_KEY = "settingsKey";
private static SettingsEntity mSettingsEntity;
private static NewSettingsEntity mNewSettingsEntity;
private static GameGuidePopupEntity mGameGuidePopupEntity;
private static SharedPreferences mDefaultSharedPreferences;
public static final String FIX_DOWNLOAD_KEY = "isFixDownload";
public static final String FIX_PLUGIN_KEY = "isFixPlugin";
@ -77,8 +68,6 @@ public class Config {
public static final int VIDEO_PAGE_SIZE = 21; // 视频列表大多都是一行3个
public static boolean isShow() {
if (SPUtils.getBoolean(Constants.SP_TEENAGER_MODE)) return false;
if (getPreferences().getBoolean(FIX_DOWNLOAD_KEY, false)) return true;
if (!isExistDownloadFilter()) return false;
@ -212,26 +201,6 @@ public class Config {
return mSettingsEntity;
}
@Nullable
public static NewSettingsEntity getNewSettingsEntity() {
if (mNewSettingsEntity == null) {
try {
String json = SPUtils.getString(Constants.SP_NEW_SETTINGS);
if (!TextUtils.isEmpty(json)) {
mNewSettingsEntity = GsonUtils.fromJson(json, NewSettingsEntity.class);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return mNewSettingsEntity;
}
@Nullable
public static GameGuidePopupEntity getGameGuidePopupEntity() {
return mGameGuidePopupEntity;
}
private static boolean isExistDownloadFilter() {
if (getSettings() == null || getSettings().getDownload() == null || getSettings().getDownload().size() == 0) {
return false;
@ -254,11 +223,7 @@ public class Config {
}
public static SharedPreferences getPreferences() {
if (mDefaultSharedPreferences == null) {
mDefaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(HaloApp.getInstance().getApplication());
}
return mDefaultSharedPreferences;
return PreferenceManager.getDefaultSharedPreferences(HaloApp.getInstance().getApplication());
}
public static boolean isExistHideFunction() {
@ -270,13 +235,6 @@ public class Config {
return false;
}
public static boolean isGameDomeSwitchOpen() {
return getSettings() != null && getSettings().getGameDomeSwitch().equals("on");
}
public static boolean isPermissionPopupSwitchOpen() {
return getSettings() != null && getSettings().getPermissionPopupSwitch().equals("on");
}
public static void fixHideFunction() {
SharedPreferences preferences = PreferenceManager.
getDefaultSharedPreferences(HaloApp.getInstance().getApplication());
@ -288,11 +246,10 @@ public class Config {
editor.apply();
}
@SuppressLint("CheckResult")
public static void getGhzsSettings() {
String channel = HaloApp.getInstance().getChannel();
RetrofitManager.getInstance()
.getApi().getSettings(PackageUtils.getGhVersionName(), channel)
RetrofitManager.getInstance(HaloApp.getInstance().getApplication())
.getApi().getSettings(PackageUtils.getVersionName(), channel)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response<SettingsEntity>() {
@ -309,53 +266,8 @@ public class Config {
if (!getPreferences().getBoolean(Config.FIX_DOWNLOAD_KEY, false) && Config.isShow()) {
getPreferences().edit().putBoolean(Config.FIX_DOWNLOAD_KEY, true).apply();
}
if (!SPUtils.getBoolean(Constants.SP_TEENAGER_MODE)) {
EventBus.getDefault().post(new EBReuse("Refresh"));
}
EventBus.getDefault().post(new EBReuse("Refresh"));
}
});
RetrofitManager.getInstance()
.getApi().getNewSettings(Build.MANUFACTURER, Build.MODEL, channel, Build.VERSION.SDK_INT, BuildConfig.VERSION_NAME)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BiResponse<NewSettingsEntity>() {
@Override
public void onSuccess(NewSettingsEntity data) {
mNewSettingsEntity = data;
SPUtils.setString(Constants.SP_NEW_SETTINGS, GsonUtils.toJson(data));
}
});
RetrofitManager.getInstance()
.getApi().getGameGuidePopup(Build.MANUFACTURER, Build.VERSION.RELEASE, Build.MODEL, channel, BuildConfig.VERSION_NAME)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BiResponse<GameGuidePopupEntity>() {
@Override
public void onSuccess(GameGuidePopupEntity data) {
mGameGuidePopupEntity = data;
}
});
String manufacturer = Build.MANUFACTURER.toUpperCase(Locale.CHINA);
if (manufacturer.equals("OPPO") || manufacturer.equals("VIVO")) {
RetrofitManager.getInstance().getNewApi().getBrowserHintUrl(manufacturer)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BiResponse<ResponseBody>() {
@Override
public void onSuccess(ResponseBody data) {
try {
JSONObject jsonObject = new JSONObject(data.string());
if (!TextUtils.isEmpty(jsonObject.getJSONObject("data").getString("link"))) {
SPUtils.setString(Constants.SP_BROWSER_HINT_URL, jsonObject.getJSONObject("data").getString("link"));
}
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
});
}
}
}

View File

@ -1,8 +1,6 @@
package com.gh.common.constant;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.TimeUtils;
import com.halo.assistant.HaloApp;
public class Constants {
@ -14,12 +12,11 @@ public class Constants {
public final static int NOT_NETWORK_CODE = 504; // 没有网络的状态码(应该是这个吧!)
public static final String LOGIN_TOKEN_ID = "userToken_id"; // 用户ID 与服务器无关
public static final String USER_TOKEN_KEY = "userTokenKey";
public static final String USER_INFO_KEY = "userInfoKey";
public static final String WELCOME_DIALOG_ID = "welcome_dialog_id";
public static final String WELCOME_DIALOG_LINK_TITLE = "welcome_dialog_link_title";
public static final String DEVICE_KEY = "deviceKey";
public static final String HAS_REQUESTED_NOTIFICATION_PERMISSIONS = "has_requested_notification_permissions";
@ -28,66 +25,13 @@ public class Constants {
public static final String GAME_DETAIL_COME_IN = "game_detail_come_in"; // 从游戏详情进入
public static final String SPLASH_AD = "splash_ad"; // 启动广告
public static final String XPOSED_INSTALLER_PACKAGE_NAME = "de.robv.android.xposed.installer";
public static final String EB_QUIT_LOGIN = "quit_login";
public static final String EB_SHOW_AD = "show_ad";
public static final String EB_GAME_DETAIL = "eb_game_detail";
// 用于避免历史下载影响到部分依赖名字作为数据更新条件的修饰符
public static final String GAME_NAME_DECORATOR = " ";
// 游戏详情进入时的自定义栏目标签是否已经默认展开过一次的标记
public static final String SP_HAS_EXPANDED_GAME_DETAIL_TAGS = "has_expanded_game_detail_tags";
// 游戏详情进入时的自定义栏目标签是否已经显示过一次展开更多的浮窗提示
public static final String SP_HAS_SHOWN_EXPANDED_GAME_DETAIL_TAGS_HINT = "has_shown_expanded_game_detail_tags_hint";
// 最近显示的弹窗信息
public static final String SP_LAST_OPENING_ID = "last_opening_dialog_id";
public static final String SP_LAST_OPENING_TIME = "last_opening_dialog_time";
public static final String SP_LAST_ACCEPTED_PRIVACY_DIALOG_ID = "last_accepted_privacy_dialog_id";
// 游戏图标和图标角标
public static final String RAW_GAME_ICON = "raw_game_icon";
public static final String GAME_ICON_SUBSCRIPT = "game_icon_subscript";
public static final String IS_PLATFORM_RECOMMEND = "isPlatformRecommend";
// 下载 id一般来说跟下载文件名一样
public static final String DOWNLOAD_ID = "download_id";
public static final String GHZS_GAME_ID = "5ae4462c2924bc7936438d07";
public static final String EXTRA_DOWNLOAD_TYPE = "extra_download_type";
public static final String SILENT_UPDATE = "静默更新";
public static final String SIMULATOR_DOWNLOAD = "下载模拟器";
public static final String SIMULATOR_GAME = "simulator_game";
public static final String SIMULATOR = "simulator";
public static final String GAME_NAME = "game_name";
public static final String SIMULATOR_DOWNLOAD_START_TIME = "simulator_download_start_time";
public static final String LAST_GHZS_UPDATE_FILE_SIZE = "last_ghzs_update_file_size";
// 新用户首次启动光环的时间
public static final String SP_INITIAL_USAGE_TIME = "initial_usage_time";
public static final String SP_IMEI = "imei";
public static final String SP_ANDROID_ID = "android_id";
// 安装类型
public static final String SP_INSTALL_TYPE = "install_type";
public static final String LAST_INSTALL_GAME = "last_install_game";
// 骨架图配置
public static final int SHIMMER_ANGLE = 18;
public static final int SHIMMER_DURATION = 1200;
public static final float MASK_WIDTH = 0.8F;
public static final float GRADIENT_CENTER_COLOR_WIDTH = 0.1F;
//引导设置 “通知管理” 引导弹窗
public static final String SP_SHOWED_NOTIFICATION_LOGIN = "show_notification_login_hint";
@ -96,159 +40,16 @@ public class Constants {
public static final String SP_SHOWED_NOTIFICATION_ARTICLE = "show_notification_article_hint";
public static final String SP_SHOWED_NOTIFICATION_VIDEO = "show_notification_video_hint";
public static final String SP_SHOWED_NOTIFICATION_RATING = "show_notification_rating_hint";
public static final String SP_SHOWED_NOTIFICATION_GIFT = "show_notification_gift_hint";
public static final String SP_SHOWED_NOTIFICATION_RESERVE_GAME = "show_notification_reserve_game_hint";
public static final String SP_SHOWED_NOTIFICATION_FEEDBACK = "show_notification_feedback_hint";
// 新版本 也要触发一次“通知管理” 引导弹窗
public static final String SP_SHOWED_NOTIFICATION_NEW_VERSION = "show_notification_new_version";
// 今天是否已经触发了 “通知管理” 引导弹窗
public static final String SP_IS_SHOWED_NOTIFICATION_TODAY = "show_is_notification_today";
// v4.0.0已废弃,标记安装的游戏为已玩过弹窗最多取消2次 (https://gitlab.ghzs.com/pm/halo-app-issues/issues/722 调整为版本相关) (不是常量了也放这里好像有点奇怪)
public static final String SP_MARK_INSTALLED_GAME = "mark_installed_game" + PackageUtils.getGhVersionName();
// 标记安装的游戏为已玩过弹窗(个人主页最多弹一次)
public static final String SP_MARK_INSTALLED_GAME_USER_HOME = "mark_installed_game_user_home" + PackageUtils.getGhVersionName();
// 标记安装的游戏为已玩过弹窗(我的游戏最多弹一次)
public static final String SP_MARK_INSTALLED_GAME_MY_GAME = "mark_installed_game_my_game" + PackageUtils.getGhVersionName();
// 标记安装的游戏为已玩过弹窗最多取消2次 (https://gitlab.ghzs.com/pm/halo-app-issues/issues/722 调整为版本相关) (不是常量了也放这里好像有点奇怪)
public static final String SP_MARK_INSTALLED_GAME = "mark_installed_game" + PackageUtils.getVersionName();
//视频详情滑动引导
public static final String SP_SHOW_SLIDE_GUIDE = "show_slide_guide";
//视频详情点击引导
public static final String SP_SHOW_CLICK_GUIDE = "show_click_guide";
//视频详情双击点赞引导
public static final String SP_SHOW_DOUBLE_CLICK_GUIDE = "show_double_click_guide";
//顶部视频声音状态,重启恢复
public static final String SP_TOP_VIDEO_VOICE = "top_video_voice";
//我的光环提醒设置已读
public static final String SP_ADDONS_FUNCS_HAVE_READ = "addons_funcs_have_read";
//视频非wifi提醒只提醒一次重启恢复
public static final String SP_NON_WIFI_TIPS = "non_wifi_tips";
//首页视频最新tab提示
public static final String SP_HOME_NEW_VIDEO_TIPS = "home_new_video";
//游戏设备弹窗提示
public static final String SP_DEVICE_REMIND = "device_remind";
//是否是第一次弹出游戏设备弹窗提示
public static final String SP_FIRST_DEVICE_REMIND = "first_device_remind";
//游戏设备弹窗不再提示
public static final String SP_NO_REMIND_AGAIN = "no_remind_again";
//游戏详情过滤标签数据
public static final String SP_FILTER_TAGS = "filter_tags";
//实名认证弹窗分类数据
public static final String SP_AUTH_DIALOG = "auth_dialog";
//我的光环小红点提示
public static final String SP_GH_RED_POINT_REMIND = "gh_red_point_remind";
//论坛首页引导
public static final String SP_FORUM_GUIDE = "forum_guide";
//礼仪考试开启状态
public static final String SP_REGULATION_TEST_LAST_REMIND_TIME = "regulation_test_last_remind_time";
public static final String SP_REGULATION_TEST_STATUS = "regulation_test_status";
public static final String SP_REGULATION_TEST_PASS_STATUS = "regulation_test_pass_status";
//相同设备号,每一种第三方登录方式登录后弹出绑定手机页面的次数
public static final String SP_QQ_SHOW_BIND_PHONE_TIME = "qq_show_bind_phone_time" + HaloApp.getInstance().getGid();
public static final String SP_WECHAT_SHOW_BIND_PHONE_TIME = "wechat_show_bind_phone_time" + HaloApp.getInstance().getGid();
public static final String SP_WEIBO_SHOW_BIND_PHONE_TIME = "weibo_show_bind_phone_time" + HaloApp.getInstance().getGid();
public static final String SP_DOUYIN_SHOW_BIND_PHONE_TIME = "douyin_show_bind_phone_time" + HaloApp.getInstance().getGid();
//隐私政策是否有更新
public static final String SP_PRIVACY_CURRENT_MD5 = "sp_privacy_current_md5";
public static final String SP_PRIVACY_MINE_MD5 = "sp_privacy_mine_md5";
public static final String SP_PRIVACY_SETTING_MD5 = "sp_privacy_setting_md5";
public static final String SP_PRIVACY_MD5 = "sp_privacy_md5";
public static final String SP_IS_USER_ACCEPTED_PRIVACY_STATEMENT = "has_user_accepted_privacy_statement";
public static final String SP_BRAND_NEW_USER = "brand_new_user";
//包名检测是否点击不再提示
public static final String SP_PACKAGE_CHECK = "package_check";
//游戏详情预约引导提示
public static final String SP_GAME_DETAIL_RESERVE_GUIDE = "game_detail_reserve_guide";
public static final String SP_XAPK_UNZIP_ACTIVITY = "xapk_unzip_activity";
public static final String SP_XAPK_URL = "xapk_url";
//游戏详情推荐弹窗
public static final String SP_RECOMMEND_POPUP = "recommend_popup";
// 设备实名信息
public static final String SP_DEVICE_CERTIFICATION_PREFIX = "device_certification_prefix";
// 使用浏览器安装开关
public static final String SP_USE_BROWSER_TO_INSTALL = "use_browser_to_install";
// 游戏详情页底部使用浏览器安装提示
public static final String SP_SHOULD_SHOW_GAMEDETAIL_USE_BROWSER_TO_INSTALL_HINT = "should_show_gamedetail_use_browser_to_install_hint";
// 第一次普通安装推荐使用浏览器安装提示
public static final String SP_SHOULD_SHOW_USE_BROWSER_TO_INSTALL_HINT = "should_show_use_browser_to_install_hint";
// 游戏详情切换安装方式显示开关
public static final String SP_SWITCH_INSTALL_VISIBLE = "sp_switch_install_visible";
//模拟器管理引导
public static final String SP_SIMULATOR_GUIDE = "simulator_guide";
//模拟器游戏引导
public static final String SP_SIMULATOR_GAME_GUIDE = "simulator_game_guide";
// 临时设备ID (本地生成与GID不相关)
public static final String SP_TEMPORARY_DEVICE_ID = "temporary_device_id";
// 光环助手最后的安装(更新)时间
public static final String SP_GH_LAST_UPDATE_TIME = "gh_last_update_time";
//首页视频播放进度
public static final String SP_HOME_VIDEO_PLAY_RECORD = "home_video_play_record";
// 论坛内容视频播放进度
public static final String SP_CONTENT_VIDEO_PLAY_RECORD = "content_video_play_record";
// 用户是否曾经永久拒绝过存储权限
public static final String SP_USER_HAS_PERMANENTLY_DENIED_STORAGE_PERMISSION = "user_has_permanently_denied_storage_permission";
// 是否已经填写邀请码
public static final String SP_HAS_COMPLETE_INVITE_CODE = "has_complete_invite_code";
// 补充配置项
public static final String SP_NEW_SETTINGS = "new_settings";
// 头像挂件ID
public static final String SP_CHOOSE_AVATAR_ID = "choose_avatar_id";
// 是否第一次进入新分类2.0
public static final String SP_FIRST_ENTER_CATEGORY_V2 = "first_enter_category_v2";
// 是否成功取过号
public static final String SP_HAS_GET_PHONE_INFO = "has_get_phone_info";
// 是否点击过更换背景按钮
public static final String SP_HAS_CLICK_CHANGE_BG = "has_click_change_bg";
// 是否显示更换背景提示
public static final String SP_SHOW_CHANGE_BG_TIPS = "show_change_bg_tips" + TimeUtils.getStartTimeOfToday();
// 新分类2.0引导
public static final String SP_SHOW_CATEGORY_GUIDE = "show_category_guide";
// 用户是否需要 weibo x86 so
public static final String SP_USER_NEED_WEIBO_X86_SO = "user_need_weibo_x86_so";
// 当前设备是不是模拟器
public static final String SP_IS_EMULATOR = "is_emulator";
// 内容视频播放选项
public static final String SP_CONTENT_VIDEO_OPTION = "content_video_option";
// 首页/游戏详情页视频播放选项
public static final String SP_HOME_OR_DETAIL_VIDEO_OPTION = "home_or_detail_video_option";
// 是否默认静音播放视频
public static final String SP_VIDEO_PLAY_MUTE = "video_play_mute";
//帖子发布页上传视频引导
public static final String SP_ARTICLE_VIDEO_GUIDE = "article_video_guide";
//问题发布页上传视频引导
public static final String SP_QUESTION_VIDEO_GUIDE = "question_video_guide";
// 论坛详情申请版主引导
public static final String SP_FORUM_DETAIL_MODERATOR_GUIDE = "forum_detail_moderator_guide";
// 游戏详情安装引导
public static final String SP_GAME_DETAIL_INSTALL_GUIDE = "game_detail_install_guide";
public static final String SP_SHOULD_SHOW_GAME_DETAIL_INSTALL_GUIDE = "should_show_game_detail_install_guide";
// 儿童/青少年模式
public static final String SP_TEENAGER_MODE = "teenager_mode";
// 我的游戏引导
public static final String SP_MY_GAME_GUIDE = "my_game_guide";
//微信绑定配置信息
public static final String SP_WECHAT_CONFIG = "wechat_config";
//游戏库导航栏小红点提示
public static final String SP_GAME_NAVIGATION = "game_navigation";
//手机号码匹配规则
public static final String REGEX_MOBILE = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
@ -258,125 +59,13 @@ public class Constants {
//输入规则
public static final String INPUT_RULE = "0123456789abcdefghijklnmopqrstuvwxyzABCDEFGHIJKLNMOPQRSTUVWXYZ_";
// 微信绑定地址
public static final String WECHAT_BIND_ADDRESS_DEV = "https://dev-and-static.ghzs.com/web/wechat_bind/index.html#/";
public static final String WECHAT_BIND_ADDRESS = "https://and-static.ghzs.com/web/wechat_bind/index.html#/";
// 微信绑定地址地址
public static final String WECHAT_BIND_ADDRESS_DEV = "https://resource.ghzs.com/page/wechat_dev/index.html#/";
public static final String WECHAT_BIND_ADDRESS = "https://resource.ghzs.com/page/wechat_pro/index.html#/";
// 礼仪考试地址
public static final String REGULATION_TEST_ADDRESS_DEV = "https://static-web.ghzs.com/etiquette-dev/index.html#/";
public static final String REGULATION_TEST_ADDRESS = "https://static-web.ghzs.com/etiquette/index.html#/";
// 徽章中心
public static final String BADGE_ADDRESS_DEV = "https://static-web.ghzs.com/badge-dev/index.html#/";
public static final String BADGE_ADDRESS = "https://static-web.ghzs.com/badge/index.html#/";
// 徽章详情
public static final String BADGE_DETAIL_ADDRESS_DEV = "https://static-web.ghzs.com/badge-dev/index.html#/badgedetail";
public static final String BADGE_DETAIL_ADDRESS = "https://static-web.ghzs.com/badge/index.html#/badgedetail";
// 分享个人主页地址
public static final String SHARE_USER_HOME_ADDRESS_DEV = "https://static-web.ghzs.com/ghzs-userhome-dev/index.html#/";
public static final String SHARE_USER_HOME_ADDRESS = "https://static-web.ghzs.com/ghzs-userhome/index.html#/";
// 腾讯企点地址
public static final String TENCENT_QIDIAN_ADDRESS = "https://admin.qidian.qq.com/template/blue/mp/menu/qr-code-jump.html?linkType=0&env=ol&kfuin=2355094296&fid=457&key=c76dcb2e3d582b6ffbfb5bb22cde85ff&cate=1&source=&isLBS=&isCustomEntry=&type=16&ftype=1&_type=wpa&qidian=true";
//版规声明
public static final String FORUM_REGULATIONS_NEWS_ID = "5f4db9cc34d44d01b92fd670";
// 权限使用场景地址
public static final String PERMISSION_SCENARIO_ADDRESS = "https://resource.ghzs.com/page/permissions/android.html";
//帮助内容详情
public static final String HELP_ADDRESS_DEV = "https://static-web.ghzs.com/ghzs_help_dev/help.html?content=";
public static final String HELP_ADDRESS = "https://static-web.ghzs.com/ghzs_help/help.html?content=";
// 注销页面
public static final String LOGOUT_ADDRESS_DEV = "https://static-web.ghzs.com/ghzs_help_dev/help.html?content=5f6b1f02786564003944a693&from=ghzs";
public static final String LOGOUT_ADDRESS = "https://static-web.ghzs.com/ghzs_help/help.html?content=5f534111b1f72909fc225672&from=ghzs";
// 商品详情
public static final String COMMODITY_DETAIL_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/product?from=ghzs";
public static final String COMMODITY_DETAIL_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/product?from=ghzs";
// 光能记录
public static final String ENERGY_RECORD_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/record?from=ghzs";
public static final String ENERGY_RECORD_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/record?from=ghzs";
// 订单中心
public static final String ORDER_CENTER_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/orders?from=ghzs";
public static final String ORDER_CENTER_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/orders?from=ghzs";
// 订单详情
public static final String ORDER_DETAIL_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/order-detail?from=ghzs";
public static final String ORDER_DETAIL_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/order-detail?from=ghzs";
// 邀请好友
public static final String INVITE_FRIENDS_ADDRESS_DEV = "https://static-web.ghzs.com/ghzs_activity_dev/inviteFriends.html#/invite";
public static final String INVITE_FRIENDS_ADDRESS = "https://static-web.ghzs.com/ghzs_activity_prod/inviteFriends.html#/invite";
// 等级页面
public static final String LEVEL_ADDRESS_DEV = "https://static-web.ghzs.com/ghzs-userhome-dev/index.html#/level";
public static final String LEVEL_ADDRESS = "https://static-web.ghzs.com/ghzs-userhome/index.html#/level";
// 兑换规则
public static final String EXCHANGE_RULE_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/exchange-rule?from=ghzs";
public static final String EXCHANGE_RULE_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/exchange-rule?from=ghzs";
// 光能规则
public static final String ENERGY_RULE_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/energy-rule?from=ghzs";
public static final String ENERGY_RULE_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/energy-rule?from=ghzs";
// 兑换商品
public static final String EXCHANGE_COMMODITY_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/exchange-log?from=ghzs";
public static final String EXCHANGE_COMMODITY_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/exchange-log?from=ghzs";
// 抽奖乐园
public static final String LOTTERY_PARADISE_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/lottery-list?from=ghzs";
public static final String LOTTERY_PARADISE_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/lottery-list?from=ghzs";
// 我的奖品
public static final String MY_PRIZE_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/mywin?from=ghzs";
public static final String MY_PRIZE_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/mywin?from=ghzs";
// 中奖订单详情
public static final String WIN_ORDER_DETAIL_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/win-order-detail?from=ghzs";
public static final String WIN_ORDER_DETAIL_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/win-order-detail?from=ghzs";
// 地址信息
public static final String ADDRESS_INFO_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/address-list?from=ghzs";
public static final String ADDRESS_INFO_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/address-list?from=ghzs";
// 领奖信息
public static final String PRIZE_INFO_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/user-info?from=ghzs";
public static final String PRIZE_INFO_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/user-info?from=ghzs";
// 提现信息
public static final String WITHDRAW_INFO_ADDRESS_DEV = "https://static-web.ghzs.com/shop-dev/index.html#/cash?from=ghzs";
public static final String WITHDRAW_INFO_ADDRESS = "https://static-web.ghzs.com/shop/index.html#/cash?from=ghzs";
// 活动详情
public static final String ACTIVITY_DETAIL_ADDRESS_DEV = "https://static-web.ghzs.com/ghzs_activity_dev/common.html?from=ghzs";
public static final String ACTIVITY_DETAIL_ADDRESS = "https://static-web.ghzs.com/ghzs_activity_prod/common.html?from=ghzs";
// 游戏单详情分享链接
public static final String GAME_COLLECTION_SHARE_ADDRESS_DEV = "https://dev-and-static.ghzs.com/web/game_collection/index.html#/?from=ghzs";
public static final String GAME_COLLECTION_SHARE_ADDRESS = "https://and-static.ghzs.com/web/game_collection/index.html#/?from=ghzs";
// 游戏单活动分享链接 https://git.shanqu.cc/pm/halo-app-issues/-/issues/1638
public static final String GAME_COLLECTION_ACTIVITY_ADDRESS_DEV = "https://dev-and-static.ghzs.com/web/ghzs_activity/haoyouUnlock.html";
public static final String GAME_COLLECTION_ACTIVITY_ADDRESS = "https://and-static.ghzs.com/web/ghzs_activity/haoyouUnlock.html";
// 青少年模式找回密码
public static final String TEEN_MODE_RESET_PASSWORD = "https://resource.ghzs.com/page/privacy_policies/help_password.html";
// 儿童/青少年使用须知
public static final String TEEN_MODE_RULE = "https://resource.ghzs.com/page/privacy_policies/teenager_privacy.html";
//游戏单管理规范
public static final String GAME_COLLECTION_RULE = "https://resource.ghzs.com/page/privacy_policies/game_collection.html";
public static final String SP_IS_DEV_ENV = "is_dev_env";
// 徽章
public static final String BADGE_ADDRESS_DEV = "http://resource.ghzs.com/page/badge_dev/index.html#/";
public static final String BADGE_ADDRESS = "http://resource.ghzs.com/page/badge_pro/index.html#/";
//最少需要多少数据才能上传
public static final int DATA_AMOUNT = 20;
@ -395,33 +84,13 @@ public class Constants {
public static final int COMMENT_CD = 60 * 1000;
//我的光环功能分组 cd间隔
public static final int ADDONS_CD = 10 * 60 * 1000;
//已收录包名更新 cd间隔
public static final int PACKAGES_CD = 60 * 1000;
public static final String[] REPORT_LIST = new String[]{"垃圾广告营销", "恶意攻击谩骂", "淫秽色情信息", "违法有害信息", "他原因"};
public static final String[] REPORT_LIST = new String[]{"垃圾广告营销", "恶意攻击谩骂", "淫秽色情信息", "违法有害信息", ""};
public static final String ENTRANCE_UNKNOWN = "(unknown)";
public static final String DEFAULT_TEXT_WRAPPER = "###";
// 触发了安装事件的标记
public static final String MARK_ALREADY_TRIGGERED_INSTALLATION = "triggered_installation";
// 标记下载重试标记(值为任务已下载大小,为空表示需要重试)
public static final String MARK_RETRY_DOWNLOAD = "retry_download";
// 工具箱历史记录最多4个
public static final String TOOLBOX_HISTORY = "toolbox_history";
// 浏览器安装说明url
public static final String SP_BROWSER_HINT_URL = "browser_hint_url";
public static final String DEFAULT_OPPO_BROWSER_HINT_URL = "https://static-web.ghzs.com/ghzs_help/help.html?content=5fa90fe143d91a022e0d33ff";
public static final String DEFAULT_VIVO_BROWSER_HINT_URL = "https://static-web.ghzs.com/ghzs_help/help.html?content=618112ce04796e63e97643a4&from=ghzs";
public static final int FOLLOW_HINT_TRIGGER_HEIGHT = 10;
// 深色模式
public static final String SP_NIGHT_MODE = "night_mode";
// 跟随系统模式
public static final String SP_SYSTEM_MODE = "system_mode";
}

View File

@ -32,12 +32,6 @@ public class ItemViewType {
public static final int IMAGE_SLIDE_ITEM = 23;
public static final int VERTICAL_SLIDE_ITEM = 24;
public static final int COLUMN_COLLECTION = 25;
public static final int GALLERY_SLIDE = 27; // 首页自动滚动画廊专题
public static final int GALLERY = 28; // 首页倾斜画廊专题
public static final int BLANK_DIVIDER = 29; // 空白补充区域
public static final int COMMON_LINK_COLLECTION = 30; // 通用链接合集
public static final int RANK_COLLECTION = 31; // 排行榜样式专题合集
public static final int GAME_COLLECTION_ITEM = 32; // 游戏单
/**
* 普通列表

View File

@ -1,185 +0,0 @@
package com.gh.common.databind
import android.os.Build
import android.text.Editable
import android.text.Html
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import com.gh.base.OnViewClickListener
import com.gh.common.util.dip2px
import com.gh.common.util.toDrawable
import com.gh.common.view.BugFixedPopupWindow
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.KaifuAddItemBinding
import com.gh.gamecenter.databinding.LayoutAddKaifuPopupBinding
import com.gh.gamecenter.databinding.LayoutPopupContainerBinding
import com.gh.gamecenter.entity.ServerCalendarEntity
import com.gh.gamecenter.servers.add.AddKaiFuPopupAdapter
import java.text.SimpleDateFormat
import java.util.*
object AddKaiFuBindingAdapter {
private var popupWindow: BugFixedPopupWindow? = null
@JvmStatic
@BindingAdapter("addKaiFuView", "clickListener")
fun addKaiFuView(
view: LinearLayout,
list: List<ServerCalendarEntity?>?,
listener: OnViewClickListener<*>?
) {
if (list == null) return
view.removeAllViews()
view.addView(LayoutInflater.from(view.context).inflate(R.layout.kaifu_new_add_item_title, null))
for (i in list.indices) {
val inflate = LayoutInflater.from(view.context).inflate(R.layout.kaifu_add_item, null)
val binding = KaifuAddItemBinding.bind(inflate)
binding.clickListener = listener
binding.entity = list[i]
binding.position = i
binding.isCloseBottom = list.size - 1 == i
view.addView(inflate)
binding.kaifuAddFirstName.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
binding.kaifuAddFirstName.hint = ""
if (binding.kaifuAddFirstName.text.isNullOrEmpty()) {
showPopupOption(binding.kaifuAddFirstName) {
binding.kaifuAddFirstName.setText(it)
binding.kaifuAddFirstName.setSelection(it.length)
}
}
} else {
binding.kaifuAddFirstName.hint = "点击填写"
}
}
binding.kaifuAddServerName.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
binding.kaifuAddServerName.hint = ""
} else {
binding.kaifuAddServerName.hint = "点击填写"
}
}
binding.kaifuAddFirstName.addTextChangedListener(object :TextWatcher{
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (!s.isNullOrEmpty()){
popupWindow?.dismiss()
}
}
override fun afterTextChanged(s: Editable?) {
}
})
if (i == list.size - 1) {
binding.kaifuAddTime.background = R.drawable.bg_add_kaifu_bottom_left.toDrawable()
binding.kaifuAddServerName.background = R.drawable.bg_add_kaifu_bottom_right.toDrawable()
}
}
}
@JvmStatic
@BindingAdapter("addKaiFuTime", "addKaiFuPosition")
fun addKaiFuTime(view: EditText, time: Long, position: Int) {
if (time == 0L) {
view.hint = "点击选择"
view.setText("")
} else {
val pattern = "yyy-MM-dd HH:mm"
val format = SimpleDateFormat(pattern, Locale.CHINA)
view.setText(format.format(time * 1000))
if (position == 0) {
view.append(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) Html.fromHtml(
String.format(
"<font color='#2496FF'>%1\$s</font>",
"&nbsp+"
), Html.FROM_HTML_MODE_LEGACY
) else Html.fromHtml(String.format("<font color='#2496FF'>%1\$s</font>", "&nbsp+")))
}
}
}
@JvmStatic
@BindingAdapter("kaiFuTextColor", "kaiFuTextPosition")
fun kaiFuTextColor(view: EditText, dataMark: Int, position: Int) {
if (dataMark == 1 && view.id == R.id.kaifu_add_time || dataMark == 2 && view.id == R.id.kaifu_add_first_name || dataMark == 3 && view.id == R.id.kaifu_add_server_name || dataMark == 4) {
view.setTextColor(ContextCompat.getColor(view.context, R.color.theme_red))
view.setHintTextColor(ContextCompat.getColor(view.context, R.color.theme_red))
} else if (position == 0) {
view.setTextColor(ContextCompat.getColor(view.context, R.color.hint))
view.setHintTextColor(ContextCompat.getColor(view.context, R.color.hint))
} else {
view.setTextColor(ContextCompat.getColor(view.context, R.color.text_title))
view.setHintTextColor(ContextCompat.getColor(view.context, R.color.hint))
}
}
@JvmStatic
private fun showPopupOption(view: View, callback: (text: String) -> Unit) {
val inflater = LayoutInflater.from(view.context)
val mainBinding = LayoutPopupContainerBinding.inflate(inflater)
popupWindow = BugFixedPopupWindow(
mainBinding.root,
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
val windowPos = IntArray(2)
val anchorLoc = IntArray(2)
// 获取锚点View在屏幕上的左上角坐标位置
view.getLocationOnScreen(anchorLoc)
val anchorHeight = view.height
// 获取屏幕的高宽
val screenHeight = view.context.resources.displayMetrics.heightPixels
popupWindow?.let { popupWindow ->
// 测量contentView
popupWindow.contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
val windowHeight = popupWindow.contentView.measuredHeight
// 判断需要向上弹出还是向下弹出显示
val isNeedShowUp = screenHeight - anchorLoc[1] - anchorHeight < windowHeight
windowPos[1] = if (isNeedShowUp) {
anchorLoc[1] - windowHeight
} else anchorLoc[1] + anchorHeight
LayoutAddKaifuPopupBinding.inflate(inflater, mainBinding.container, false).apply {
root.layoutParams = root.layoutParams.apply {
width = view.width + 16F.dip2px()
}
popupRv.adapter = AddKaiFuPopupAdapter(
root.context,
arrayListOf("安卓混服", "硬核专服", "官方专服", "官方渠道服", "腾讯QQ服", "腾讯微信服")
) {
callback.invoke(it)
popupWindow.dismiss()
}
popupRv.layoutManager = LinearLayoutManager(root.context)
mainBinding.container.addView(root)
}
popupWindow.isTouchable = true
popupWindow.inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED
popupWindow.isOutsideTouchable = true
popupWindow.animationStyle = R.style.popwindow_option_anim_style
// 设置偏移
windowPos[1] = windowPos[1] - 12F.dip2px()
windowPos[0] = anchorLoc[0] - 11F.dip2px()
popupWindow.showAtLocation(view, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
}
}
}

View File

@ -2,7 +2,6 @@ package com.gh.common.databind;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
@ -10,30 +9,22 @@ import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.base.OnViewClickListener;
import com.gh.common.constant.Config;
import com.gh.common.dialog.CertificationDialog;
import com.gh.common.dialog.PackageCheckDialogFragment;
import com.gh.common.dialog.ReserveDialogFragment;
import com.gh.common.exposure.ExposureEvent;
import com.gh.common.history.HistoryHelper;
import com.gh.common.exposure.ExposureUtils;
import com.gh.common.repository.ReservationRepository;
import com.gh.common.simulator.SimulatorDownloadManager;
import com.gh.common.simulator.SimulatorGameManager;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.DownloadDialogHelper;
import com.gh.common.util.ExtensionsKt;
import com.gh.common.util.GameUtils;
import com.gh.common.util.GameViewUtils;
import com.gh.common.util.ImageUtils;
@ -41,21 +32,19 @@ import com.gh.common.util.LogUtils;
import com.gh.common.util.MtaHelper;
import com.gh.common.util.NewsUtils;
import com.gh.common.util.NumberUtils;
import com.gh.common.util.PackageInstaller;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PermissionHelper;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.RealNameHelper;
import com.gh.common.util.ReservationHelper;
import com.gh.common.view.DownloadDialog;
import com.gh.common.view.DownloadProgressBar;
import com.gh.common.view.DrawableView;
import com.gh.common.view.GameIconView;
import com.gh.download.DownloadManager;
import com.gh.download.dialog.DownloadDialog;
import com.gh.download.server.BrowserInstallHelper;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.WebActivity;
import com.gh.gamecenter.baselist.LoadStatus;
import com.gh.gamecenter.databinding.KaifuAddItemBinding;
import com.gh.gamecenter.databinding.KaifuDetailItemRowBinding;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
@ -63,9 +52,7 @@ import com.gh.gamecenter.entity.LinkEntity;
import com.gh.gamecenter.entity.PluginLocation;
import com.gh.gamecenter.entity.ServerCalendarEntity;
import com.gh.gamecenter.entity.TagStyleEntity;
import com.gh.gamecenter.entity.TestEntity;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.gamedetail.dialog.GamePermissionDialogFragment;
import com.gh.gamecenter.manager.PackagesManager;
import com.gh.gamecenter.qa.entity.CommunityVideoEntity;
import com.lightgame.download.DownloadEntity;
@ -74,9 +61,15 @@ import com.lightgame.utils.Utils;
import org.greenrobot.eventbus.EventBus;
import java.io.File;
import java.util.ArrayList;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.BindingAdapter;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
/**
* Created by khy on 12/02/18.
@ -84,37 +77,22 @@ import java.util.List;
public class BindingAdapters {
@BindingAdapter("imageIcon")
public static void loadIcon(SimpleDraweeView view, String imageUrl) {
ImageUtils.displayIcon(view, imageUrl);
}
@BindingAdapter("imageUrl")
public static void loadImage(SimpleDraweeView view, String imageUrl) {
ImageUtils.display(view, imageUrl);
}
@BindingAdapter("setTextSize")
public static void setTextSize(TextView view, int number) {
view.setTextSize(number);
}
public static void setTypeface(TextView view, String type) {
if (type == null) return;
switch (type) {
case "bold":
view.setTypeface(null, Typeface.BOLD);
break;
case "italic":
view.setTypeface(null, Typeface.ITALIC);
break;
case "bold_italic":
view.setTypeface(null, Typeface.BOLD_ITALIC);
break;
default:
view.setTypeface(null, Typeface.NORMAL);
break;
}
}
@BindingAdapter({"addDetailKaiFuView", "addDetailKaiFuViewListener", "isReadyPatch"})
public static void addDetailKaiFuView(LinearLayout view, List<ServerCalendarEntity> list
, OnViewClickListener listener, Boolean isReadyPatch) {
if (list == null) return;
@ -122,13 +100,13 @@ public class BindingAdapters {
for (int i = 0; i < list.size() + 1; i++) { // 1 is Title
View inflate = LayoutInflater.from(view.getContext()).inflate(R.layout.kaifu_detail_item_row, null);
KaifuDetailItemRowBinding binding = KaifuDetailItemRowBinding.bind(inflate);
binding.getRoot().setBackgroundColor(isReadyPatch != null && isReadyPatch ? ExtensionsKt.toColor(R.color.theme) : ExtensionsKt.toColor(R.color.white));
binding.getRoot().setPadding(DisplayUtils.dip2px(1), DisplayUtils.dip2px(1), DisplayUtils.dip2px(1), i == list.size() ? DisplayUtils.dip2px(1) : 0);
ServerCalendarEntity serverEntity = list.get(i - 1);
binding.timeTv.setText(i == 0 ? "时间" : serverEntity.getFormatTime("HH:mm"));
binding.remarkTv.setText(i == 0 ? "备注" : serverEntity.getRemark());
binding.nameTv.setText(i == 0 ? "名字" : (TextUtils.isEmpty(serverEntity.getNote()) ? "-" : serverEntity.getNote()));
if (i != 0) {
binding.setIsCloseBottom(i == list.size());
binding.setIsReadyPatch(isReadyPatch);
if (i == 0) {
binding.setIsTitle(true);
} else {
ServerCalendarEntity serverEntity = list.get(i - 1);
binding.setEntity(serverEntity);
binding.getRoot().setOnClickListener(v -> {
listener.onClick(v, isReadyPatch != null && isReadyPatch ? serverEntity : null);
});
@ -150,20 +128,77 @@ public class BindingAdapters {
}
// 如果超过10000则转换为1.0W
@BindingAdapter("transSimpleCount")
public static void transSimpleCount(TextView view, int count) {
view.setText(NumberUtils.transSimpleCount(count));
}
public static void textColorFromString(TextView tv, String hexString) {
if (TextUtils.isEmpty(hexString)) return;
@BindingAdapter({"addKaiFuView", "clickListener"})
public static void addKaiFuView(LinearLayout view, List<ServerCalendarEntity> list, OnViewClickListener listener) {
if (list == null) return;
view.removeAllViews();
view.addView(LayoutInflater.from(view.getContext()).inflate(R.layout.kaifu_add_item_title, null));
for (int i = 0; i < list.size(); i++) {
View inflate = LayoutInflater.from(view.getContext()).inflate(R.layout.kaifu_add_item, null);
KaifuAddItemBinding binding = KaifuAddItemBinding.bind(inflate);
binding.setClickListener(listener);
binding.setEntity(list.get(i));
binding.setPosition(i);
binding.setIsCloseBottom(list.size() - 1 == i);
view.addView(inflate);
try {
tv.setTextColor(Color.parseColor(hexString));
} catch (Exception e) {
e.printStackTrace();
binding.kaifuAddName.setOnFocusChangeListener((v, hasFocus) -> {
if (hasFocus) {
binding.kaifuAddName.setHint("");
} else {
binding.kaifuAddName.setHint("点击填写");
}
});
binding.kaifuAddRemark.setOnFocusChangeListener((v, hasFocus) -> {
if (hasFocus) {
binding.kaifuAddRemark.setHint("");
} else {
binding.kaifuAddRemark.setHint("点击填写");
}
});
}
}
@BindingAdapter({"addKaiFuTime", "addKaiFuPosition"})
public static void addKaiFuTime(EditText view, Long time, Integer position) {
if (time == 0) {
view.setHint("点击选择");
view.setText("");
} else {
String pattern;
if (position == 0) {
pattern = "yyy-MM-dd HH:mm +";
} else {
pattern = "yyy-MM-dd HH:mm";
}
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.CHINA);
view.setText(format.format(time * 1000));
}
}
@BindingAdapter({"kaiFuTextColor", "kaiFuTextPosition"})
public static void kaiFuTextColor(EditText view, Integer dataMark, Integer position) {
if (dataMark == 1 && view.getId() == R.id.kaifu_add_time
|| dataMark == 2 && view.getId() == R.id.kaifu_add_name
|| dataMark == 3 && view.getId() == R.id.kaifu_add_remark
|| dataMark == 4 && (view.getId() == R.id.kaifu_add_time || view.getId() == R.id.kaifu_add_name)) {
view.setTextColor(ContextCompat.getColor(view.getContext(), R.color.red));
view.setHintTextColor(ContextCompat.getColor(view.getContext(), R.color.red));
} else if (position == 0) {
view.setTextColor(ContextCompat.getColor(view.getContext(), R.color.hint));
view.setHintTextColor(ContextCompat.getColor(view.getContext(), R.color.hint));
} else {
view.setTextColor(ContextCompat.getColor(view.getContext(), R.color.title));
view.setHintTextColor(ContextCompat.getColor(view.getContext(), R.color.hint));
}
}
@BindingAdapter("visibleGone")
public static void showHide(View view, Boolean show) {
if (show != null && show) {
view.setVisibility(View.VISIBLE);
@ -172,43 +207,7 @@ public class BindingAdapters {
}
}
public static void goneIf(View view, Boolean gone) {
if (gone != null && gone) {
view.setVisibility(View.GONE);
} else {
view.setVisibility(View.VISIBLE);
}
}
/**
* lazy 的 paddingTop
*/
public static void lazyPaddingLeft(View view, int paddingLeftInDp) {
view.setPadding(DisplayUtils.dip2px(paddingLeftInDp), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom());
}
/**
* lazy 的 paddingTop
*/
public static void lazyPaddingTop(View view, int paddingTopInDp) {
view.setPadding(view.getPaddingLeft(), DisplayUtils.dip2px(paddingTopInDp), view.getPaddingRight(), view.getPaddingBottom());
}
/**
* lazy 的 paddingBottom
*/
public static void lazyPaddingBottom(View view, int paddingBottomInDp) {
view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), DisplayUtils.dip2px(paddingBottomInDp));
}
public static void visibleInvisible(View view, Boolean show) {
if (show != null && show) {
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.INVISIBLE);
}
}
@BindingAdapter("messageUnread")
public static void setMessageUnread(TextView view, int unreadCount) {
if (unreadCount < 100) {
view.setText(String.valueOf(unreadCount));
@ -217,6 +216,7 @@ public class BindingAdapters {
}
}
@BindingAdapter("serverTypePadding")
public static void setServerTypePadding(TextView view, String serverType) {
int paddRight = 0;
if (TextUtils.isEmpty(serverType)) {
@ -234,6 +234,7 @@ public class BindingAdapters {
view.setPadding(0, 0, paddRight, 0);
}
@BindingAdapter("serverType")
public static void setServerType(TextView view, String serverType) {
view.setText(serverType);
if ("删档内测".equals(serverType) || "不删档内测".equals(serverType)) {
@ -243,22 +244,12 @@ public class BindingAdapters {
}
}
public static void setGame(View view, GameEntity gameEntity) {
if (gameEntity != null && view instanceof GameIconView) {
((GameIconView) view).displayGameIcon(gameEntity);
}
}
public static void setGameIcon(View view, GameEntity gameEntity) {
if (gameEntity != null && view instanceof GameIconView) {
((GameIconView) view).displayGameIcon(gameEntity.getIcon(), gameEntity.getIconSubscript());
}
}
@BindingAdapter("articleType")
public static void setArticleType(TextView view, String articleType) {
NewsUtils.setNewsType(view, articleType, 0, 0);
}
@BindingAdapter("detailDownloadText")
public static void setDetailDownloadText(TextView view, GameEntity gameEntity) {
if (gameEntity == null || gameEntity.getApk().isEmpty()) {
view.setBackgroundResource(R.drawable.game_item_btn_pause_style);
@ -267,6 +258,7 @@ public class BindingAdapters {
}
}
@BindingAdapter("liBaoBtn")
public static void setLiBaoBtn(TextView view, String status) {
if (TextUtils.isEmpty(status)) return;
switch (status) {
@ -331,6 +323,7 @@ public class BindingAdapters {
}
// 大图下的进度条
@BindingAdapter({"downloadButton", "traceEvent", "clickCallBack", "entrance", "location"})
public static void setDownloadButton(DownloadProgressBar progressBar,
GameEntity gameEntity,
ExposureEvent traceEvent,
@ -338,9 +331,6 @@ public class BindingAdapters {
@Nullable String entrance,
@Nullable String location) {
// 恢复DialogFragment
restoreDialogFragment(progressBar);
// 判断是否显示按钮
if (gameEntity != null
&& Config.isShowDownload(gameEntity.getId())
@ -368,95 +358,45 @@ public class BindingAdapters {
case PLUGIN:
if (gameEntity.getApk().size() == 1) {
ApkEntity apk = gameEntity.getApk().get(0);
DownloadEntity downloadEntity = SimulatorGameManager.findDownloadEntityByUrl(apk.getUrl());
if (gameEntity.getSimulator() != null) {
boolean isInstalled = PackageUtils.isInstalledFromAllPackage(v.getContext(), gameEntity.getSimulator().getApk().getPackageName());
if (downloadEntity != null && SimulatorGameManager.isSimulatorGame(gameEntity) && !isInstalled) {
SimulatorDownloadManager.getInstance().showDownloadDialog(v.getContext(), gameEntity.getSimulator(),
SimulatorDownloadManager.SimulatorLocation.LAUNCH, gameEntity.getId(), gameEntity.getName(), null);
return;
}
}
RealNameHelper.checkIfAuth(v.getContext(), gameEntity, () -> {
GamePermissionDialogFragment.show((AppCompatActivity) v.getContext(), gameEntity, gameEntity.getInfo(), () -> {
BrowserInstallHelper.showBrowserInstallHintDialog(v.getContext(), () -> {
PackageCheckDialogFragment.show((AppCompatActivity) v.getContext(), gameEntity, () -> {
DownloadDialogHelper.findAvailableDialogAndShow(v.getContext(), gameEntity, apk, () -> {
CertificationDialog.showCertificationDialog(v.getContext(), gameEntity, () -> {
DialogUtils.showVersionNumberDialog(v.getContext(), gameEntity, () -> {
DialogUtils.showOverseaDownloadDialog(v.getContext(), gameEntity, () -> {
DialogUtils.checkDownload(v.getContext(), apk.getSize(),
isSubscribe -> download(progressBar, gameEntity, traceEvent, isSubscribe, entrance, location));
});
});
});
});
});
DownloadDialogHelper.findAvailableDialogAndShow(
v.getContext(),
gameEntity,
apk,
() -> {
DialogUtils.checkDownload(v.getContext(), apk.getSize(),
isSubscribe -> download(progressBar, gameEntity, traceEvent, isSubscribe, entrance, location));
});
});
});
} else {
RealNameHelper.checkIfAuth(v.getContext(), gameEntity, () -> {
GamePermissionDialogFragment.show((AppCompatActivity) v.getContext(), gameEntity, gameEntity.getInfo(), () -> {
CertificationDialog.showCertificationDialog(v.getContext(), gameEntity, () -> {
DialogUtils.showVersionNumberDialog(v.getContext(), gameEntity, () -> {
DownloadDialog.showDownloadDialog(
v.getContext(),
gameEntity,
traceEvent,
entrance,
location + ":" + gameEntity.getName());
});
});
});
});
DownloadDialog.getInstance(v.getContext()).showPopupWindow(v, gameEntity,
entrance, location + gameEntity.getName(), traceEvent);
}
break;
case LAUNCH_OR_OPEN:
if (gameEntity.getApk().size() == 1) {
//启动模拟器游戏
if (SimulatorGameManager.isSimulatorGame(gameEntity)) {
DownloadEntity downloadEntity = SimulatorGameManager.findDownloadEntityByUrl(gameEntity.getApk().get(0).getUrl());
if (downloadEntity != null) {
File file = new File(downloadEntity.getPath());
if (!file.exists()) {
download(progressBar, gameEntity, traceEvent, false, entrance, location);
return;
}
SimulatorGameManager.launchSimulatorGame(downloadEntity, gameEntity);
}
return;
}
DataUtils.onGameLaunchEvent(v.getContext(), gameEntity.getName(), gameEntity.getApk().get(0).getPlatform(), location);
PackageUtils.launchApplicationByPackageName(v.getContext(), gameEntity.getApk().get(0).getPackageName());
} else {
DownloadDialog.showDownloadDialog(
v.getContext(),
gameEntity,
traceEvent,
entrance,
location + ":" + gameEntity.getName());
DownloadDialog.getInstance(v.getContext()).showPopupWindow(v, gameEntity,
entrance, location + gameEntity.getName(), traceEvent);
}
break;
case INSTALL_PLUGIN:
case INSTALL_NORMAL:
if (gameEntity.getApk().size() == 1) {
DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshotByUrl(gameEntity.getApk().get(0).getUrl());
DownloadEntity downloadEntity = DownloadManager.getInstance(progressBar.getContext()).getDownloadEntityByUrl(gameEntity.getApk().get(0).getUrl());
if (downloadEntity != null) {
PackageInstaller.install(v.getContext(), downloadEntity);
PackageUtils.launchSetup(v.getContext(), downloadEntity);
}
}
break;
case RESERVABLE:
RealNameHelper.checkIfAuth(v.getContext(), gameEntity, () -> {
GamePermissionDialogFragment.show((AppCompatActivity) v.getContext(), gameEntity, gameEntity.getInfo(), () -> {
CheckLoginUtils.checkLogin(progressBar.getContext(), "", () -> {
ReservationHelper.reserve(v.getContext(), gameEntity.getId(), () -> {
LogUtils.logReservation(gameEntity, traceEvent);
updateReservation(progressBar, gameEntity);
});
CheckLoginUtils.checkLogin(progressBar.getContext(), "", () -> {
PermissionHelper.checkReadPhoneStatePermissionBeforeAction(progressBar.getContext(), () -> {
ReserveDialogFragment dialogFragment = ReserveDialogFragment.getInstance(gameEntity, () -> {
LogUtils.logReservation(gameEntity, traceEvent);
updateReservation(progressBar, gameEntity);
});
dialogFragment.show(((AppCompatActivity) progressBar.getContext()).getSupportFragmentManager(), "reserve");
});
});
break;
@ -476,21 +416,10 @@ public class BindingAdapters {
}
break;
case H5_GAME:
LinkEntity linkEntity = gameEntity.getH5Link();
boolean isPlay = "play".equals(linkEntity.getType()); // 是否为开始玩
MtaHelper.onEvent("H5页面", "入口", "列表页_" + gameEntity.getName());
if (isPlay) {
HistoryHelper.insertGameEntity(gameEntity);
}
GamePermissionDialogFragment.show((AppCompatActivity) v.getContext(), gameEntity, gameEntity.getInfo(), () -> {
Intent i = new Intent(WebActivity.getIntentForWebGame(progressBar.getContext(), linkEntity.getLink(), gameEntity.getName(), isPlay, linkEntity.getCloseButton()));
progressBar.getContext().startActivity(i);
});
break;
case UPDATING:
Utils.toast(progressBar.getContext(), "正在加急更新版本,敬请后续留意");
LinkEntity linkEntity = gameEntity.getH5Link();
Intent i = new Intent(WebActivity.getIntentForWebGame(progressBar.getContext(), linkEntity.getLink(), gameEntity.getName(), "play".equals(linkEntity.getType())));
progressBar.getContext().startActivity(i);
break;
}
});
@ -521,16 +450,12 @@ public class BindingAdapters {
} else {
if (offStatus != null && "dialog".equals(offStatus)) {
progressBar.setText("查看");
progressBar.setDownloadType(DownloadProgressBar.DownloadType.NONE);
} else if ("updating".equals(offStatus)) {
progressBar.setText("更新中");
progressBar.setDownloadType(DownloadProgressBar.DownloadType.UPDATING);
} else {
progressBar.setText("暂无");
progressBar.setDownloadType(DownloadProgressBar.DownloadType.NONE);
}
progressBar.setDownloadType(DownloadProgressBar.DownloadType.NONE);
}
} else {
String status = GameUtils.getDownloadBtnText(progressBar.getContext(), gameEntity, PluginLocation.only_game);
switch (status) {
@ -550,7 +475,7 @@ public class BindingAdapters {
// 显示下载过程状态
if (gameEntity.getApk().size() == 1) {
DownloadEntity downloadEntity = DownloadManager.getInstance().getDownloadEntitySnapshotByUrl(gameEntity.getApk().get(0).getUrl());
DownloadEntity downloadEntity = DownloadManager.getInstance(progressBar.getContext()).getDownloadEntityByUrl(gameEntity.getApk().get(0).getUrl());
if (downloadEntity != null) {
progressBar.setProgress((int) (downloadEntity.getPercent() * 10));
switch (downloadEntity.getStatus()) {
@ -578,9 +503,6 @@ public class BindingAdapters {
case cancel:
case hijack:
case notfound:
case uncertificated:
case unqualified:
case unavailable:
break;
default:
break;
@ -589,35 +511,6 @@ public class BindingAdapters {
}
}
/**
* 当页面完全重建时若存在重建的DialogFragment则需要手动恢复该DialogFragment之前配置的回调(因为DialogFragment重建时只会从arguments中获取之前的配置内容
* 而arguments无法传递回调)或者dismiss该DialogFragment
*/
private static void restoreDialogFragment(DownloadProgressBar progressBar) {
GamePermissionDialogFragment gamePermissionDialogFragment =
((GamePermissionDialogFragment) ((AppCompatActivity) progressBar.getContext()).getSupportFragmentManager().findFragmentByTag(GamePermissionDialogFragment.class.getSimpleName()));
if (gamePermissionDialogFragment != null) {
gamePermissionDialogFragment.dismissAllowingStateLoss();
}
}
/*private static void download(DownloadProgressBar progressBar, GameEntity gameEntity, ExposureEvent traceEvent, @Nullable String entrance, @Nullable String location, View v) {
if (gameEntity.getApk().size() == 1) {
ApkEntity apk = gameEntity.getApk().get(0);
DownloadDialogHelper.findAvailableDialogAndShow(
v.getContext(),
gameEntity,
apk,
() -> {
DialogUtils.checkDownload(v.getContext(), apk.getSize(),
isSubscribe -> download(progressBar, gameEntity, traceEvent, isSubscribe, entrance, location));
});
} else {
DownloadDialog.getInstance(v.getContext()).showPopupWindow(v, gameEntity,
entrance, location + gameEntity.getName(), traceEvent);
}
}*/
private static void updateReservation(DownloadProgressBar progressBar, GameEntity gameEntity) {
// 显示预约
@ -653,7 +546,10 @@ public class BindingAdapters {
String msg = FileUtils.isCanDownload(progressBar.getContext(), apkEntity.getSize());
if (TextUtils.isEmpty(msg)) {
DataUtils.onGameDownloadEvent(progressBar.getContext(), gameEntity.getName(), apkEntity.getPlatform(), entrance, "下载开始", method);
ExposureUtils.DownloadType downloadType = ExposureUtils.getDownloadType(apkEntity, method);
ExposureEvent downloadExposureEvent = ExposureUtils.logADownloadExposureEvent(gameEntity, apkEntity.getPlatform(), traceEvent, downloadType);
DownloadManager.createDownload(progressBar.getContext(),
apkEntity,
gameEntity,
@ -661,7 +557,7 @@ public class BindingAdapters {
entrance,
location + gameEntity.getName(),
isSubscribe,
traceEvent);
downloadExposureEvent);
progressBar.setProgress(0);
progressBar.setDownloadType("插件化".equals(method) ?
@ -671,96 +567,49 @@ public class BindingAdapters {
}
}
public static void setGameLabelList(LinearLayout layout, List<TagStyleEntity> tagStyle) {
GameViewUtils.setLabelList(layout.getContext(), layout, tagStyle);
}
@BindingAdapter({"gameLabelList", "subjectTag"})
public static void setGameLabelList(LinearLayout layout, GameEntity gameEntity, String subjectTag) {
if (gameEntity == null) return;
if (gameEntity.getTest() != null) {
layout.removeAllViews();
View testView = LayoutInflater.from(layout.getContext()).inflate(R.layout.game_test_label, null);
TextView testType = testView.findViewById(R.id.test_type);
TextView testTime = testView.findViewById(R.id.test_time);
testType.setText(gameEntity.getTest().getType());
testType.setBackgroundColor(ContextCompat.getColor(layout.getContext(), R.color.tag_yellow));
// 包含测试开服标签
public static void setGameTags(LinearLayout layout, GameEntity gameEntity) {
try {
if (layout.getVisibility() == View.GONE) return;
ArrayList<TagStyleEntity> tagStyle = new ArrayList<>();
TestEntity test = gameEntity.getTest();
if (test != null
// 这个判断用于开测表列表
&& !"type_tag".equals(test.getGameTag())) {
if ("custom".equals(test.getGameTag())) {
TagStyleEntity typeTag = new TagStyleEntity();
if (!TextUtils.isEmpty(test.getText())) {
typeTag.setName(test.getText() != null ? test.getText() : "");
} else {
typeTag.setName(test.getType() != null ? test.getType() : "");
}
typeTag.setBackground("E8F3FF");
typeTag.setColor("1383EB");
tagStyle.add(typeTag);
} else {
TagStyleEntity typeTag = new TagStyleEntity();
typeTag.setName(test.getType() != null ? test.getType() : "");
typeTag.setBackground("FFF3E0");
typeTag.setColor("FA8500");
tagStyle.add(typeTag);
TagStyleEntity timeTag = new TagStyleEntity();
timeTag.setName(GameViewUtils.getGameTestDate(test.getStart()));
timeTag.setBackground("E0FFF9");
timeTag.setColor("00A887");
tagStyle.add(timeTag);
}
if (gameEntity.getTest().getStart() == 0) {
testTime.setVisibility(View.GONE);
} else {
tagStyle = gameEntity.getTagStyle();
testTime.setText(GameViewUtils.getGameTestDate(gameEntity.getTest().getStart()));
}
GameViewUtils.setLabelList(layout.getContext(), layout, tagStyle);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setVideoDetailGameTags(LinearLayout layout, GameEntity gameEntity) {
try {
ArrayList<TagStyleEntity> tagStyle = new ArrayList<>();
TestEntity test = gameEntity.getTest();
if (test != null
// 这个判断用于开测表列表
&& !"type_tag".equals(test.getGameTag())) {
TagStyleEntity typeTag = new TagStyleEntity();
typeTag.setName(test.getType() != null ? test.getType() : "");
typeTag.setBackground("FFF3E0");
typeTag.setColor("FA8500");
tagStyle.add(typeTag);
TagStyleEntity timeTag = new TagStyleEntity();
timeTag.setName(GameViewUtils.getGameTestDate(test.getStart()));
timeTag.setBackground("E0FFF9");
timeTag.setColor("00A887");
tagStyle.add(timeTag);
} else {
tagStyle = gameEntity.getTagStyle();
}
GameViewUtils.setLabelList(layout.getContext(), layout, tagStyle, 4);
} catch (Exception e) {
e.printStackTrace();
layout.addView(testView);
} else {
GameViewUtils.setLabelList(layout.getContext(), layout, gameEntity.getTag(), subjectTag, gameEntity.getTagStyle());
}
}
@BindingAdapter("isRefreshing")
public static void isRefreshing(SwipeRefreshLayout layout, LoadStatus status) {
if (status != LoadStatus.INIT_LOADING && status != LoadStatus.LIST_LOADING) {
layout.setRefreshing(false);
}
}
public static void setGameName(TextView view, GameEntity game, boolean isShowPlatform, @Nullable Boolean isShowSuffix) {
if (isShowSuffix == null) isShowSuffix = true; // 默认显示
@BindingAdapter({"setGameName", "isShowPlatform"})
public static void setGameName(TextView view, GameEntity game, boolean isShowPlatform) {
if (isShowPlatform && game.getApk().size() > 0) {
view.setText(String.format("%s - %s", !isShowSuffix ? game.getNameWithoutSuffix() : game.getName(),
view.setText(String.format("%s - %s", game.getName(),
PlatformUtils.getInstance(view.getContext()).getPlatformName(
game.getApk().get(0).getPlatform())));
} else {
view.setText(!isShowSuffix ? game.getNameWithoutSuffix() : game.getName());
view.setText(game.getName());
}
}
@BindingAdapter({"setCommunityImage", "setCommunityVideoImage"})
public static void setCommunityImage(SimpleDraweeView imageView, List<String> images, List<CommunityVideoEntity> videos) {
if (videos.size() > 0) {
CommunityVideoEntity videoEntity = videos.get(0);
@ -774,6 +623,7 @@ public class BindingAdapters {
}
}
@BindingAdapter({"setCommunityVideoDuration"})
public static void setCommunityVideoDuration(TextView mVideoDuration, List<CommunityVideoEntity> videos) {
if (videos != null && videos.size() > 0) {
CommunityVideoEntity videoEntity = videos.get(0);
@ -785,6 +635,7 @@ public class BindingAdapters {
}
}
@BindingAdapter({"setGameTags", "setMaxGameTags"})
public static void setGameTags(TextView view, List<TagStyleEntity> tags, int maxTags) {
if (tags == null) {
view.setText("");
@ -812,16 +663,4 @@ public class BindingAdapters {
}
view.setText(span);
}
public static void setVideoData(TextView view, int count) {
if (count > 0) {
view.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(view.getContext(), R.drawable.ic_video_data_up), null, null, null);
view.setTextColor(ContextCompat.getColor(view.getContext(), R.color.text_EA3333));
view.setText(count + "");
} else {
view.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
view.setTextColor(ContextCompat.getColor(view.getContext(), R.color.text_subtitleDesc));
view.setText("-");
}
}
}

View File

@ -1,94 +0,0 @@
package com.gh.common.dialog
import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.gh.base.fragment.BaseDialogFragment
import com.gh.common.util.DirectUtils
import com.gh.common.util.EntranceUtils
import com.gh.common.util.SpanBuilder
import com.gh.common.util.dip2px
import com.gh.common.view.CustomLinkMovementMethod
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.DialogApplyModeratorBinding
class ApplyModeratorDialogFragment : BaseDialogFragment() {
private lateinit var binding: DialogApplyModeratorBinding
private var mGroupNumber = ""
private var mGroupKey = ""
private var mParentTag = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireArguments().run {
mGroupNumber = getString(KEY_GROUP_NUMBER) ?: ""
mGroupKey = getString(KEY_GROUP_KEY) ?: ""
mParentTag = getString(EntranceUtils.KEY_PARENT_TAG) ?: ""
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = DialogApplyModeratorBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val startText = "版主考核群:"
val text = "$startText$mGroupNumber\n感谢你对论坛建设的支持\n请加入版主考核群并联系群主进行版主资格考核"
binding.desTv.text = SpanBuilder(text)
.click(startText.length, startText.length + mGroupNumber.length, R.color.theme_font,true) {
DirectUtils.directToQqGroup(
requireContext(),
mGroupKey
)
}
.build()
binding.desTv.movementMethod = CustomLinkMovementMethod.getInstance()
binding.confirmTv.setOnClickListener {
dismissAllowingStateLoss()
activity?.supportFragmentManager?.findFragmentByTag(mParentTag)
?.onActivityResult(REQUEST_CODE, Activity.RESULT_OK, null)
}
}
override fun onStart() {
super.onStart()
val width = requireContext().resources.displayMetrics.widthPixels - 60F.dip2px()
val height = ViewGroup.LayoutParams.WRAP_CONTENT
dialog?.window?.setLayout(width, height)
}
companion object {
const val KEY_GROUP_NUMBER = "group_number"
const val KEY_GROUP_KEY = "group_key"
const val REQUEST_CODE = 1103
@JvmStatic
fun show(
activity: AppCompatActivity,
number: String,
key: String,
tag: String
) {
ApplyModeratorDialogFragment().apply {
arguments = Bundle().apply {
putString(KEY_GROUP_NUMBER, number)
putString(KEY_GROUP_KEY, key)
putString(EntranceUtils.KEY_PARENT_TAG, tag)
}
}.show(
activity.supportFragmentManager,
ApplyModeratorDialogFragment::class.java.simpleName
)
}
}
}

View File

@ -1,95 +0,0 @@
package com.gh.common.dialog
import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.view.*
import com.gh.base.fragment.BaseDialogFragment
import com.gh.gamecenter.R
import com.halo.assistant.HaloApp
abstract class BaseDraggableDialogFragment : BaseDialogFragment(), View.OnTouchListener {
private var mInitPositionY = 0f
private lateinit var mGestureDetector: GestureDetector
private lateinit var mRootView: View
private lateinit var mDragCloseView: View
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mRootView = getRootView()
mDragCloseView = getDragCloseView()
mDragCloseView.setOnTouchListener(this)
mGestureDetector = GestureDetector(requireContext(), SingleTapConfirm())
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val createDialog = super.onCreateDialog(savedInstanceState)
createDialog.setCanceledOnTouchOutside(true)
val window = createDialog.window
window?.setGravity(Gravity.BOTTOM)
window?.setWindowAnimations(R.style.community_publication_animation)
return createDialog
}
// dialog drag animation
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View, event: MotionEvent): Boolean {
if (mGestureDetector.onTouchEvent(event) && mRootView.y == 0F) {
v.performClick()
return true
}
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mInitPositionY = mRootView.y - event.rawY
}
MotionEvent.ACTION_MOVE -> {
val offsetY = event.rawY + mInitPositionY
val dialogY = mRootView.y
if (dialogY + offsetY > 0) {
mRootView.animate()
.y(offsetY)
.setDuration(0)
.start()
} else {
resetDialogPosition()
}
}
MotionEvent.ACTION_CANCEL,
MotionEvent.ACTION_UP,
MotionEvent.ACTION_OUTSIDE -> {
if (mRootView.y >= mRootView.height / 2) {
dismissAllowingStateLoss()
} else {
resetDialogPosition(300)
}
}
else -> return false
}
return true
}
private fun resetDialogPosition(duration: Long = 0) {
mRootView.animate()
.y(0F)
.setDuration(duration)
.start()
}
private class SingleTapConfirm : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(event: MotionEvent): Boolean {
return true
}
}
override fun onStart() {
super.onStart()
val width = HaloApp.getInstance().application.resources.displayMetrics.widthPixels
val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
dialog?.window?.setLayout(width, height)
}
abstract fun getRootView(): View
abstract fun getDragCloseView(): View
override fun getThemeRes(): Int = R.style.DialogFragmentDimAmount
}

View File

@ -4,8 +4,6 @@ import android.content.DialogInterface
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.gh.common.util.MtaHelper
import com.lightgame.dialog.BaseDialogFragment
import java.util.concurrent.atomic.AtomicBoolean
@ -17,7 +15,6 @@ abstract class BaseTrackableDialogFragment : BaseDialogFragment() {
abstract fun getEvent(): String
abstract fun getKey(): String
open fun getValue(): String = ""
// 区分此 dialog 是点击 dialog 外部取消的还是点击返回取消的
private val mIsCanceledByClickOutsideOfDialog = AtomicBoolean(true)
@ -50,9 +47,6 @@ abstract class BaseTrackableDialogFragment : BaseDialogFragment() {
MtaHelper.onEventWithBasicDeviceInfo(getEvent(), getKey(), value)
} else {
MtaHelper.onEvent(getEvent(), getKey(), value)
if (getValue().isNotEmpty()) {
MtaHelper.onEvent(getEvent(), value, getValue())
}
}
}
@ -65,29 +59,4 @@ abstract class BaseTrackableDialogFragment : BaseDialogFragment() {
open fun trackWithBasicDeviceInfo() = false
override fun show(manager: FragmentManager, tag: String?) {
val fragment = manager.findFragmentByTag(tag)
if (fragment != null) {
val transaction = manager.beginTransaction()
transaction.show(fragment)
transaction.commit()
} else {
try {
val clazz: Class<*> = DialogFragment::class.java
val dismissed = clazz.getDeclaredField("mDismissed")
dismissed.isAccessible = true
dismissed[this] = false
val shownByMe = clazz.getDeclaredField("mShownByMe")
shownByMe.isAccessible = true
shownByMe[this] = true
val transaction = manager.beginTransaction()
transaction.add(this, tag)
transaction.commitAllowingStateLoss()
} catch (e: Exception) {
super.show(manager, tag)
e.printStackTrace()
}
}
}
}

View File

@ -1,193 +0,0 @@
package com.gh.common.dialog
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.gh.common.avoidcallback.AvoidOnResultManager
import com.gh.common.avoidcallback.Callback
import com.gh.common.constant.Constants
import com.gh.common.util.*
import com.gh.gamecenter.R
import com.gh.gamecenter.ShellActivity
import com.gh.gamecenter.entity.AuthDialogEntity
import com.gh.gamecenter.entity.AuthDialogLevel
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.manager.UserManager
import com.google.gson.reflect.TypeToken
import com.halo.assistant.fragment.user.UserInfoEditFragment
import com.lightgame.utils.AppManager
class CertificationDialog(context: Context, private val authDialogEntity: AuthDialogEntity, val gameId: String, val listener: DialogUtils.ConfirmListener) :
Dialog(context, R.style.GhAlertDialog) {
private lateinit var view: View
private lateinit var detailedDesTv: TextView
private lateinit var noRemindAgainCb: CheckBox
private lateinit var actionLeftTv: TextView
private lateinit var actionRightTv: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
view = LayoutInflater.from(context).inflate(R.layout.dialog_sertification, null)
setContentView(view)
detailedDesTv = view.findViewById(R.id.detailedDesTv)
noRemindAgainCb = view.findViewById(R.id.noRemindAgainCb)
actionLeftTv = view.findViewById(R.id.actionLeftTv)
actionRightTv = view.findViewById(R.id.actionRightTv)
detailedDesTv.paint.flags = Paint.UNDERLINE_TEXT_FLAG
detailedDesTv.paint.isAntiAlias = true
detailedDesTv.setOnClickListener {
DirectUtils.directToWebView(context, authDialogEntity.link)
}
when (authDialogEntity.level) {
AuthDialogLevel.MUST_PASS.value -> {
actionLeftTv.text = "暂不下载"
actionRightTv.text = "去实名认证"
noRemindAgainCb.visibility = View.GONE
actionLeftTv.setOnClickListener {
dismiss()
}
actionRightTv.setOnClickListener {
if (UserManager.getInstance().isLoggedIn) {
gotoAuthPage()
} else {
gotoLoginPage()
}
}
}
AuthDialogLevel.ALWAYS_HINT.value -> {
actionLeftTv.text = "去实名认证"
actionRightTv.text = "继续下载"
noRemindAgainCb.visibility = View.GONE
actionLeftTv.setOnClickListener {
if (UserManager.getInstance().isLoggedIn) {
gotoAuthPage()
} else {
gotoLoginPage()
}
}
actionRightTv.setOnClickListener {
listener.onConfirm()
dismiss()
}
}
AuthDialogLevel.OPTIONAL_HINT.value -> {
actionLeftTv.text = "去实名认证"
actionRightTv.text = "继续下载"
noRemindAgainCb.visibility = View.VISIBLE
actionLeftTv.setOnClickListener {
if (noRemindAgainCb.isChecked) {
SPUtils.setBoolean(gameId, true)
}
if (UserManager.getInstance().isLoggedIn) {
gotoAuthPage()
} else {
gotoLoginPage()
}
}
actionRightTv.setOnClickListener {
if (noRemindAgainCb.isChecked) {
SPUtils.getBoolean(gameId, true)
}
listener.onConfirm()
dismiss()
}
}
}
}
//跳转登录页面
private fun gotoLoginPage() {
val currentActivity = AppManager.getInstance().currentActivity() ?: return
CheckLoginUtils.checkLogin(currentActivity as AppCompatActivity,
null, true, "实名认证弹窗") {
if (UserManager.getInstance().isAuth) {
listener.onConfirm()
dismiss()
}
}
}
//跳转实名认证页面
private fun gotoAuthPage() {
val currentActivity = AppManager.getInstance().currentActivity() ?: return
AvoidOnResultManager.getInstance(currentActivity as AppCompatActivity)
.startForResult(
ShellActivity.getIntent(
context,
ShellActivity.Type.REAL_NAME_INFO,
).apply {
putExtra(EntranceUtils.KEY_GAME_ID, gameId)
}, object : Callback {
override fun onActivityResult(resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && data != null) {
val isAuthSuccess =
data.getBooleanExtra(UserInfoEditFragment.AUTH_SUCCESS, false)
if (isAuthSuccess) {
listener.onConfirm()
dismiss()
}
}
}
})
}
companion object {
@JvmStatic
fun showCertificationDialog(context: Context, game: GameEntity, listener: DialogUtils.ConfirmListener) {
//1.先判断是否登录 是执行2 否执行3
//2.判断是否实名认证 是终止 否执行3
//3.判断是否需要弹出认证弹窗接口
if (UserManager.getInstance().isLoggedIn) {
if (UserManager.getInstance().isAuth) {//已实名认证
listener.onConfirm()
} else {
authDialog(context, game, listener)
}
} else {
authDialog(context, game, listener)
}
}
@SuppressLint("CheckResult")
private fun authDialog(context: Context, game: GameEntity, listener: DialogUtils.ConfirmListener) {
var authDialog: AuthDialogEntity? = null
if (game.authDialog != null) {
authDialog = game.authDialog
}
if (authDialog == null) {
val datas = SPUtils.getString(Constants.SP_AUTH_DIALOG)
val type = object : TypeToken<List<AuthDialogEntity>>() {}.type
val authDialogs = GsonUtils.gson.fromJson<List<AuthDialogEntity>>(datas, type)
if (!authDialogs.isNullOrEmpty()) {
authDialog = authDialogs.find { it.gameCategory == game.category }
}
}
val isCloseAuthDialog = SPUtils.getBoolean(game.id, false)
if (authDialog != null && (authDialog.level != AuthDialogLevel.OPTIONAL_HINT.value || !isCloseAuthDialog)) {
val dialog = CertificationDialog(context, authDialog, game.id, listener)
dialog.show()
} else {
listener.onConfirm()
}
}
}
}

View File

@ -1,242 +0,0 @@
package com.gh.common.dialog
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.preference.PreferenceManager
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.common.constant.Constants
import com.gh.common.util.*
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.DialogDeviceRemindBinding
import com.gh.gamecenter.entity.DeviceDialogEntity
import com.gh.gamecenter.entity.GameEntity
import com.google.gson.reflect.TypeToken
import com.gh.gamecenter.setting.GameDownloadSettingFragment.Companion.AUTO_INSTALL_SP_KEY
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus
import io.reactivex.disposables.Disposable
import java.lang.ref.WeakReference
/**
* 设备提醒弹窗
*/
class DeviceRemindDialog(context: Context, val entity: DeviceDialogEntity, val gameEntity: GameEntity) : Dialog(context, R.style.GhAlertDialog) {
private val mBinding: DialogDeviceRemindBinding by lazy { DialogDeviceRemindBinding.inflate(layoutInflater) }
private var currentPage = 0
private var mSlideLooperInterval = 3000L
private lateinit var mLooperHandle: LooperHandle
private lateinit var mAdapter: BannerAdapter
private var mDatas: ArrayList<String> = ArrayList()
private val mSlideLooperKey = 100
private var disposable: Disposable? = null
private val dataWatcher = object : DataWatcher() {
override fun onDataChanged(downloadEntity: DownloadEntity) {
if (downloadEntity.status == DownloadStatus.done && downloadEntity.name == gameEntity.name) {
val sp = PreferenceManager.getDefaultSharedPreferences(getContext())
val autoInstall = sp.getBoolean(AUTO_INSTALL_SP_KEY, true)
if (autoInstall) {
dismiss()
}
}
}
}
companion object {
fun showDeviceRemindDialog(context: Context, gameEntity: GameEntity) {
val datas = SPUtils.getString(Constants.SP_DEVICE_REMIND)
if (datas.isNotEmpty()) {
val pair = shouldShowDeviceRemindDialog(gameEntity)
if (pair.first) {
val dialog = DeviceRemindDialog(context, pair.second!!, gameEntity)
dialog.show()
}
}
}
fun shouldShowDeviceRemindDialog(gameEntity: GameEntity): Pair<Boolean, DeviceDialogEntity?> {
val datas = SPUtils.getString(Constants.SP_DEVICE_REMIND)
if (datas.isNotEmpty()) {
val type = object : TypeToken<List<DeviceDialogEntity>>() {}.type
val entities = GsonUtils.gson.fromJson<List<DeviceDialogEntity>>(datas, type)
//1.判断设备是否匹配
val entity = entities.find { it.manufacturer.toLowerCase().startsWith(Build.MANUFACTURER.toLowerCase()) }
?: return Pair(false, null)
//2.判断游戏不含剔除标签
gameEntity.tagStyle.forEach {
if (entity.excludeTags.contains(it.name)) {
return Pair(false, null)
}
}
//3.不再弹出提示判断
val isNoRemindAgain = SPUtils.getBoolean(Constants.SP_NO_REMIND_AGAIN, false)
if (isNoRemindAgain) return Pair(false, null)
return Pair(true, entity)
}
return Pair(false, null)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setContentView(mBinding.root)
mDatas.addAll(entity.gallery)
mBinding.titleTv.text = entity.title
mBinding.contentTv.text = entity.content
mBinding.bannerView.apply {
orientation = ViewPager2.ORIENTATION_HORIZONTAL
mAdapter = BannerAdapter()
val recyclerView = getChildAt(0) as RecyclerView
recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER
registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
currentPage = position
slideIndicator(currentPage % mDatas.size)
}
})
recyclerView.addOnItemTouchListener(object : RecyclerView.SimpleOnItemTouchListener() {
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
val isStop = e.action == MotionEvent.ACTION_DOWN || e.action == MotionEvent.ACTION_MOVE
if (isStop) mAdapter.stopScroll() else mAdapter.startScroll()
return false
}
})
adapter = mAdapter
mLooperHandle = LooperHandle(mAdapter)
currentPage = (adapter as BannerAdapter).getActualFirstPositionInCenter()
setCurrentItem(currentPage, false)
if (mDatas.size > 1) {
addIndicator()
slideIndicator(currentPage % mDatas.size)
autoPlay()
}
}
val isFirst = SPUtils.getBoolean(Constants.SP_FIRST_DEVICE_REMIND, false)
if (!isFirst) {
mBinding.cancelTv.isEnabled = false
mBinding.cancelTv.background = ContextCompat.getDrawable(context, R.drawable.button_round_f5f5f5)
disposable = countDownTimer(3) { finish, time ->
if (finish) {
mBinding.cancelTv.isEnabled = true
mBinding.cancelTv.background = ContextCompat.getDrawable(context, R.drawable.button_blue_oval)
mBinding.cancelTv.text = "我知道了"
mBinding.cancelTv.setTextColor(ContextCompat.getColor(context, R.color.white))
} else {
mBinding.cancelTv.text = "我知道了(${time}S)"
}
}
SPUtils.setBoolean(Constants.SP_FIRST_DEVICE_REMIND, true)
} else {
mBinding.noRemindAgainCb.visibility = View.VISIBLE
mBinding.cancelTv.text = "我知道了"
mBinding.cancelTv.isEnabled = true
mBinding.cancelTv.setTextColor(ContextCompat.getColor(context, R.color.white))
mBinding.cancelTv.background = ContextCompat.getDrawable(context, R.drawable.button_blue_oval)
}
mBinding.cancelTv.setOnClickListener {
SPUtils.setBoolean(Constants.SP_NO_REMIND_AGAIN, mBinding.noRemindAgainCb.isChecked)
dismiss()
}
DownloadManager.getInstance().addObserver(dataWatcher)
}
private fun addIndicator() {
mBinding.indicatorLl.removeAllViews()
mDatas.forEach { _ ->
val indicatorView = ImageView(context).apply {
setImageResource(R.drawable.selector_device_remind_indicator)
val params = LinearLayout.LayoutParams(DisplayUtils.dip2px(8F), LinearLayout.LayoutParams.WRAP_CONTENT)
params.leftMargin = DisplayUtils.dip2px(1F)
params.rightMargin = DisplayUtils.dip2px(1F)
layoutParams = params
}
mBinding.indicatorLl.addView(indicatorView)
}
}
private fun slideIndicator(position: Int) {
for (i in 0 until mBinding.indicatorLl.childCount) {
val childAt = mBinding.indicatorLl.getChildAt(i)
childAt.isSelected = i == position
}
}
private fun autoPlay() {
mAdapter.startScroll()
}
inner class BannerAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return object : RecyclerView.ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_device_remind_banner, parent, false)) {}
}
override fun getItemCount(): Int = if (mDatas.size == 1) mDatas.size else Int.MAX_VALUE
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val data = mDatas[position % mDatas.size]
val view = holder.itemView as SimpleDraweeView
ImageUtils.display(view, data)
}
fun getActualFirstPositionInCenter(): Int {
if (mDatas.size == 1) return 0
var index = itemCount / 2
if (index % mDatas.size != 0) {
index -= (index % mDatas.size)
}
return index
}
fun scrollToNextPage() {
currentPage++
mBinding.bannerView.setCurrentItem(currentPage, true)
}
fun startScroll() {
mLooperHandle.removeMessages(mSlideLooperKey)
mLooperHandle.sendEmptyMessageDelayed(mSlideLooperKey, mSlideLooperInterval)
}
fun stopScroll() {
mLooperHandle.removeMessages(mSlideLooperKey)
}
}
class LooperHandle(val mAdapter: BannerAdapter) : Handler() {
private val mWeakReference: WeakReference<BannerAdapter> = WeakReference(mAdapter)
override fun handleMessage(msg: Message) {
val adapter = mWeakReference.get()
adapter?.scrollToNextPage()
adapter?.startScroll()
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
if (disposable != null && !disposable!!.isDisposed) {
disposable!!.dispose()
disposable = null
}
DownloadManager.getInstance().removeObserver(dataWatcher)
}
}

View File

@ -1,6 +1,5 @@
package com.gh.common.dialog
import android.app.Dialog
import android.graphics.Paint
import android.os.Bundle
import android.util.TypedValue
@ -9,91 +8,62 @@ import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.text.HtmlCompat
import com.gh.base.fragment.BaseDialogFragment
import com.gh.common.util.DirectUtils
import com.gh.common.util.dip2px
import com.gh.common.util.toColor
import com.gh.common.util.DisplayUtils
import com.gh.common.util.MtaHelper
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.DialogGameOffServiceBinding
import com.gh.gamecenter.entity.GameEntity
import kotlinx.android.synthetic.main.dialog_game_off_service.*
// 游戏关闭下载弹窗
class GameOffServiceDialogFragment
// : BaseTrackableDialogFragment()
: BaseDialogFragment() {
class GameOffServiceDialogFragment : BaseTrackableDialogFragment() {
private var mDialog: GameEntity.Dialog? = null
private var mBinding: DialogGameOffServiceBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mDialog = requireArguments().getParcelable(KEY_DIALOG)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return DialogGameOffServiceBinding
.inflate(inflater)
.apply { mBinding = this }
.root
return inflater.inflate(R.layout.dialog_game_off_service, null)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mBinding?.run {
mDialog?.run {
titleTv.text = title
contentTv.text = HtmlCompat.fromHtml(content, HtmlCompat.FROM_HTML_MODE_LEGACY)
okTv.setOnClickListener {
dismissAllowingStateLoss()
mDialog?.run {
titleTv.text = title
contentTv.text = HtmlCompat.fromHtml(content, HtmlCompat.FROM_HTML_MODE_LEGACY)
for (site in sites) {
val siteTv = TextView(context)
siteTv.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
topMargin = DisplayUtils.dip2px(12f)
}
siteTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
siteTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.theme))
siteTv.text = site.text
siteTv.paintFlags = siteTv.paintFlags or Paint.UNDERLINE_TEXT_FLAG
siteTv.setOnClickListener {
MtaHelper.onEvent("游戏下载状态按钮", getKey(), site.text)
DirectUtils.directToWebView(requireContext(), site.url, "(关闭下载弹窗)")
dismiss()
}
// 过滤内容为空的元素
val notEmptySite = sites.filter { it.text.isNotBlank() }
notEmptySite.forEachIndexed { index, site ->
val siteTv = TextView(context)
siteTv.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
topMargin = 24F.dip2px()
if (index == notEmptySite.size - 1) bottomMargin = 8F.dip2px()
}
siteTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14F)
siteTv.setTextColor(R.color.theme_font.toColor())
siteTv.text = site.text
siteTv.paintFlags = siteTv.paintFlags or Paint.UNDERLINE_TEXT_FLAG
siteTv.setOnClickListener {
// MtaHelper.onEvent("游戏下载状态按钮", getKey(), site.text)
DirectUtils.directToWebView(requireContext(), site.url, "(关闭下载弹窗)")
dismissAllowingStateLoss()
}
container.addView(siteTv)
}
container.addView(siteTv)
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState).apply { setCanceledOnTouchOutside(true) }
override fun getEvent(): String {
return "游戏下载状态按钮"
}
// override fun getEvent(): String {
// return "游戏下载状态按钮"
// }
//
// override fun getKey(): String {
// return "查看详情弹窗"
// }
override fun getKey(): String {
return "查看详情弹窗"
}
companion object {
const val KEY_DIALOG = "dialog"
@JvmStatic
fun getInstance(dialog: GameEntity.Dialog) = GameOffServiceDialogFragment().apply {
arguments = Bundle().apply {
putParcelable(KEY_DIALOG, dialog)
}
mDialog = dialog
}
}

View File

@ -1,138 +0,0 @@
package com.gh.common.dialog
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentTransaction
import com.airbnb.lottie.LottieAnimationView
import com.gh.common.constant.Config
import com.gh.common.constant.Constants
import com.gh.common.util.*
import com.gh.common.util.PermissionHelper.INSTALL_PERMISSION_CODE
import com.gh.common.xapk.XapkInstaller
import com.gh.gamecenter.R
import com.lightgame.download.DownloadEntity
import com.lightgame.utils.Utils
import kotlin.random.Random
class InstallPermissionDialogFragment : BaseTrackableDialogFragment() {
lateinit var mView: View
var isXapk = false
var url: String = ""
var mCallBack: ((isFromPermissionGrantedCallback: Boolean) -> Unit)? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mView = inflater.inflate(R.layout.dialog_install_permission, null, false)
return mView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val closeTv = mView.findViewById<TextView>(R.id.closeTv)
val closeIv = mView.findViewById<ImageView>(R.id.closeIv)
val activateTv = mView.findViewById<TextView>(R.id.activateTv)
val contentTv = mView.findViewById<TextView>(R.id.contentTv)
val switchLottie = mView.findViewById<LottieAnimationView>(R.id.switchLottie)
contentTv.text = if (isXapk) "未授权下解压XAPK可能导致解压失败" else "以保证游戏的安装和更新"
switchLottie.setAnimation("lottie/install_permission_switch.json")
switchLottie.playAnimation()
val randomNumber = if (isXapk) 1 else Random.nextInt(2)
closeTv.goneIf(randomNumber == 0)
closeIv.goneIf(randomNumber != 0)
if (isXapk) {
closeTv.text = "暂不,尝试解压"
closeIv.visibility = View.VISIBLE
}
closeTv.setOnClickListener {
MtaHelper.onEvent(getEvent(), getKey(), "文案样式_点击以后再说")
if (isXapk) {
mCallBack?.invoke(false)
}
dismiss()
}
closeIv.setOnClickListener {
MtaHelper.onEvent(getEvent(), getKey(), "图标样式_点击关闭")
dismiss()
}
activateTv.setOnClickListener {
MtaHelper.onEvent(getEvent(), getKey(), if (randomNumber == 0) "文案样式_点击立即开启" else "图标样式_点击立即开启")
PermissionHelper.toInstallPermissionSetting(requireActivity())
if (isXapk) {
SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, requireActivity().javaClass.name)
SPUtils.setString(Constants.SP_XAPK_URL, url)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == INSTALL_PERMISSION_CODE) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
SPUtils.setString(Constants.SP_XAPK_UNZIP_ACTIVITY, "")
SPUtils.setString(Constants.SP_XAPK_URL, "")
}
mCallBack?.invoke(true)
dismiss()
}
}
override fun getEvent(): String = "安装引导弹窗"
override fun getKey(): String = "引导弹窗"
companion object {
@JvmStatic
fun show(activity: AppCompatActivity, downloadEntity: DownloadEntity, callBack: ((isFromPermissionGrantedCallback: Boolean) -> Unit)?) {
val isXapk = XapkInstaller.XAPK_EXTENSION_NAME == downloadEntity.path.getExtension()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
callBack?.invoke(false)
return
}
val haveInstallPermission = activity.packageManager.canRequestPackageInstalls()
if (haveInstallPermission) {
callBack?.invoke(false)
return
}
if (isXapk) {
val xapkUnzipVersions = Config.getSettings()?.permissionPopupAppliedVersions?.xapkUnzip
if (xapkUnzipVersions?.contains(Build.VERSION.SDK_INT.toString()) == false) {
callBack?.invoke(false)
return
}
} else {
val installVersions = Config.getSettings()?.permissionPopupAppliedVersions?.install
if (installVersions?.contains(Build.VERSION.SDK_INT.toString()) == false) {
callBack?.invoke(false)
return
}
}
var installPermissionDialogFragment = activity.supportFragmentManager.findFragmentByTag(InstallPermissionDialogFragment::class.java.simpleName) as? InstallPermissionDialogFragment
if (installPermissionDialogFragment != null) {
installPermissionDialogFragment.mCallBack = callBack
installPermissionDialogFragment.isXapk = isXapk
installPermissionDialogFragment.url = downloadEntity.url
val transaction: FragmentTransaction = activity.supportFragmentManager.beginTransaction()
transaction.show(installPermissionDialogFragment)
transaction.commit()
} else {
installPermissionDialogFragment = InstallPermissionDialogFragment().apply {
this.mCallBack = callBack
this.isXapk = isXapk
this.url = downloadEntity.url
}
installPermissionDialogFragment.show(activity.supportFragmentManager, InstallPermissionDialogFragment::class.java.simpleName)
}
}
}
}

View File

@ -1,39 +1,32 @@
package com.gh.common.dialog
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.gh.common.util.GsonUtils
import android.widget.LinearLayout
import android.widget.TextView
import com.gh.common.util.DisplayUtils
import com.gh.common.util.MtaHelper
import com.gh.common.util.PermissionHelper
import com.gh.common.util.fromHtml
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.DialogNotificationHintBinding
import com.gh.gamecenter.entity.NotificationStyleEntity
import com.gh.gamecenter.entity.NotificationUgc
import com.lightgame.utils.Utils
import org.json.JSONArray
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import kotlin.random.Random
import com.gh.gamecenter.entity.NotificationHint
import kotlinx.android.synthetic.main.dialog_notification_hint.*
// 通知权限弹窗
class NotificationHintDialogFragment : BaseTrackableDialogFragment() {
private var mNotificationUgc: NotificationUgc? = null
private val mBinding: DialogNotificationHintBinding by lazy { DialogNotificationHintBinding.inflate(layoutInflater) }
private var mNotificationHint: NotificationHint? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return mBinding.root
return inflater.inflate(R.layout.dialog_notification_hint, null)
}
@Suppress("DEPRECATION")
@ -41,56 +34,38 @@ class NotificationHintDialogFragment : BaseTrackableDialogFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val jsonString = getJsonFromAssets()
if (jsonString.isNullOrEmpty()) {
Utils.log("Failed to obtain configuration file")
return
titleTv.text = mNotificationHint?.title
contentContainer.removeAllViews()
for (item in mNotificationHint?.content!!) {
val tv = TextView(context)
tv.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
topMargin = if (contentContainer.childCount == 0) 0 else DisplayUtils.dip2px(12f)
}
tv.text = item
tv.setTextColor(Color.parseColor("#1383EB"))
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
contentContainer.addView(tv)
}
val index = Random.nextInt(2)
val jsonArray = JSONArray(jsonString)
val jsonObj = jsonArray.getJSONObject(index)
if (!jsonObj.has(mNotificationUgc?.value)) {
Utils.log("ugc type error")
return
}
val styleEntityJson = jsonObj.getJSONObject(mNotificationUgc!!.value)
val styleEntity = GsonUtils.fromJson(styleEntityJson.toString(), NotificationStyleEntity::class.java)
val drawableId = resources.getIdentifier(styleEntity.image, "drawable", requireContext().packageName)
mBinding.run {
notificationIv.setImageDrawable(ContextCompat.getDrawable(requireContext(), drawableId))
notificationTitle.text = styleEntity.title
notificationContent.text = styleEntity.content.fromHtml()
if (index == 0) {
closeIv.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_notification_close_1))
activateTv.setOnClickListener {
MtaHelper.onEventWithBasicDeviceInfo(getEvent(), getKey(), "点击立即开启")
dismiss()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//这种方案适用于 API 26, 即8.0含8.0)以上可以用
val intent = Intent()
intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID)
startActivity(intent)
} else {
activateTv.background = ContextCompat.getDrawable(requireContext(), R.drawable.bg_notification_open_btn_style_1)
activateTv.text = "优雅的开启"
PermissionHelper.toPermissionSetting(requireActivity())
}
}
activateTv.setOnClickListener {
MtaHelper.onEventWithBasicDeviceInfo(getEvent(), getKey(), "点击立即开启")
MtaHelper.onEventWithBasicDeviceInfo(getEvent(), getKey(), "${styleEntity.scenes}_${styleEntity.styleNo}_点击立即开启")
dismissAllowingStateLoss()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//这种方案适用于 API 26, 即8.0含8.0)以上可以用
val intent = Intent()
intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID)
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
PermissionHelper.toPermissionSetting(requireActivity())
}
} else {
PermissionHelper.toPermissionSetting(requireActivity())
}
}
closeIv.setOnClickListener {
dismissAllowingStateLoss()
MtaHelper.onEventWithBasicDeviceInfo(getEvent(), getKey(), "点击关闭")
MtaHelper.onEventWithBasicDeviceInfo(getEvent(), getKey(), "${styleEntity.scenes}_${styleEntity.styleNo}_点击关闭")
}
laterTv.setOnClickListener {
dismiss()
MtaHelper.onEventWithBasicDeviceInfo(getEvent(), getKey(), "点击以后再说")
}
dialog?.setCanceledOnTouchOutside(true)
@ -106,30 +81,10 @@ class NotificationHintDialogFragment : BaseTrackableDialogFragment() {
override fun trackWithBasicDeviceInfo() = true
private fun getJsonFromAssets(): String? {
val stringBuilder = StringBuilder()
var bufferedReader: BufferedReader? = null
var inputStreamReader: InputStreamReader? = null
try {
inputStreamReader = InputStreamReader(requireContext().assets.open("notification_style.json"))
bufferedReader = BufferedReader(inputStreamReader)
var line: String?
while (bufferedReader.readLine().also { line = it } != null) {
stringBuilder.append(line)
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
inputStreamReader?.close()
bufferedReader?.close()
}
return stringBuilder.toString()
}
companion object {
@JvmStatic
fun getInstance(ugc: NotificationUgc) = NotificationHintDialogFragment().apply {
mNotificationUgc = ugc
fun getInstance(hint: NotificationHint) = NotificationHintDialogFragment().apply {
mNotificationHint = hint
}
}
}

View File

@ -1,388 +0,0 @@
package com.gh.common.dialog
import android.animation.ValueAnimator
import android.content.Context
import android.content.pm.PackageInfo
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.base.BaseRecyclerViewHolder
import com.gh.common.constant.Constants
import com.gh.common.util.*
import com.gh.common.view.CustomLinkMovementMethod
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.FragmentPackageCheckBinding
import com.gh.gamecenter.databinding.PackageCheckItemBinding
import com.gh.gamecenter.entity.DetectionObjectEntity
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.entity.LinkEntity
import com.gh.gamecenter.entity.PackageDialogEntity
import com.gh.gamecenter.eventbus.EBPackage
import com.halo.assistant.HaloApp
import com.lightgame.adapter.BaseRecyclerAdapter
import com.lightgame.dialog.BaseDialogFragment
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
/**
* 包名检测弹窗
*/
// TODO 将 gameEntity 放到 argument 里再取出,避免重建时为空
class PackageCheckDialogFragment : BaseDialogFragment() {
private lateinit var binding: FragmentPackageCheckBinding
private var mTotalWidth = 0f
private val mDuration = 3000
private var mDisposable: Disposable? = null
private var mAdapter: PackageCheckAdapter? = null
private var mAllInstalledPackages = PackageUtils.getInstalledPackages(HaloApp.getInstance().application, 0)
var gameEntity: GameEntity? = null
var callBack: DialogUtils.ConfirmListener? = null
private val dataWatcher = object : DataWatcher() {
override fun onDataChanged(downloadEntity: DownloadEntity) {
val packageName = downloadEntity.packageName
val detectionObjects = gameEntity?.packageDialog?.detectionObjects
if (DownloadStatus.add == downloadEntity.status || DownloadStatus.done == downloadEntity.status) {
detectionObjects?.forEach { detectionObject ->
if (detectionObject.packages.contains(packageName)) {
val packageLink = gameEntity?.packageDialog?.links?.find { it.buttonLink }
LogUtils.uploadPackageCheck(
"pkg_check_pop_download", if (DownloadStatus.add == downloadEntity.status) "下载开始" else "下载完成",
gameEntity, packageLink?.text ?: "", packageLink?.title
?: "", downloadEntity.gameId, downloadEntity.getMetaExtra(Constants.GAME_NAME)
)
}
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
EventBus.getDefault().register(this)
gameEntity?.let {
LogUtils.uploadPackageCheck("pkg_check_pop_click", "出现弹窗", it, "", "", "", "")
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentPackageCheckBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
gameEntity?.packageDialog?.let {
changeParams(it.detectionObjects.size)
binding.packageRv.layoutManager = LinearLayoutManager(requireContext())
mAdapter = PackageCheckAdapter(requireContext(), it.detectionObjects)
binding.packageRv.adapter = mAdapter
binding.titleTv.text = it.title
binding.contentTv.text = it.content
val spanBuilder = SpanBuilder(it.linkHintText).build()
it.links.forEachIndexed { index, link ->
val linkSpan = SpanBuilder(link.title ?: "").click(
0, (link.title
?: "").length, R.color.theme_font, true
) {
LogUtils.uploadPackageCheck("pkg_check_pop_click", "点击链接", gameEntity, link.text, link.title, "", "")
DirectUtils.directToLinkPage(requireContext(), link, "包名检测弹窗", "")
}.build()
spanBuilder.append(linkSpan)
if (index != it.links.size - 1) {
spanBuilder.append("")
}
}
binding.linkHintTv.text = spanBuilder
binding.linkHintTv.movementMethod = CustomLinkMovementMethod.getInstance()
when (it.level) {
"HINT_SKIP" -> {
binding.cancelTv.text = "取消"
binding.noRemindAgainCb.visibility = View.GONE
}
"ALWAYS_HINT" -> {
binding.cancelTv.text = "我知道了"
binding.noRemindAgainCb.visibility = View.GONE
}
"OPTIONAL_CURRENT_HINT" -> {
binding.cancelTv.text = "我知道了"
binding.noRemindAgainCb.visibility = View.VISIBLE
}
else -> {
binding.cancelTv.text = "我知道了"
binding.noRemindAgainCb.visibility = View.VISIBLE
}
}
initListener(it)
}
binding.root.post {
checkPackage()
}
}
private fun changeParams(size: Int) {
val params = binding.packageRv.layoutParams as LinearLayout.LayoutParams
params.height = if (size > 3) (28f.dip2px() * 3.5).toInt() else 28f.dip2px() * size
binding.packageRv.layoutParams = params
}
private fun initListener(entity: PackageDialogEntity) {
binding.downloadBtn.setOnClickListener {
if (binding.noRemindAgainCb.isChecked) {
saveRecord(entity)
}
val isAllPackageInstalled = isAllPackageInstalled(mAllInstalledPackages, entity)
if (isAllPackageInstalled) {
callBack?.onConfirm()
dismissAllowingStateLoss()
} else {
var packageLink = getNotInstalledLink(entity)
if (packageLink == null) {
packageLink = entity.links.find { it.buttonLink }
}
if (packageLink != null) {
LogUtils.uploadPackageCheck("pkg_check_pop_click", "点击前往下载", gameEntity, packageLink.text, packageLink.title, "", "")
DirectUtils.directToLinkPage(requireContext(), packageLink, "包名检测弹窗", "")
}
}
}
binding.cancelTv.setOnClickListener {
if (entity.level != "HINT_SKIP") {
callBack?.onConfirm()
}
if (binding.noRemindAgainCb.isChecked) {
saveRecord(entity)
LogUtils.uploadPackageCheck("pkg_check_pop_click", "不再提示", gameEntity, "", "", "", "")
}
dismissAllowingStateLoss()
}
}
private fun saveRecord(entity: PackageDialogEntity) {
if (entity.level == "OPTIONAL_CURRENT_HINT") {
SPUtils.setBoolean("${Constants.SP_PACKAGE_CHECK}:${gameEntity?.id}", true)
} else {
SPUtils.setBoolean("${Constants.SP_PACKAGE_CHECK}:${gameEntity?.packageDialog?.id}", true)
}
}
private fun checkPackage() {
var index = 0
mTotalWidth = (DisplayUtils.getScreenWidth() - 108f.dip2px()).toFloat()
mDisposable = rxTimer(1) {
gameEntity?.packageDialog?.detectionObjects?.let { objects ->
if (objects.isNotEmpty()) {
val averageTime = if (objects.size == 1) {
mDuration
} else {
mDuration / objects.size
}
if (it != 0L && it % averageTime == 0L && index < objects.size) {
mAdapter?.notifyPackages()
binding.packageRv.smoothScrollToPosition(index)
index++
}
}
}
if (it >= mDuration) {
mDisposable?.dispose()
binding.downloadBtn.isEnabled = true
binding.downloadBtn.background = R.drawable.bg_notification_open_btn_style_2.toDrawable()
}
}
val animator = ValueAnimator.ofInt(0, 100)
animator.duration = mDuration.toLong()
animator.interpolator = LinearInterpolator()
animator.addUpdateListener {
binding.progressBar.progress = it.animatedValue as Int
}
animator.start()
}
private fun getNotInstalledLink(packageDialogEntity: PackageDialogEntity): LinkEntity? {
val links = LinkedHashSet<LinkEntity>()
packageDialogEntity.detectionObjects.forEach { obj ->
if (!checkDetectionsInstalled(mAllInstalledPackages, obj.packages)) {
obj.assignDownload.forEach {
links.add(packageDialogEntity.links[it])
}
}
}
var link: LinkEntity? = null
if (links.size > 1) {
link = links.find { it.buttonLink } ?: links.toList()[0]
} else if (links.size == 1) {
link = links.toList()[0]
}
return link
}
override fun onStart() {
super.onStart()
val width = requireContext().resources.displayMetrics.widthPixels - 60F.dip2px()
val height = ViewGroup.LayoutParams.WRAP_CONTENT
requireDialog().window?.setLayout(width, height)
requireDialog().setCanceledOnTouchOutside(true)
DownloadManager.getInstance().addObserver(dataWatcher)
}
override fun onResume() {
super.onResume()
mAllInstalledPackages = PackageUtils.getInstalledPackages(HaloApp.getInstance().application, 0)
gameEntity?.packageDialog?.let {
if (isAllPackageInstalled(mAllInstalledPackages, it)) {
callBack?.onConfirm()
dismissAllowingStateLoss()
}
}
}
override fun onDestroyView() {
super.onDestroyView()
EventBus.getDefault().unregister(this)
if (mDisposable?.isDisposed == false) {
mDisposable?.dispose()
}
LogUtils.uploadPackageCheck("pkg_check_pop_click", "关闭弹窗", gameEntity, "", "", "", "")
DownloadManager.getInstance().removeObserver(dataWatcher)
}
//安装、卸载事件
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(busFour: EBPackage) {
if ("安装" == busFour.type || "卸载" == busFour.type) {
mAllInstalledPackages = PackageUtils.getInstalledPackages(HaloApp.getInstance().application, 0)
mAdapter?.notifyDataSetChanged()
}
}
inner class PackageCheckAdapter(val context: Context, val entities: ArrayList<DetectionObjectEntity>) :
BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {
private var index = -1
fun notifyPackages() {
index++
notifyItemChanged(index)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return PackageCheckViewHolder(parent.toBinding())
}
override fun getItemCount(): Int = entities.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is PackageCheckViewHolder) {
val entity = entities[position]
holder.binding.gameNameTv.text = entity.text
if (position <= index) {
val isAllInstalled = checkDetectionsInstalled(mAllInstalledPackages, entity.packages)
if (isAllInstalled) {
holder.binding.statusTv.text = "已安装"
holder.binding.statusTv.setTextColor(ContextCompat.getColor(context, R.color.theme_font))
} else {
holder.binding.statusTv.text = "未安装"
holder.binding.statusTv.setTextColor(ContextCompat.getColor(context, R.color.theme_red))
}
holder.binding.statusTv.visibility = View.VISIBLE
} else {
holder.binding.statusTv.visibility = View.GONE
}
}
}
}
class PackageCheckViewHolder(val binding: PackageCheckItemBinding) : BaseRecyclerViewHolder<DetectionObjectEntity>(binding.root)
companion object {
@JvmStatic
fun show(activity: AppCompatActivity, gameEntity: GameEntity, callBack: DialogUtils.ConfirmListener) {
val packageDialogEntity = gameEntity.packageDialog
if (packageDialogEntity == null) {
callBack.onConfirm()
return
}
val allInstalledPackages = PackageUtils.getInstalledPackages(HaloApp.getInstance().application, 0)
if (isAllPackageInstalled(allInstalledPackages, packageDialogEntity)) {
callBack.onConfirm()
return
}
val isChoose = SPUtils.getBoolean("${Constants.SP_PACKAGE_CHECK}:${packageDialogEntity.id}", false)
if (packageDialogEntity.level == "OPTIONAL_HINT" && isChoose) {
callBack.onConfirm()
return
}
val isCurrentGameChoose = SPUtils.getBoolean("${Constants.SP_PACKAGE_CHECK}:${gameEntity.id}", false)
if (packageDialogEntity.level == "OPTIONAL_CURRENT_HINT" && isCurrentGameChoose) {
callBack.onConfirm()
return
}
if (!activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) return
var dialogFragment =
activity.supportFragmentManager.findFragmentByTag(PackageCheckDialogFragment::class.java.simpleName) as? PackageCheckDialogFragment
if (dialogFragment == null) {
dialogFragment = PackageCheckDialogFragment()
dialogFragment.gameEntity = gameEntity
dialogFragment.callBack = callBack
dialogFragment.show(activity.supportFragmentManager, PackageCheckDialogFragment::class.java.simpleName)
} else {
dialogFragment.gameEntity = gameEntity
dialogFragment.callBack = callBack
val transaction: FragmentTransaction = activity.supportFragmentManager.beginTransaction()
transaction.show(dialogFragment)
transaction.commit()
}
}
private fun checkDetectionsInstalled(allInstalledPackages: List<PackageInfo>, packages: ArrayList<String>): Boolean {
var isPackagesInstalled = false
packages.forEach { packageName ->
val isInstalled = allInstalledPackages.find { it.packageName == packageName } != null
if (isInstalled) {
isPackagesInstalled = true
return@forEach
}
}
return isPackagesInstalled
}
fun isAllPackageInstalled(allInstalledPackages: List<PackageInfo>, packageDialogEntity: PackageDialogEntity): Boolean {
var isAllInstalled = true
packageDialogEntity.detectionObjects.forEach loop@{ obj ->
if (!checkDetectionsInstalled(allInstalledPackages, obj.packages)) {
isAllInstalled = false
return isAllInstalled
}
}
return isAllInstalled
}
}
}

View File

@ -1,190 +0,0 @@
package com.gh.common.dialog
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.ScrollingMovementMethod
import android.text.style.ClickableSpan
import android.view.*
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentTransaction
import com.gh.base.fragment.BaseDialogFragment
import com.gh.common.constant.Constants
import com.gh.common.util.SPUtils
import com.gh.common.util.dip2px
import com.gh.common.util.fromHtml
import com.gh.common.view.CustomLinkMovementMethod
import com.gh.gamecenter.R
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.databinding.DialogPrivacyProtocolBinding
import com.gh.gamecenter.entity.DialogEntity
import com.lightgame.utils.AppManager
import splitties.bundle.put
class PrivacyPolicyDialogFragment : BaseDialogFragment() {
private var mCallBack: ((isSuccess: Boolean) -> Unit)? = null
private val mBinding by lazy { DialogPrivacyProtocolBinding.inflate(layoutInflater) }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return mBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mBinding.contentTv.movementMethod = ScrollingMovementMethod()
val privacyPolicyEntity = arguments?.get(KEY_DATA) as? DialogEntity.PrivacyPolicyEntity
if (privacyPolicyEntity == null) {
showPreLaunchStyle()
} else {
showUpdatedStyle(privacyPolicyEntity)
}
}
private fun showUpdatedStyle(privacyPolicyEntity: DialogEntity.PrivacyPolicyEntity) {
mBinding.titleIv.visibility = View.VISIBLE
mBinding.privacyTitleTv.text = "光环助手《隐私协议》更新"
mBinding.contentTv.text = privacyPolicyEntity.content.fromHtml()
val skipText = SpannableStringBuilder("查看隐私政策详情")
skipText.setSpan(object : ClickableSpan() {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = ContextCompat.getColor(requireContext(), R.color.theme_font)
ds.isUnderlineText = false
}
override fun onClick(widget: View) {
val intent = WebActivity.getIntent(requireContext(), context!!.getString(R.string.privacy_policy_url), true)
context?.startActivity(intent)
}
}, skipText.length - 6, skipText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
mBinding.descTv.movementMethod = CustomLinkMovementMethod()
mBinding.descTv.text = skipText
if (privacyPolicyEntity.alertType == "INFORM") {
mBinding.refuseTv.visibility = View.GONE
mBinding.agreeTv.text = "我知道了"
mBinding.agreeTv.setOnClickListener {
SPUtils.setString(Constants.SP_LAST_ACCEPTED_PRIVACY_DIALOG_ID, privacyPolicyEntity.id)
mCallBack?.invoke(true)
dismissAllowingStateLoss()
}
} else {
mBinding.refuseTv.text = "不同意退出"
mBinding.agreeTv.text = "同意"
mBinding.refuseTv.setOnClickListener {
dismissAllowingStateLoss()
AppManager.getInstance().finishAllActivity()
}
mBinding.agreeTv.setOnClickListener {
SPUtils.setString(Constants.SP_LAST_ACCEPTED_PRIVACY_DIALOG_ID, privacyPolicyEntity.id)
mCallBack?.invoke(true)
dismissAllowingStateLoss()
}
}
}
private fun showPreLaunchStyle() {
val skipText = SpannableStringBuilder("查看完整版的隐私政策和用户协议")
skipText.setSpan(object : ClickableSpan() {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = ContextCompat.getColor(requireContext(), R.color.theme_font)
ds.isUnderlineText = false
}
override fun onClick(widget: View) {
val intent = WebActivity.getIntent(requireContext(), context!!.getString(R.string.privacy_policy_url), true)
context?.startActivity(intent)
}
}, skipText.length - 9, skipText.length - 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
skipText.setSpan(object : ClickableSpan() {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = ContextCompat.getColor(requireContext(), R.color.theme_font)
ds.isUnderlineText = false
}
override fun onClick(widget: View) {
val intent = WebActivity.getIntent(requireContext(), context!!.getString(R.string.disclaimer_url), true)
context?.startActivity(intent)
}
}, skipText.length - 4, skipText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
mBinding.descTv.movementMethod = CustomLinkMovementMethod()
mBinding.descTv.text = skipText
mBinding.refuseTv.setOnClickListener {
mCallBack?.invoke(false)
dismissAllowingStateLoss()
}
mBinding.agreeTv.setOnClickListener {
mCallBack?.invoke(true)
dismissAllowingStateLoss()
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val createDialog = super.onCreateDialog(savedInstanceState)
createDialog.setCanceledOnTouchOutside(false)
createDialog.setOnKeyListener(object : DialogInterface.OnKeyListener {
override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true
}
return false
}
})
val window = createDialog.window
window?.setGravity(Gravity.CENTER)
return createDialog
}
override fun onStart() {
super.onStart()
val width = requireContext().resources.displayMetrics.widthPixels - 60F.dip2px()
val height = ViewGroup.LayoutParams.WRAP_CONTENT
dialog?.window?.setLayout(width, height)
}
companion object {
const val KEY_DATA = "data"
@JvmStatic
fun show(activity: FragmentActivity,
privacyPolicyEntity: DialogEntity.PrivacyPolicyEntity? = null,
callBack: ((isSuccess: Boolean) -> Unit)?) {
var privacyDialogFragment = activity.supportFragmentManager.findFragmentByTag(PrivacyPolicyDialogFragment::class.java.simpleName) as? PrivacyPolicyDialogFragment
if (privacyDialogFragment != null) {
privacyDialogFragment.mCallBack = callBack
val transaction: FragmentTransaction = activity.supportFragmentManager.beginTransaction()
transaction.show(privacyDialogFragment)
transaction.commit()
} else {
privacyDialogFragment = PrivacyPolicyDialogFragment().apply {
mCallBack = callBack
}
}
privacyDialogFragment.arguments = Bundle().apply {
put(KEY_DATA, privacyPolicyEntity)
}
privacyDialogFragment.show(
activity.supportFragmentManager,
PrivacyPolicyDialogFragment::class.java.simpleName
)
}
}
}

View File

@ -1,384 +1,198 @@
//package com.gh.common.dialog
//
//import android.annotation.SuppressLint
//import android.app.Application
//import android.os.Bundle
//import android.text.Html
//import android.view.*
//import android.view.animation.AnimationUtils
//import android.widget.EditText
//import android.widget.TextView
//import androidx.lifecycle.AndroidViewModel
//import androidx.lifecycle.MutableLiveData
//import androidx.lifecycle.Observer
//import butterknife.BindView
//import butterknife.ButterKnife
//import butterknife.OnClick
//import com.gh.base.fragment.BaseDialogFragment
//import com.gh.common.AppExecutor
//import com.gh.common.constant.Config
//import com.gh.common.history.HistoryHelper
//import com.gh.common.repository.ReservationRepository
//import com.gh.common.util.*
//import com.gh.gamecenter.R
//import com.gh.gamecenter.entity.GameEntity
//import com.gh.gamecenter.entity.NotificationUgc
//import com.gh.gamecenter.manager.UserManager
//import com.gh.gamecenter.retrofit.BiResponse
//import com.gh.gamecenter.retrofit.RetrofitManager
//import com.halo.assistant.HaloApp
//import com.lightgame.utils.Utils
//import io.reactivex.android.schedulers.AndroidSchedulers
//import io.reactivex.schedulers.Schedulers
//import okhttp3.ResponseBody
//import org.json.JSONArray
//import org.json.JSONObject
//
//// 预约弹窗
//@Deprecated("v5.6.0废弃")
//class ReserveDialogFragment
// : BaseDialogFragment(), KeyboardHeightObserver {
//// : BaseTrackableDialogFragment() {
//
// @BindView(R.id.reserve_hint_tv)
// lateinit var reserveHintTv: TextView
//
// @BindView(R.id.reserve_content_tv)
// lateinit var reserveContentTv: TextView
//
// @BindView(R.id.reserve_completed_content_tv)
// lateinit var reserveCompletedContentTv: TextView
//
// @BindView(R.id.mobile_et)
// lateinit var mobileEt: EditText
//
// @BindView(R.id.reserve_container)
// lateinit var reserveContainer: View
//
// @BindView(R.id.reserve_completed_container)
// lateinit var reserveCompletedContainer: View
//
// @BindView(R.id.customizable_btn)
// lateinit var customizableBtn: TextView
//
// @BindView(R.id.content_container)
// lateinit var contentContainer: View
//
// @BindView(R.id.mobile_index_container)
// lateinit var mobileIndexContainer: View
//
// @BindView(R.id.mobile_index_reserve)
// lateinit var mobileIndexReserve: TextView
//
// @BindView(R.id.mobile_index_user)
// lateinit var mobileIndexUser: TextView
//
// @BindView(R.id.mobile_et_delete)
// lateinit var mobileEtDelete: View
//
// @BindView(R.id.layout_container)
// lateinit var layoutContainer: View
//
// private lateinit var mViewModel: ReserveViewModel
//
// var successCallback: SuccessCallback? = null
//
// private var mGame: GameEntity? = null
// private var mGameId: String = ""
// private var mGameName: String = ""
//
// private var mKeyboardHeightProvider: KeyboardHeightProvider? = null
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
//
// mGame = requireArguments().getParcelable(EntranceUtils.KEY_GAME)
// mGameId = mGame?.id ?:""
// mGameName = mGame?.name ?:""
//
// mViewModel = viewModelProvider()
// mKeyboardHeightProvider = KeyboardHeightProvider(activity)
// mKeyboardHeightProvider?.start()
// }
//
// override fun onActivityCreated(savedInstanceState: Bundle?) {
// super.onActivityCreated(savedInstanceState)
// dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
// }
//
// override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// return inflater.inflate(R.layout.dialog_reserve_game, null)
// }
//
//// override fun getEvent(): String {
//// return "预约游戏"
//// }
////
//// override fun getKey(): String {
//// return "预约功能操作"
//// }
//
// @Suppress("DEPRECATION")
// @SuppressLint("SetTextI18n")
// override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// super.onViewCreated(view, savedInstanceState)
// ButterKnife.bind(this, view)
//
// val reserveContent = "游戏上线,您将收到<font color='#1383EB'>免费短信</font>提醒"
// reserveContentTv.text = Html.fromHtml(reserveContent)
//
//
// mobileEt.setTextChangedListener { s, _, _, _ ->
// mobileIndexContainer.visibility = View.GONE
// mobileEtDelete.goneIf(s.trim().isEmpty())
// }
//
// mViewModel.reservation.observeNonNull(this) {
// if (it.success) {
// showSuccessDialog(it.withMobile, it.boundWechat)
// successCallback?.onSuccess()
// HistoryHelper.insertGameEntity(mGame!!)
// }
// }
//
// mViewModel.reserveMobile.observe(viewLifecycleOwner, Observer {
// setMobileIndexHint(it)
// })
//
// dialog?.setCanceledOnTouchOutside(true)
// }
//
// private fun showSuccessDialog(withMobile: Boolean, boundWechat: Boolean) {
// reserveHintTv.text = "游戏预约成功"
// reserveContainer.visibility = View.GONE
// reserveCompletedContainer.visibility = View.VISIBLE
//
// val reservation = Config.getSettings()?.appointment
// val dialogConfig = if (withMobile) reservation?.withMobile else reservation?.withoutMobile
//
// reserveCompletedContentTv.text = dialogConfig?.htmlContent?.fromHtml()
// if (dialogConfig?.text.isNullOrEmpty()
// || (dialogConfig?.type == "wechat_bind" && boundWechat)) {
// customizableBtn.visibility = View.GONE
// } else {
// customizableBtn.text = dialogConfig?.text
// customizableBtn.setOnClickListener {
//// MtaHelper.onEvent("预约游戏", "预约功能操作", "点击跳转按钮")
// DirectUtils.directToLinkPage(
// requireContext(),
// dialogConfig!!.toLinkEntity(),
// "(游戏预约)",
// "")
// dismissAllowingStateLoss()
// }
// }
// }
//
// private fun setMobileIndexHint(reserveMobile: String?) {
// var userMobile = UserManager.getInstance().userInfoEntity?.mobile
// if (reserveMobile == userMobile) userMobile = null
//
// if (!reserveMobile.isNullOrEmpty()) {
// mobileIndexReserve.visibility = View.VISIBLE
// mobileIndexReserve.text = reserveMobile
// } else {
// mobileIndexReserve.visibility = View.GONE
// }
//
// if (!userMobile.isNullOrEmpty()) {
// mobileIndexUser.visibility = View.VISIBLE
// mobileIndexUser.text = userMobile
// } else {
// mobileIndexUser.visibility = View.GONE
// }
// mobileIndexContainer.goneIf(mobileIndexUser.visibility == View.GONE && mobileIndexReserve.visibility == View.GONE)
// if (mobileIndexContainer.visibility ==View.VISIBLE) {
// mobileIndexContainer.animation = AnimationUtils.loadAnimation(requireContext(), R.anim.reserve_dialog_index_anim)
// }
// }
//
// @OnClick(R.id.reserve_with_mobile_btn,
// R.id.reserve_without_mobile_btn,
// R.id.content_container,
// R.id.close_btn,
// R.id.customizable_btn,
// R.id.mobile_index_reserve,
// R.id.mobile_index_user,
// R.id.mobile_et_delete,
// R.id.mobile_et,
// R.id.layout_container)
// fun onClick(view: View) {
// when (view.id) {
// R.id.reserve_without_mobile_btn -> {
//// MtaHelper.onEvent("预约游戏", "预约功能操作", "点击无手机号预约")
// if (mobileIndexContainer.visibility == View.VISIBLE) {
// mobileIndexContainer.visibility = View.GONE
// return
// }
//
// mViewModel.reserve(gameId = mGameId, gameName = mGameName)
// }
//
// R.id.reserve_with_mobile_btn -> {
// if (mobileIndexContainer.visibility == View.VISIBLE) {
// mobileIndexContainer.visibility = View.GONE
// return
// }
//
// val mobile = mobileEt.text.toString()
// if (mobile.length < 11 || !mobile.startsWith("1")) {
// Utils.toast(context, "手机号格式错误,请检查并重新输入")
// return
// }
//
//// MtaHelper.onEvent("预约游戏", "预约功能操作", "点击立即预约")
// mViewModel.reserve(gameId = mGameId, gameName = mGameName, mobile = mobile)
// }
//
// R.id.close_btn -> {
//// MtaHelper.onEvent("预约游戏", "预约功能操作", "点击关闭")
// dismissAllowingStateLoss()
// AppExecutor.uiExecutor.executeWithDelay(Runnable {
// NotificationHelper.showNotificationHintDialog(NotificationUgc.RESERVE_GAME)
// }, 1000)
// }
// R.id.content_container -> {
// mobileIndexContainer.visibility = View.GONE
// }
// R.id.mobile_index_reserve -> {
// mobileEt.setText(mobileIndexReserve.text.toString())
// mobileEt.setSelection(mobileEt.text.length)
// mobileIndexContainer.visibility = View.GONE
// }
// R.id.mobile_index_user -> {
// mobileEt.setText(mobileIndexUser.text.toString())
// mobileEt.setSelection(mobileEt.text.length)
// mobileIndexContainer.visibility = View.GONE
// }
// R.id.mobile_et_delete -> {
// mobileEt.setText("")
// }
// R.id.mobile_et -> {
// mobileIndexContainer.visibility = View.GONE
// }
// R.id.layout_container -> {
// dismissAllowingStateLoss()
// }
// }
// }
//
// override fun onResume() {
// super.onResume()
// if (HaloApp.getInstance().mCacheKeyboardHeight > 0) {
// val attributes = dialog?.window?.attributes
// val heightPixels = requireContext().resources.displayMetrics.heightPixels
// val mCacheKeyboardHeight = HaloApp.getInstance().mCacheKeyboardHeight
// val statusBarHeight = DisplayUtils.getStatusBarHeight(requireContext().resources)
// dialog?.window?.attributes?.height = heightPixels - mCacheKeyboardHeight - statusBarHeight
// attributes?.gravity = Gravity.TOP
// dialog?.window?.attributes = attributes
// }
// mKeyboardHeightProvider?.setKeyboardHeightObserver(this)
// }
//
// override fun onPause() {
// super.onPause()
// mKeyboardHeightProvider?.setKeyboardHeightObserver(null)
// }
//
// override fun onDestroy() {
// super.onDestroy()
// mKeyboardHeightProvider?.close()
// }
//
// override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
// if (height > 0) {
// val attributes = dialog?.window?.attributes
// attributes?.gravity = Gravity.CENTER
// dialog?.window?.attributes = attributes
// HaloApp.getInstance().mCacheKeyboardHeight = height
// }
// }
//
// companion object {
// @JvmStatic
// fun getInstance(gameEntity: GameEntity, successCallback: SuccessCallback) = ReserveDialogFragment().apply {
// arguments = Bundle().apply {
// putParcelable(EntranceUtils.KEY_GAME, gameEntity)
// }
// this.successCallback = successCallback
// }
// }
//
// interface SuccessCallback {
// fun onSuccess()
// }
//}
//
//class ReserveViewModel(application: Application) : AndroidViewModel(application) {
// val reservation = MutableLiveData<Reservation>()
//
// val reserveMobile = MutableLiveData<String>()
//
// init {
// getAppointmentMobile()
// }
//
// @SuppressLint("CheckResult")
// fun reserve(gameId: String, gameName: String, mobile: String = "") {
//
// val requestMap = hashMapOf<String, String>()
// requestMap["game_id"] = gameId
// if (mobile.isNotEmpty()) {
// requestMap["mobile"] = mobile
// }
//
// RetrofitManager.getInstance().api
// .createNewGameReservation(requestMap.createRequestBody())
// .subscribeOn(Schedulers.io())
// .subscribe(object : BiResponse<ResponseBody>() {
// override fun onSuccess(data: ResponseBody) {
// var boundWechat = false
// tryWithDefaultCatch {
// boundWechat = JSONObject(data.string() ?: "").getBoolean("wechat_bind")
// }
//
// reservation.postValue(Reservation(success = true, withMobile = mobile.isNotEmpty(), boundWechat = boundWechat))
// ReservationRepository.addReservationToMemoryAndRefresh(gameId)
//
//// MtaHelper.onEvent("预约游戏", "预约", gameName)
// }
//
// override fun onFailure(exception: Exception) {
// Utils.toast(getApplication(), exception.message)
// }
// })
// }
//
// @SuppressLint("CheckResult")
// private fun getAppointmentMobile() {
// RetrofitManager.getInstance().api
// .getAppointmentMobile(UserManager.getInstance().userId)
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(object : BiResponse<ResponseBody>() {
// override fun onSuccess(data: ResponseBody) {
// var mobile: String? = null
// tryCatchInRelease {
// val jsonArray = JSONArray(data.string())
// if (jsonArray.length() > 0) {
// mobile = jsonArray.get(0).toString()
// }
// }
//
// reserveMobile.postValue(mobile)
// }
//
// override fun onFailure(exception: Exception) {
// reserveMobile.postValue(null)
// }
// })
// }
//
// class Reservation(var success: Boolean = false, var withMobile: Boolean = false, var boundWechat: Boolean = false)
//}
package com.gh.common.dialog
import android.annotation.SuppressLint
import android.app.Application
import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.gh.common.constant.Config
import com.gh.common.repository.ReservationRepository
import com.gh.common.util.*
import com.gh.gamecenter.R
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.manager.UserManager
import com.gh.gamecenter.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.json.JSONObject
// 预约弹窗
class ReserveDialogFragment : BaseTrackableDialogFragment() {
@BindView(R.id.reserve_hint_tv)
lateinit var reserveHintTv: TextView
@BindView(R.id.reserve_content_tv)
lateinit var reserveContentTv: TextView
@BindView(R.id.reserve_completed_content_tv)
lateinit var reserveCompletedContentTv: TextView
@BindView(R.id.mobile_et)
lateinit var mobileEt: EditText
@BindView(R.id.reserve_container)
lateinit var reserveContainer: View
@BindView(R.id.reserve_completed_container)
lateinit var reserveCompletedContainer: View
@BindView(R.id.customizable_btn)
lateinit var customizableBtn: TextView
private lateinit var mViewModel: ReserveViewModel
private var mSuccessCallback: SuccessCallback? = null
private var mGameId: String = ""
private var mGameName: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mViewModel = viewModelProvider()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.dialog_reserve_game, null)
}
override fun getEvent(): String {
return "预约游戏"
}
override fun getKey(): String {
return "预约功能操作"
}
@Suppress("DEPRECATION")
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ButterKnife.bind(this, view)
val reserveContent = "游戏上线,您将<font color='#ff4147'>免费</font>收到短信提醒"
reserveContentTv.text = Html.fromHtml(reserveContent)
mobileEt.setText(UserManager.getInstance().userInfoEntity.mobile)
mobileEt.setSelection(mobileEt.text.length)
mViewModel.reservation.observeNonNull(this) {
if (it.success) {
showSuccessDialog(it.withMobile, it.boundWechat)
mSuccessCallback?.onSuccess()
}
}
dialog?.setCanceledOnTouchOutside(true)
}
private fun showSuccessDialog(withMobile: Boolean, boundWechat: Boolean) {
reserveHintTv.text = "游戏预约成功"
reserveContainer.visibility = View.GONE
reserveCompletedContainer.visibility = View.VISIBLE
val reservation = Config.getSettings()?.appointment
val dialogConfig = if (withMobile) reservation?.withMobile else reservation?.withoutMobile
reserveCompletedContentTv.text = dialogConfig?.htmlContent?.fromHtml()
if (dialogConfig?.text.isNullOrEmpty()
|| (dialogConfig?.type == "wechat_bind" && boundWechat)) {
customizableBtn.visibility = View.GONE
} else {
customizableBtn.text = dialogConfig?.text
customizableBtn.setOnClickListener {
MtaHelper.onEvent("预约游戏", "预约功能操作", "点击跳转按钮")
DirectUtils.directToLinkPage(
requireContext(),
dialogConfig!!.toLinkEntity(),
"(游戏预约)",
"")
dismissAllowingStateLoss()
}
}
}
@OnClick(R.id.reserve_with_mobile_btn,
R.id.reserve_without_mobile_btn,
R.id.close_btn,
R.id.customizable_btn)
fun onClick(view: View) {
when (view.id) {
R.id.reserve_without_mobile_btn -> {
MtaHelper.onEvent("预约游戏", "预约功能操作", "点击无手机号预约")
mViewModel.reserve(gameId = mGameId, gameName = mGameName)
}
R.id.reserve_with_mobile_btn -> {
val mobile = mobileEt.text.toString()
if (mobile.length < 11 || !mobile.startsWith("1")) {
Utils.toast(context, "手机号格式错误,请检查并重新输入")
return
}
MtaHelper.onEvent("预约游戏", "预约功能操作", "点击立即预约")
mViewModel.reserve(gameId = mGameId, gameName = mGameName, mobile = mobile)
}
R.id.close_btn -> {
MtaHelper.onEvent("预约游戏", "预约功能操作", "点击关闭")
dismissAllowingStateLoss()
}
}
}
companion object {
@JvmStatic
fun getInstance(gameEntity: GameEntity, successCallback: SuccessCallback) = ReserveDialogFragment().apply {
this.mGameId = gameEntity.id
this.mGameName = gameEntity.name ?: ""
this.mSuccessCallback = successCallback
}
}
interface SuccessCallback {
fun onSuccess()
}
}
class ReserveViewModel(application: Application) : AndroidViewModel(application) {
val reservation = MutableLiveData<Reservation>()
@SuppressLint("CheckResult")
fun reserve(gameId: String, gameName: String, mobile: String = "") {
val requestMap = hashMapOf<String, String>()
requestMap["game_id"] = gameId
if (mobile.isNotEmpty()) {
requestMap["mobile"] = mobile
}
RetrofitManager.getInstance(getApplication()).api
.createNewGameReservation(requestMap.createRequestBody())
.subscribeOn(Schedulers.io())
.subscribe(object : BiResponse<ResponseBody>() {
override fun onSuccess(data: ResponseBody) {
var boundWechat = false
tryWithDefaultCatch {
boundWechat = JSONObject(data.string() ?: "").getBoolean("wechat_bind")
}
reservation.postValue(Reservation(success = true, withMobile = mobile.isNotEmpty(), boundWechat = boundWechat))
ReservationRepository.addReservationToMemoryAndRefresh(gameId)
MtaHelper.onEvent("预约游戏", "预约", gameName)
}
override fun onFailure(exception: Exception) {
Utils.toast(getApplication(), exception.message)
}
})
}
class Reservation(var success: Boolean = false, var withMobile: Boolean = false, var boundWechat: Boolean = false)
}

View File

@ -8,13 +8,12 @@ import com.gh.common.util.MtaHelper
import java.util.concurrent.atomic.AtomicBoolean
open class TrackableDialog(context: Context,
themeResId: Int,
private var mEvent: String,
private var mKey: String,
private var mValue: String? = null,
private var mCancelValue: String? = null,
private var mKeyBackValue: String? = null,
private var mLogShowEvent: Boolean = true)
themeResId: Int,
private var mEvent: String,
private var mKey: String,
private var mCancelValue: String? = null,
private var mKeyBackValue: String? = null,
private var mLogShowEvent: Boolean = true)
: Dialog(context, themeResId) {
// 区分此 dialog 是点击 dialog 外部取消的还是点击返回取消的
@ -26,9 +25,6 @@ open class TrackableDialog(context: Context,
setOnCancelListener {
if (mIsCanceledByClickOutsideOfDialog.get()) {
MtaHelper.onEvent(mEvent, mKey, mCancelValue ?: "点击空白")
if (!mValue.isNullOrEmpty()) {
MtaHelper.onEvent(mEvent, "点击空白", mValue)
}
}
}
@ -36,9 +32,6 @@ open class TrackableDialog(context: Context,
if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {
mIsCanceledByClickOutsideOfDialog.set(false)
MtaHelper.onEvent(mEvent, mKey, mKeyBackValue ?: "点击返回")
if (mValue != null) {
MtaHelper.onEvent(mEvent, "点击返回", mValue)
}
}
false
}
@ -48,9 +41,6 @@ open class TrackableDialog(context: Context,
super.show()
if (mLogShowEvent) {
MtaHelper.onEvent(mEvent, mKey, "出现弹窗")
if (!mValue.isNullOrEmpty()) {
MtaHelper.onEvent(mEvent, "出现弹窗", mValue)
}
}
}

View File

@ -3,88 +3,16 @@ package com.gh.common.exposure
import android.os.Parcelable
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
import kotlinx.android.parcel.Parcelize
@Keep
@Parcelize
data class ExposureEntity(
@SerializedName("game_id")
val gameId: String? = "",
@SerializedName("subject_id")
val subjectId: String? = null, // 专题 id
@SerializedName("carousel_id")
val carouselId: String? = "", // 轮播图 id
val gameName: String? = "",
val gameVersion: String? = "",
val sequence: Int? = 0,
val outerSequence: Int? = 0,
val platform: String? = null,
var isMirrorData: Boolean = false,
@SerializedName("is_web_download")
var isWebDownload: Boolean = false,
val downloadType: String? = null,
val downloadCompleteType: String? = null,
@SerializedName("display_type")
val displayType: String? = "",
@SerializedName("is_platform_recommend")
val isPlatformRecommend: Boolean? = false,
// 外层内容 id (包括)
// 1. "test_server_id" : "", // 开测表 ID
// 2. "block_id" : "", // 板块 ID
// 3. "category_id" : "", // 新分类1.0 ID
// 4. "category_v2_id" : "", // 新分类2.0 ID
var containerId: String? = null,
var containerType: String? = null,
@SerializedName("test_server_id")
var testServerId: String? = null,
@SerializedName("block_id")
var blockId: String? = null,
@SerializedName("category_id")
var categoryId: String? = null,
@SerializedName("category_v2_id")
var categoryV2Id: String? = null,
@SerializedName("navigation_id")
var navigationId: String? = null,
// 专题详情的来源页面和来源 id
@SerializedName("source_page")
var sourcePage: String? = null,
@SerializedName("source_page_id")
var sourcePageId: String? = null,
@SerializedName("source_page_name")
var sourcePageName: String? = null,
// 下载地址的 host 和 path
var host: String? = null,
var path: String? = null,
// 统计启动弹窗相关数据用的 (ugly)
@SerializedName("dialog_id")
var welcomeDialogId: String? = null,
@SerializedName("link_title")
var welcomeDialogLinkTitle: String? = null
) : Parcelable {
fun setContainerInfo(id: String?, type: String?) {
when (type) {
TEST_SERVER_ID -> testServerId = id
BLOCK_ID -> blockId = id
CATEGORY_ID -> categoryId = id
CATEGORY_V2_ID -> categoryV2Id = id
NAVIGATION_ID -> navigationId = id
}
containerId = null
containerType = null
}
companion object {
const val TEST_SERVER_ID = "test_server_id"
const val BLOCK_ID = "block_id"
const val CATEGORY_ID = "category_id"
const val CATEGORY_V2_ID = "category_v2_id"
const val NAVIGATION_ID = "navigation_id"
}
}
@SerializedName("game_id")
val gameId: String? = "",
val gameName: String? = "",
val sequence: Int? = 0,
val platform: String? = "",
val downloadType: String? = "",
val downloadCompleteType: String? = ""
) : Parcelable

View File

@ -4,107 +4,38 @@ import android.os.Parcelable
import androidx.annotation.Keep
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.gh.common.constant.Constants
import com.gh.common.exposure.meta.Meta
import com.gh.common.exposure.meta.MetaUtil
import com.gh.common.exposure.time.TimeUtil
import com.gh.common.util.getFirstElementDividedByDivider
import com.gh.download.server.BrowserInstallHelper
import com.gh.gamecenter.entity.GameEntity
import com.lightgame.download.DownloadEntity
import kotlinx.parcelize.Parcelize
import kotlinx.android.parcel.Parcelize
import java.util.*
import kotlin.collections.ArrayList
@Keep
@Parcelize
@Entity(tableName = "exposureEvent")
data class ExposureEvent(
var payload: ExposureEntity,
val source: List<ExposureSource>,
var eTrace: List<ExposureEvent>? = arrayListOf(),
val event: ExposureType,
val meta: Meta = MetaUtil.getMeta(),
val time: Int = TimeUtil.currentTime(),
@PrimaryKey
val id: String = UUID.randomUUID().toString()
) : Parcelable {
var payload: ExposureEntity,
val source: List<ExposureSource>,
var eTrace: List<ExposureEvent>? = arrayListOf(),
val event: ExposureType,
val meta: Meta = MetaUtil.getMeta(),
val time: Int = TimeUtil.currentTime(),
@PrimaryKey
val id: String = UUID.randomUUID().toString()) : Parcelable {
companion object {
@JvmStatic
fun createEvent(
gameEntity: GameEntity?,
source: List<ExposureSource>,
eTrace: List<ExposureEvent>? = null,
event: ExposureType = ExposureType.EXPOSURE
): ExposureEvent {
if (gameEntity?.getApk()?.size == 1) {
gameEntity.gameVersion = gameEntity.getApk().elementAtOrNull(0)?.version ?: ""
}
fun createEvent(gameEntity: GameEntity?, source: List<ExposureSource>, eTrace: List<ExposureEvent>? = null, event: ExposureType = ExposureType.EXPOSURE): ExposureEvent {
return ExposureEvent(
payload = ExposureEntity(
gameId = gameEntity?.id?.getFirstElementDividedByDivider(DownloadEntity.GAME_ID_DIVIDER),
gameName = eTrace?.firstOrNull()?.payload?.gameName
?: gameEntity?.name?.removeSuffix(Constants.GAME_NAME_DECORATOR),
gameVersion = eTrace?.firstOrNull()?.payload?.gameVersion
?: gameEntity?.gameVersion,
subjectId = eTrace?.firstOrNull()?.payload?.subjectId
?: gameEntity?.subjectId
?: gameEntity?.subjectData?.id,
isMirrorData = eTrace?.firstOrNull()?.payload?.isMirrorData
?: gameEntity?.shouldUseMirrorInfo() ?: false,
isWebDownload = BrowserInstallHelper.isUseBrowserToInstallEnabled() && BrowserInstallHelper.shouldUseBrowserToInstall(), // 实时的值,不用从 eTrace 里取
sequence = eTrace?.firstOrNull()?.payload?.sequence ?: gameEntity?.sequence,
outerSequence = eTrace?.firstOrNull()?.payload?.outerSequence
?: gameEntity?.outerSequence,
platform = eTrace?.firstOrNull()?.payload?.platform ?: gameEntity?.platform,
downloadType = gameEntity?.downloadType,
downloadCompleteType = gameEntity?.downloadCompleteType,
displayType = eTrace?.firstOrNull()?.payload?.displayType
?: gameEntity?.displayContent,
isPlatformRecommend = gameEntity?.isPlatformRecommend,
// ugly
welcomeDialogId = gameEntity?.welcomeDialogId
?: eTrace?.firstOrNull()?.payload?.welcomeDialogId,
welcomeDialogLinkTitle = gameEntity?.welcomeDialogTitle
?: eTrace?.firstOrNull()?.payload?.welcomeDialogLinkTitle
),
source = source,
eTrace = eTrace,
event = event
).also {
it.payload.categoryId = eTrace?.firstOrNull()?.payload?.categoryId
it.payload.categoryV2Id = eTrace?.firstOrNull()?.payload?.categoryV2Id
it.payload.testServerId = eTrace?.firstOrNull()?.payload?.testServerId
it.payload.blockId = eTrace?.firstOrNull()?.payload?.blockId
it.payload.setContainerInfo(
eTrace?.firstOrNull()?.payload?.containerId ?: gameEntity?.containerId,
eTrace?.firstOrNull()?.payload?.containerType ?: gameEntity?.containerType
)
it.payload.sourcePage = eTrace?.firstOrNull()?.payload?.sourcePage
it.payload.sourcePageId = eTrace?.firstOrNull()?.payload?.sourcePageId
it.payload.sourcePageName = eTrace?.firstOrNull()?.payload?.sourcePageName
gameEntity?.exposureEvent = it
}
payload = ExposureEntity(gameId = gameEntity?.id,
gameName = gameEntity?.name,
sequence = gameEntity?.sequence,
platform = gameEntity?.platform,
downloadType = gameEntity?.downloadType,
downloadCompleteType = gameEntity?.downloadCompleteType),
source = source,
eTrace = eTrace,
event = event).apply { gameEntity?.exposureEvent = this }
}
@JvmStatic
fun createEventWithSourceConcat(
gameEntity: GameEntity?,
basicSource: List<ExposureSource>,
source: List<ExposureSource>,
eTrace: List<ExposureEvent>? = null,
event: ExposureType = ExposureType.EXPOSURE
): ExposureEvent {
val concatSourceList = ArrayList<ExposureSource>().apply {
addAll(basicSource)
addAll(source)
}
return createEvent(gameEntity, concatSourceList, eTrace, event)
}
}
}

View File

@ -11,24 +11,20 @@ import io.reactivex.functions.Consumer
*/
class ExposureListener(var fragment: Fragment, var exposable: IExposable) : RecyclerView.OnScrollListener() {
val throttleBus: ExposureThrottleBus by lazy { ExposureThrottleBus(Consumer { commitExposure(it) }, Consumer(Throwable::printStackTrace)) }
var throttleBus: ExposureThrottleBus? = null
var layoutManager: LinearLayoutManager? = null
var visibleState: ExposureThrottleBus.VisibleState? = null
init {
fragment.fragmentManager?.registerFragmentLifecycleCallbacks(
object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentPaused(fm: FragmentManager, f: Fragment) {
if (fragment == f) {
visibleState?.let { commitExposure(it) }
throttleBus.clear()
}
override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
throttleBus = ExposureThrottleBus(Consumer { commitExposure(it) }, Consumer(Throwable::printStackTrace))
}
override fun onFragmentViewDestroyed(fm: FragmentManager, f: Fragment) {
if (fragment == f) {
fragment.fragmentManager?.unregisterFragmentLifecycleCallbacks(this)
}
override fun onFragmentPaused(fm: FragmentManager, f: Fragment) {
visibleState?.let { commitExposure(it) }
throttleBus?.clear()
}
}, false)
}
@ -43,8 +39,8 @@ class ExposureListener(var fragment: Fragment, var exposable: IExposable) : Recy
if (layoutManager == null) layoutManager = recyclerView.layoutManager as LinearLayoutManager
layoutManager?.run {
visibleState = ExposureThrottleBus.VisibleState(findFirstVisibleItemPosition(), findLastVisibleItemPosition())
throttleBus.postVisibleState(visibleState!!)
visibleState = ExposureThrottleBus.VisibleState(findFirstCompletelyVisibleItemPosition(), findLastCompletelyVisibleItemPosition())
throttleBus?.postVisibleState(visibleState!!)
}
}
@ -55,7 +51,7 @@ class ExposureListener(var fragment: Fragment, var exposable: IExposable) : Recy
val eventList = arrayListOf<ExposureEvent>()
for (pos in visibleState.firstVisiblePosition..visibleState.lastVisiblePosition) {
for (pos in visibleState.firstCompletelyVisible..visibleState.lastCompletelyVisible) {
try {
exposable.getEventByPosition(pos)?.let { eventList.add(it) }
exposable.getEventListByPosition(pos)?.let { eventList.addAll(it) }

View File

@ -1,13 +1,15 @@
package com.gh.common.exposure
import com.aliyun.sls.android.producer.Log
import com.gh.common.loghub.LoghubHelper
import com.aliyun.sls.android.sdk.model.LogGroup
import com.gh.common.exposure.time.TimeUtil
import com.gh.common.util.toJson
import com.gh.common.util.tryWithDefaultCatch
import com.gh.gamecenter.BuildConfig
import com.gh.loghub.LgLOG
import com.gh.loghub.LoghubHelper
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlin.concurrent.fixedRateTimer
/**
* A handful tool for committing logs to aliyun loghub.
@ -15,28 +17,38 @@ import java.util.concurrent.ExecutorService
* 如何简单地统计列表中每个 item 的曝光事件?
*
* 1. Adapter 实现 IExposable 接口,在 BindView 阶段更新 ExposureEventExposureEvent 供 getEventByPosition(pos) 方法获取用
* 2. 构建一个 ExposureListener 并作为入参添加至 recyclerview 的 onScroll 回调中
* 2. 构建一个 ExposureListener 并作为入参添加至 recyclerview 的 Scroll 回调中
* 3. 没了
*/
object ExposureManager {
private const val ENDPOINT = "cn-qingdao.log.aliyuncs.com"
private const val PROJECT = "ghzs"
private const val STORE_SIZE = 100
private const val STORE_FORCE_UPLOAD_PERIOD = 300 * 1000L
private const val LOG_STORE = BuildConfig.EXPOSURE_REPO
private val loghubHelper = LoghubHelper.getInstance()
// exposureCache 用来过滤掉具有相同 id 的曝光事件,避免重复发送事件
private val exposureSet by lazy { hashSetOf<ExposureEvent>() }
private var exposureExecutor: ExecutorService? = null
private val exposureCache by lazy { FixedSizeLinkedHashSet<String>(300) }
private val exposureSet = hashSetOf<ExposureEvent>()
private val exposureExecutor = Executors.newSingleThreadExecutor()
private val exposureCache = FixedSizeLinkedHashSet<String>(300)
private val exposureDao by lazy { ExposureDatabase.buildDatabase(HaloApp.getInstance().application).logHubEventDao() }
@JvmStatic
fun init(excutor: ExecutorService) {
exposureExecutor = excutor
exposureExecutor?.execute {
tryWithDefaultCatch {
val eventList = exposureDao.getAll()
exposureSet.addAll(eventList)
}
fun init() {
TimeUtil.init()
loghubHelper.init(HaloApp.getInstance().application, ENDPOINT, PROJECT, LOG_STORE) { TimeUtil.currentTimeMillis() }
exposureExecutor.execute {
val eventList = exposureDao.getAll()
exposureSet.addAll(eventList)
}
fixedRateTimer(name = "ExposureManager-Store-Checker", initialDelay = 500, period = STORE_FORCE_UPLOAD_PERIOD) {
commitSavedExposureEvents(true)
}
}
@ -44,7 +56,7 @@ object ExposureManager {
* Log a single exposure event.
*/
fun log(event: ExposureEvent) {
exposureExecutor?.execute {
exposureExecutor.execute {
try {
if (!exposureCache.contains(event.id)) {
// Catch `android.database.sqlite.SQLiteFullException: database or disk is full` exception.
@ -66,7 +78,7 @@ object ExposureManager {
* Log a collection of exposure event.
*/
fun log(eventList: List<ExposureEvent>) {
exposureExecutor?.execute {
exposureExecutor.execute {
for (event in eventList) {
try {
if (!exposureCache.contains(event.id)) {
@ -89,18 +101,16 @@ object ExposureManager {
* @param forced Ignore all restrictions.
*/
fun commitSavedExposureEvents(forced: Boolean = false) {
exposureExecutor?.execute {
tryWithDefaultCatch {
// TODO 初始化 loghubHelper 去掉这个 tryCatch 块
if (exposureSet.size < STORE_SIZE && !forced || exposureSet.size == 0) return@execute
exposureExecutor.execute {
if (exposureSet.size < STORE_SIZE && !forced || exposureSet.size == 0) return@execute
val exposureList = exposureSet.toList()
uploadExposures(exposureList)
val exposureList = exposureSet.toList()
// uploadLogGroup 是一个异步方法LoghubHelper 里面实现了重传功能,所以这里交给它就好了
loghubHelper.uploadLogGroup(buildLogGroup(exposureList))
Utils.log("Exposure", "提交了${exposureList.size}条曝光记录")
exposureSet.removeAll(exposureList)
exposureDao.deleteMany(exposureList)
}
Utils.log("Exposure", "提交了${exposureList.size}条曝光记录")
exposureSet.removeAll(exposureList)
exposureDao.deleteMany(exposureList)
}
}
@ -108,25 +118,31 @@ object ExposureManager {
return jsonWithMultipleBracket.replace("[[", "[").replace("]]", "]")
}
private fun uploadExposures(eventList: List<ExposureEvent>) {
eventList.forEach {
LoghubHelper.uploadLog(buildLog(it), LOG_STORE)
}
private fun buildLogGroup(eventList: List<ExposureEvent>): LogGroup {
val logGroup = LogGroup("sls android", "no ip")
eventList.forEach { logGroup.PutLog(buildLog(it)) }
return logGroup
}
private fun buildLog(event: ExposureEvent) = Log().apply {
putContent("id", event.id)
putContent("payload", event.payload.toJson())
putContent("event", event.event.toString())
putContent("source", eliminateMultipleBrackets(event.source.toJson()))
putContent("meta", event.meta.toJson())
putContent("e-traces", if (event.eTrace != null) {
private fun buildLog(event: ExposureEvent): LgLOG {
val log = LgLOG(TimeUtil.currentTime())
log.PutContent("id", event.id)
log.PutContent("payload", event.payload.toJson())
log.PutContent("event", event.event.toString())
log.PutContent("source", eliminateMultipleBrackets(event.source.toJson()))
log.PutContent("meta", event.meta.toJson())
log.PutContent("e-traces", if (event.eTrace != null) {
eliminateMultipleBrackets(event.eTrace?.toJson() ?: "")
} else "")
logTime = event.time.toLong()
log.PutTime(event.time)
return log
}
class FixedSizeLinkedHashSet<T>(var maxSize: Int) : LinkedHashSet<T>() {
internal class FixedSizeLinkedHashSet<T>(var maxSize: Int) : LinkedHashSet<T>() {
override fun add(element: T): Boolean {
if (size == maxSize) {
pop()

View File

@ -2,7 +2,7 @@ package com.gh.common.exposure
import android.os.Parcelable
import androidx.annotation.Keep
import kotlinx.parcelize.Parcelize
import kotlinx.android.parcel.Parcelize
@Keep
@Parcelize

View File

@ -38,21 +38,21 @@ class ExposureThrottleBus(var onSuccess: Consumer<VisibleState>, var onError: Co
mPublishSubject.onNext(visibleState)
}
class VisibleState(val firstVisiblePosition: Int, val lastVisiblePosition: Int) {
class VisibleState(val firstCompletelyVisible: Int, val lastCompletelyVisible: Int) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that = other as VisibleState
if (firstVisiblePosition != that.firstVisiblePosition) return false
if (firstCompletelyVisible != that.firstCompletelyVisible) return false
return lastVisiblePosition == that.lastVisiblePosition
return lastCompletelyVisible == that.lastCompletelyVisible
}
override fun hashCode(): Int {
var result = firstVisiblePosition
result = 31 * result + lastVisiblePosition
var result = firstCompletelyVisible
result = 31 * result + lastCompletelyVisible
return result
}
}

View File

@ -1,137 +1,68 @@
package com.gh.common.exposure
import android.text.TextUtils
import com.g00fy2.versioncompare.Version
import com.gh.common.util.PackageUtils
import com.gh.common.util.toObject
import com.gh.gamecenter.entity.ApkEntity
import com.gh.gamecenter.entity.GameEntity
import com.halo.assistant.HaloApp
import com.lightgame.download.DownloadEntity
import java.util.*
object ExposureUtils {
private val mDownloadCompleteTraceEventIdSet = ExposureManager.FixedSizeLinkedHashSet<String>(3)
@JvmStatic
fun logADownloadExposureEvent(
entity: GameEntity,
platform: String?,
traceEvent: ExposureEvent?,
downloadType: DownloadType
): ExposureEvent {
fun logADownloadExposureEvent(entity: GameEntity,
platform: String?,
traceEvent: ExposureEvent?,
downloadType: DownloadType): ExposureEvent {
val gameEntity = entity.clone()
gameEntity.id = if (entity.id.contains(DownloadEntity.GAME_ID_DIVIDER)) {
entity.id.split(DownloadEntity.GAME_ID_DIVIDER).toTypedArray()[0]
} else {
entity.id
}
gameEntity.gameVersion = entity.getApk().elementAtOrNull(0)?.version
?: gameEntity.gameVersion
gameEntity.platform = platform
gameEntity.downloadType = downloadType.toString()
val exposureEvent = ExposureEvent.createEvent(
gameEntity = gameEntity,
source = traceEvent?.source ?: ArrayList(),
eTrace = ExposureTraceUtils.appendTrace(traceEvent),
event = ExposureType.DOWNLOAD
)
if (!TextUtils.isEmpty(entity.id)) {
ExposureManager.log(exposureEvent)
}
val exposureEvent = ExposureEvent.createEvent(gameEntity = gameEntity,
source = traceEvent?.source ?: ArrayList(),
eTrace = ExposureTraceUtils.appendTrace(traceEvent),
event = ExposureType.DOWNLOAD)
ExposureManager.log(exposureEvent)
return exposureEvent
}
@JvmStatic
fun logADownloadCompleteExposureEvent(
entity: GameEntity,
platform: String?,
trace: String?,
host: String? = "unknown",
path: String? = "unknown",
downloadType: DownloadType
) {
fun logADownloadCompleteExposureEvent(entity: GameEntity,
platform: String?,
trace: String?,
downloadType: DownloadType) {
val gameEntity = entity.clone()
gameEntity.platform = platform
gameEntity.downloadCompleteType = downloadType.toString()
val traceEvent = trace?.toObject<ExposureEvent>()
if (TextUtils.isEmpty(entity.id)) return
// 避免生成 trace 相同的下载完成事件,根据日志看下载完成的同一秒有可能生成两条
if (mDownloadCompleteTraceEventIdSet.contains(traceEvent?.id)) {
return
}
traceEvent?.payload?.gameId?.let { mDownloadCompleteTraceEventIdSet.add(it) }
val exposureEvent = ExposureEvent.createEvent(
gameEntity = gameEntity,
source = traceEvent?.source ?: ArrayList(),
eTrace = ExposureTraceUtils.appendTrace(traceEvent),
event = ExposureType.DOWNLOAD_COMPLETE
)
exposureEvent.payload.host = host
exposureEvent.payload.path = path
val exposureEvent = ExposureEvent.createEvent(gameEntity = gameEntity,
source = traceEvent?.source ?: ArrayList(),
eTrace = ExposureTraceUtils.appendTrace(traceEvent),
event = ExposureType.DOWNLOAD_COMPLETE)
ExposureManager.log(exposureEvent)
ExposureManager.commitSavedExposureEvents(forced = true)
}
@JvmStatic
fun getDownloadType(apkEntity: ApkEntity, gameId: String): DownloadType {
return if (PackageUtils.isInstalled(
HaloApp.getInstance().application,
apkEntity.packageName
)
) {
if (PackageUtils.isSignedByGh(
HaloApp.getInstance().application,
apkEntity.packageName
)
) {
if (PackageUtils.isCanUpdate(apkEntity, gameId)) {
DownloadType.PLUGIN_UPDATE
} else {
if (Version(apkEntity.version).isHigherThan(
PackageUtils.getVersionNameByPackageName(
apkEntity.packageName
)
)
) {
DownloadType.UPDATE
} else {
DownloadType.DOWNLOAD
}
}
fun getDownloadType(apkEntity: ApkEntity, method: String) : DownloadType {
return if ("更新" == method) {
if (PackageUtils.isSignature(HaloApp.getInstance().application, apkEntity.packageName)) {
DownloadType.PLUGIN_UPDATE
} else {
if (!TextUtils.isEmpty(apkEntity.ghVersion)) {
DownloadType.PLUGIN_DOWNLOAD
} else {
DownloadType.UPDATE
}
DownloadType.UPDATE
}
} else if ("插件化" == method) {
DownloadType.PLUGIN_DOWNLOAD
} else {
DownloadType.DOWNLOAD
}
}
/**
* 为游戏实体添加位置序号和上层专题 id (若存在)
*/
@JvmStatic
fun updateExposureInfo(
gameList: List<GameEntity>?,
subjectId: String? = null,
containerId: String? = null,
containerType: String? = null
) {
gameList?.let {
for ((index, game) in it.withIndex()) {
game.sequence = index
game.subjectId = subjectId
game.containerId = containerId
game.containerType = containerType
}
fun getUpdateType(apkEntity: ApkEntity) : DownloadType {
return if (PackageUtils.isSignature(HaloApp.getInstance().application, apkEntity.packageName)) {
DownloadType.PLUGIN_UPDATE
} else {
DownloadType.UPDATE
}
}

View File

@ -2,16 +2,16 @@ package com.gh.common.exposure.meta
import android.os.Parcelable
import androidx.annotation.Keep
import kotlinx.parcelize.Parcelize
import kotlinx.android.parcel.Parcelize
@Keep
@Parcelize
data class Meta(
val mac: String? = "",
val jnfj: String? = "",
val imei: String? = "",
val model: String? = "",
val manufacturer: String? = "",
val dia: String? = "",
val android_id: String? = "",
val android_sdk: Int? = -1,
val android_version: String? = "",
val network: String? = "",

View File

@ -5,17 +5,17 @@ import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import com.gh.common.constant.Constants
import com.gh.common.util.SPUtils
import com.gh.common.util.tryWithDefaultCatch
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.manager.UserManager
import com.halo.assistant.HaloApp
import com.leon.channel.helper.ChannelReaderUtil
import com.walkud.rom.checker.RomIdentifier
import java.io.File
object MetaUtil {
@ -23,28 +23,13 @@ object MetaUtil {
private var channel = ""
private var m: Meta? = null
private var imei: String? = null
private var base64EncodedImei: String? = null
private var androidId: String? = null
private var base64EncodedAndroidId: String? = null
private var romName: String? = null
private var romVersion: String? = null
fun refreshMeta() {
if (romName == null) {
tryWithDefaultCatch {
romName = RomIdentifier.getRom().name
romVersion = RomIdentifier.getRom().versionName
}
}
m = Meta(mac = null,
jnfj = getBase64EncodedIMEI(),
m = Meta(mac = getMac(),
imei = getIMEI(),
model = getModel(),
manufacturer = getManufacturer(),
dia = getBase64EncodedAndroidId(),
android_id = getAndroidId(),
android_sdk = getAndroidSDK(),
android_version = getAndroidVersion(),
network = getNetwork(),
@ -55,7 +40,7 @@ object MetaUtil {
appVersion = BuildConfig.VERSION_NAME,
userId = UserManager.getInstance().userId,
exposureVersion = BuildConfig.EXPOSURE_VERSION,
rom = romName + "" + romVersion)
rom = RomIdentifier.getRom().name + "" + RomIdentifier.getRom().versionName)
}
fun getMeta(): Meta {
@ -66,90 +51,66 @@ object MetaUtil {
}
private fun getChannel(): String? {
return HaloApp.getInstance().channel
if (TextUtils.isEmpty(channel)) {
channel = if (ChannelReaderUtil.getChannel(application) != null) ChannelReaderUtil.getChannel(application) else ""
}
return channel
}
/**
* Get MAC address
* TODO check > 6.0 results
*/
fun getMac(): String? {
var mac: String = ""
//Plan A
try {
mac = File("/sys/class/net/wlan0/address").inputStream().bufferedReader().use { it.readText() }
if (!TextUtils.isEmpty(mac)) return mac.trim()
} catch (e: Exception) {
// e.printStackTrace()
}
// Plan B
try {
mac = File("/sys/class/net/eth0/address").inputStream().bufferedReader().use { it.readText() }
if (!TextUtils.isEmpty(mac)) return mac.trim()
} catch (e: Exception) {
// e.printStackTrace()
}
// Plan C
val wifiManager = application.getSystemService(Context.WIFI_SERVICE) as WifiManager
try {
mac = wifiManager.connectionInfo.macAddress
} catch (e: Exception) {
// e.printStackTrace()
}
return mac.trim()
}
/**
* Get IMEI
*/
@JvmStatic
fun getIMEI(): String {
fun getIMEI(): String? {
if (!HaloApp.isUserAcceptPrivacyPolicy(HaloApp.getInstance().application)) {
if (application.checkCallingOrSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
return ""
}
if (imei != null) {
return imei ?: ""
}
imei = SPUtils.getString(Constants.SP_IMEI)
if (!TextUtils.isEmpty(imei)) {
return imei ?: ""
}
if (application.checkCallingOrSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return ""
}
val telephonyManager = application.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (Build.VERSION.SDK_INT >= 29) {
return "".apply {
imei = this
SPUtils.setString(Constants.SP_IMEI, this)
}
} else if (Build.VERSION.SDK_INT >= 26) {
return (telephonyManager.imei ?: "").apply {
imei = this
SPUtils.setString(Constants.SP_IMEI, this)
}
if (Build.VERSION.SDK_INT >= 26) {
return telephonyManager.imei
}
return (telephonyManager.getDeviceId() ?: "").apply {
imei = this
SPUtils.setString(Constants.SP_IMEI, this)
}
return telephonyManager.getDeviceId()
}
@JvmStatic
fun getBase64EncodedIMEI(): String {
if (imei == null) {
getIMEI()
}
if (TextUtils.isEmpty(base64EncodedImei) && imei != null) {
try {
base64EncodedImei = android.util.Base64.encodeToString(getIMEI().trim().toByteArray(), android.util.Base64.NO_WRAP)
} catch (e: java.lang.Exception) {
e.printStackTrace()
return ""
}
}
return base64EncodedImei ?: ""
}
@JvmStatic
fun getBase64EncodedAndroidId(): String {
if (androidId == null) {
getAndroidId()
}
if (TextUtils.isEmpty(base64EncodedAndroidId) && androidId != null) {
try {
base64EncodedAndroidId = android.util.Base64.encodeToString(getAndroidId().trim().toByteArray(), android.util.Base64.NO_WRAP)
} catch (e: java.lang.Exception) {
e.printStackTrace()
return ""
}
}
return base64EncodedAndroidId ?: ""
}
fun getModel(): String? {
return Build.MODEL
}
@ -158,35 +119,14 @@ object MetaUtil {
return Build.MANUFACTURER
}
@JvmStatic
fun getAndroidId(): String {
if (!HaloApp.isUserAcceptPrivacyPolicy(HaloApp.getInstance().application)) {
return ""
}
if (androidId != null) {
return androidId ?: ""
}
androidId = SPUtils.getString(Constants.SP_ANDROID_ID)
if (!TextUtils.isEmpty(androidId)) {
return androidId ?: ""
}
return try {
Settings.Secure.getString(application.contentResolver, Settings.Secure.ANDROID_ID).apply {
androidId = this
SPUtils.setString(Constants.SP_ANDROID_ID, this)
}
fun getAndroidId(): String? {
var android_id: String = ""
try {
android_id = Settings.Secure.getString(application.contentResolver, Settings.Secure.ANDROID_ID)
} catch (e: Exception) {
e.printStackTrace()
androidId = ""
SPUtils.setString(Constants.SP_ANDROID_ID, "")
""
}
return android_id
}
fun getAndroidSDK(): Int? {

View File

@ -0,0 +1,30 @@
package com.gh.common.exposure.time
import com.gh.gamecenter.entity.TimeEntity
import com.gh.gamecenter.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.schedulers.Schedulers
import kotlin.concurrent.fixedRateTimer
class Corrector {
companion object {
const val TIME_CORRECTOR_ADJUST_PERIOD: Long = 600000
}
var delta: Long = 0
init {
fixedRateTimer("TimeUtil-Corrector-Checker", initialDelay = 0, period = TIME_CORRECTOR_ADJUST_PERIOD) {
RetrofitManager.getInstance(HaloApp.getInstance().application).api.time
.subscribeOn(Schedulers.io())
.subscribe(object : Response<TimeEntity>() {
override fun onResponse(response: TimeEntity?) {
val serverTime = response?.time
serverTime?.let { delta = it * 1000 - System.currentTimeMillis() }
}
})
}
}
}

View File

@ -1,15 +1,23 @@
package com.gh.common.exposure.time
import com.gh.common.FixedRateJobHelper
object TimeUtil {
private lateinit var corrector: Corrector
fun init() {
corrector = Corrector()
}
fun currentTimeMillis(): Long {
return FixedRateJobHelper.timeDeltaBetweenServerAndClient + System.currentTimeMillis()
return corrector.delta + System.currentTimeMillis()
}
fun currentTime(): Int {
return ((FixedRateJobHelper.timeDeltaBetweenServerAndClient + System.currentTimeMillis()) / 1000).toInt()
return if (::corrector.isInitialized) {
((corrector.delta + System.currentTimeMillis()) / 1000).toInt()
} else {
(System.currentTimeMillis() / 1000).toInt()
}
}
}

View File

@ -1,21 +0,0 @@
package com.gh.common.filter
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
@Keep
data class RegionSetting(
@SerializedName("game_mirror")
var mirrorGameIdSet: HashSet<String>,
@SerializedName("game_block")
var filterGameIdSet: HashSet<String>,
@SerializedName("channel_control")
var channelControl: ChannelControl) {
@Keep
data class ChannelControl(
@SerializedName("game_category")
var gameCategory: String,
@SerializedName("effect")
var effect: Boolean)
}

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