Compare commits

..

36 Commits

Author SHA1 Message Date
1023e0492b feat: 测试插件化
Signed-off-by: chenjuntao <chenjuntao@ghzhushou.com>
2024-04-25 17:02:54 +08:00
0fda3ecfcd feat: 合规调整-已安装列表权限-2024/4/22(gitlab-ci) https://jira.shanqu.cc/browse/GHZSCY-5250
Signed-off-by: chenjuntao <chenjuntao@ghzhushou.com>
2024-04-25 11:09:55 +08:00
166abd5c9b feat: 合规调整-已安装列表权限-2024/4/22 https://jira.shanqu.cc/browse/GHZSCY-5250
Signed-off-by: chenjuntao <chenjuntao@ghzhushou.com>
2024-04-25 11:08:52 +08:00
af3102f6be feat: 合规调整-已安装列表权限-2024/4/22 https://jira.shanqu.cc/browse/GHZSCY-5250
Signed-off-by: chenjuntao <chenjuntao@ghzhushou.com>
2024-04-25 10:11:45 +08:00
93363f23b4 feat: 合规调整-已安装列表权限-2024/4/22 https://jira.shanqu.cc/browse/GHZSCY-5250
Signed-off-by: chenjuntao <chenjuntao@ghzhushou.com>
2024-04-24 16:15:31 +08:00
a552677e41 Merge branch 'chen/202404/GHZSCY-5187-2' into 'dev'
style:匹配按钮设计规范...

See merge request halo/android/assistant-android!1645
2024-04-24 16:12:37 +08:00
bb148f42b8 style:匹配按钮设计规范 https://jira.shanqu.cc/browse/GHZSCY-5187?focusedCommentId=61918&page=com.atlassian.jira.plugin.system.issuetabpanels%253Acomment-tabpanel#comment-61918 2024-04-24 16:09:44 +08:00
065aa96e18 Merge branch 'fix/GHZSCY-5236' into 'dev'
fix: 多渠道多版本-首次启动跳转问题 https://jira.shanqu.cc/browse/GHZSCY-5236

See merge request halo/android/assistant-android!1640
2024-04-24 11:43:36 +08:00
d9a90ca80b fix: 多渠道多版本-首次启动跳转问题 https://jira.shanqu.cc/browse/GHZSCY-5236 2024-04-24 11:10:39 +08:00
2aeffb1cc4 Merge branch 'chen/202404/GHZSCY-5187' into 'dev'
style:匹配按钮设计规范...

See merge request halo/android/assistant-android!1644
2024-04-23 17:47:19 +08:00
d3188cc3cd style:匹配按钮设计规范 https://jira.shanqu.cc/browse/GHZSCY-5187?focusedCommentId=61918&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-61918 2024-04-23 17:42:52 +08:00
1d7f902a81 feat: 移除一键登录 SDK 依赖 (移除相关无用的资源)
Signed-off-by: chenjuntao <chenjuntao@ghzhushou.com>
2024-04-23 16:19:59 +08:00
13a40806e4 Merge branch 'fix/GHZS-5009' into 'dev'
fix: 插件问题反馈内容默认文案出错 https://jira.shanqu.cc/browse/GHZS-5009

See merge request halo/android/assistant-android!1637
2024-04-23 15:04:29 +08:00
b56e5c4022 Merge branch 'feat/GHZS-5188' into 'dev'
feat: 调整客户端用到的部分域名(同时移除已经从未上线的光能部分相关代码) https://jira.shanqu.cc/browse/GHZS-5188

See merge request halo/android/assistant-android!1638
2024-04-23 15:04:21 +08:00
acca1537da Merge branch 'feat/optimise_package_privacy' into 'dev'
feat: 移除一键登录 SDK 依赖

See merge request halo/android/assistant-android!1642
2024-04-23 15:04:12 +08:00
6e5b639d58 feat: 调整客户端用到的部分域名(同时移除已经从未上线的光能部分相关代码) https://jira.shanqu.cc/browse/GHZS-5188 2024-04-23 14:43:10 +08:00
24000f55af feat: 移除一键登录 SDK 依赖 2024-04-22 17:56:04 +08:00
3540c4626d Merge branch 'fix/update_crash' into 'dev'
fix: 修复软更时更新弹窗回到桌面由于下载监听移除不及时导致的闪退问题

See merge request halo/android/assistant-android!1636
2024-04-22 15:34:30 +08:00
e6a2758fdb fix: 修复软更时更新弹窗回到桌面由于下载监听移除不及时导致的闪退问题 2024-04-22 15:08:02 +08:00
a56e2bd16e Merge remote-tracking branch 'origin/release' into dev
# Conflicts:
#	dependencies.gradle
2024-04-22 14:01:25 +08:00
e038c565ff Merge branch 'hotfix/v5.34.8-1038/authorization_crash' into 'release'
fix: 修复通用授权登陆界面出现的闪退问题...

See merge request halo/android/assistant-android!1635
2024-04-22 13:57:42 +08:00
ec5905bb11 fix: 修复通用授权登陆界面出现的闪退问题 https://sentry.shanqu.cc/organizations/lightgame/issues/373879/events/b72b2eb3c7ef4426ba8d42ff5a476bbe/?project=22 2024-04-22 13:49:47 +08:00
21f50c4eed Merge branch 'hotfix/v5.34.8-1038/optional_update_crash' into 'release'
fix: 修复软更时取消弹窗切换页面后有机率触发闪退的问题 https://sentry.shanqu.cc/organizations/lightgame/issues/380566

See merge request halo/android/assistant-android!1634
2024-04-22 11:42:21 +08:00
5a93f3671b fix: 修复软更时取消弹窗切换页面后有机率触发闪退的问题 https://sentry.shanqu.cc/organizations/lightgame/issues/380566 2024-04-22 11:04:57 +08:00
6dcb8b6efe Merge branch 'fix/GHZSCY-5244' into 'dev'
fix:【光环助手】5.35验收问题:极光推送触发了APP角标提示,但不能消除 https://jira.shanqu.cc/browse/GHZSCY-5244

See merge request halo/android/assistant-android!1633
2024-04-19 18:06:48 +08:00
d60916b3bc fix:【光环助手】5.35验收问题:极光推送触发了APP角标提示,但不能消除 https://jira.shanqu.cc/browse/GHZSCY-5244 2024-04-19 18:06:48 +08:00
798b19d9d7 Merge branch 'feat/remove_useless_activity' into 'dev'
feat: 移除已被弃用的 activity 及其相关的代码 (没有依赖、非通用跳转、已无入口等)

See merge request halo/android/assistant-android!1632
2024-04-19 16:14:12 +08:00
5c47d3cda8 feat: 移除已被弃用的 activity 及其相关的代码 (没有依赖、非通用跳转、已无入口等) 2024-04-19 16:14:12 +08:00
aea64c0602 Merge branch 'fix/GHZSCY-5231' into 'dev'
fix:【光环助手】轮播banner刷新时蒙层消失 https://jira.shanqu.cc/browse/GHZSCY-5231

See merge request halo/android/assistant-android!1631
2024-04-18 17:48:51 +08:00
4abc0a3edb fix:【光环助手】轮播banner刷新时蒙层消失 https://jira.shanqu.cc/browse/GHZSCY-5231 2024-04-18 17:48:50 +08:00
ded940412e Merge branch 'feat/remove_useless_dependencies' into 'dev'
feat: 移除无用依赖

See merge request halo/android/assistant-android!1630
2024-04-18 13:59:24 +08:00
9971651fe1 feat: 移除无用依赖
Signed-off-by: chenjuntao <chenjuntao@ghzhushou.com>
2024-04-18 13:53:25 +08:00
4e00b5db19 chore: 版本更新至 5.34.8 2024-04-17 15:59:16 +08:00
e6a6bbcf97 Merge branch 'feat/GHZS-5229' into 'release'
chore: 神策 SDK 更新至 6.8.0

See merge request halo/android/assistant-android!1629
2024-04-17 15:58:35 +08:00
0eecc4699f chore: 神策 SDK 更新至 6.8.0 2024-04-17 15:56:04 +08:00
920e7a8038 fix: 插件问题反馈内容默认文案出错 https://jira.shanqu.cc/browse/GHZS-5009
Signed-off-by: chenjuntao <chenjuntao@ghzhushou.com>
2024-03-21 10:07:14 +08:00
227 changed files with 2246 additions and 8664 deletions

4
.gitignore vendored
View File

@ -9,6 +9,4 @@ build/
release-app/
test-app/
scripts/apk-channel/
app/src/test/java/com/gh/gamecenter
app/src/main/assets-debug/
app/src/main/assets-release/
app/src/test/java/com/gh/gamecenter

View File

@ -71,7 +71,7 @@ android_build:
exit_codes: 137
only:
- dev
- release
- feat/GHZSCY-5250
# 代码检查
sonarqube_analysis:
@ -152,4 +152,4 @@ oss-upload&send-email:
- /usr/local/bin/python /ci-android-mail-jira-comment.py
only:
- dev
- release
- feat/GHZSCY-5250

6
.gitmodules vendored
View File

@ -5,12 +5,6 @@
[submodule "vspace-bridge"]
path = vspace-bridge
url = ../../../cwzs/android/vspace-bridge.git
[submodule "module_common/src/debug/assets/assistant-android-mock"]
path = module_common/src/debug/assets/assistant-android-mock
url = ../../../halo/android/assistant-android-mock.git
[submodule "ndownload"]
path = ndownload
url = ../../../android/ndownload.git
[submodule "vasdk"]
path = vasdk
url = ../../../sdg/android/vasdk.git

View File

@ -75,7 +75,7 @@ android {
versionName rootProject.ext.versionName
applicationId rootProject.ext.applicationId
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt', 'proguard-fresco.txt', rootProject.ext.va_proguard_rules
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt', 'proguard-fresco.txt'
String CORE_EVENT_GAME_CATEGORY = ""
@ -164,15 +164,6 @@ android {
flavorDimensions("env", "region")
sourceSets {
debug {
assets.srcDirs += 'src/main/assets-debug'
}
release {
assets.srcDirs += 'src/main/assets-release'
}
publish {
java.srcDirs = ['src/main/java', "src/default/java"]
}
@ -354,8 +345,6 @@ dependencies {
})
implementation "com.github.CarGuo.GSYVideoPlayer:gsyVideoPlayer-exo_player2:$gsyVideo"
// implementation "androidx.work:work-runtime:${workManager}"
implementation "com.llew.huawei:verifier:${verifier}"
teaImplementation "com.bytedance.applog:RangersAppLog-Lite-cn:${bytedanceApplog}"
@ -368,8 +357,6 @@ dependencies {
implementation "com.lg:easyfloat:${easyFloat}"
implementation "io.github.florent37:shapeofview:${shapeOfView}"
implementation "com.lg:apksig:${apksig}"
implementation "com.lg:gid:${gid}"
@ -381,9 +368,9 @@ dependencies {
kapt "com.alibaba:arouter-compiler:$arouterVersion"
implementation project(':ndownload')
implementation project(':vspace-bridge')
implementation project(':vspace-bridge:vspace')
implementation(project(':module_common')) {
implementation (project(':module_common')) {
exclude group: 'androidx.swiperefreshlayout'
}
implementation(project(':module_login')) {
@ -428,15 +415,6 @@ dependencies {
implementation(pushProject) {
exclude group: 'androidx.swiperefreshlayout'
}
implementation(project(":va-lib"))
implementation(project(':va-main')) {
exclude group: 'androidx.swiperefreshlayout'
}
debugImplementation "com.bytedance.tools.codelocator:codelocator-core:2.0.3"
compileOnly project(":va-core")
compileOnly project(":va-plugin-host-lib")
implementation project(":va-plugin-host")
implementation project(":va-archive")
}
File propFile = file('sign.properties')

View File

@ -1,85 +1,32 @@
package com.gh.vspace
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.Keep
import com.gh.gamecenter.R
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.LayoutPersonalOtherItemBinding
import com.gh.vspace.installexternalgames.InstallExternalGameActivity
import com.lg.vspace.VaApp
import com.lg.vspace.plugin.host.PluginHelper
import com.lightgame.utils.Utils
import com.lightgame.utils.toast.ToastHelper
import com.lody.virtual.client.core.VirtualCore
import java.io.File
@Keep
class ExternalGameUsage : ITestCase {
private fun buttonTemplate(viewParent: ViewGroup, id: Int, fn: (LayoutPersonalOtherItemBinding) -> Unit) {
class ExternalGameUsage : IExternalGamesUsage {
override fun addInstallExternalGameButton(viewParent: ViewGroup) {
val context = viewParent.context
viewParent.findViewById<View>(id) ?: run {
viewParent.findViewById<View>(R.id.install_game_from_external) ?: run {
val binding = LayoutPersonalOtherItemBinding.inflate(LayoutInflater.from(context)).apply {
root.id = id
fn(this)
root.id = R.id.install_game_from_external
titleTv.text = context.getString(R.string.title_install_external_game)
iconIv.setImageResource(R.drawable.ic_personal_my_game)
root.setOnClickListener {
VHelper.connectService {
context.startActivity(
InstallExternalGameActivity.getIntent(context)
.apply { flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK })
}
}
}
viewParent.addView(binding.root, 0)
}
}
override fun addInstallExternalGameButton(viewParent: ViewGroup) {
val context = viewParent.context
buttonTemplate(viewParent, R.id.install_game_from_external) {
it.titleTv.text = context.getString(R.string.title_install_external_game)
it.iconIv.setImageResource(R.drawable.ic_personal_my_game)
it.root.setOnClickListener {
VHelper.connectService {
context.startActivity(
InstallExternalGameActivity.getIntent(context).apply { flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK })
}
}
}
}
override fun addInstallPluginButton(viewParent: ViewGroup) {
buttonTemplate(viewParent, R.id.install_plugin) {
it.titleTv.text = "安装64位插件"
it.root.setOnClickListener {
val file = File("/data/local/tmp/gh-plugins/artifacts.zip")
if (file.exists()) {
Utils.log(VHelper.LOG_TAG, "有本地更新文件: 64位插件")
PluginHelper.getInstance().updatePlugin(file, VHelper.getCwBaseLogParams())
} else {
ToastUtils.showToast("data/local/tmp没有push文件")
}
}
}
}
override fun addInstallPlugin32Button(viewParent: ViewGroup) {
buttonTemplate(viewParent, R.id.install_plugin_32) {
it.titleTv.text = "安装32位插件"
it.root.setOnClickListener {
val file = File("/data/local/tmp/gh-plugins/artifacts32.zip")
if (file.exists()) {
Utils.log(VHelper.LOG_TAG, "有本地更新文件: 32位插件")
VirtualCore.get().updatePlugin(file.absolutePath, "artifacts32.zip",
VHelper.getCwBaseLogParams().let {
val bundle = Bundle()
for ((key, value) in it) {
bundle.putString(key, value)
}
bundle
})
} else {
ToastUtils.showToast("data/local/tmp没有push文件")
}
}
}
}
}

View File

@ -25,11 +25,6 @@ class ExternalGameAdapter(private val games: List<ExternalGameUiState>, private
路径:${item.apkPath}
""".trimIndent()
}
holder.update.setOnClickListener {
onItemClickListener.onItemClick(item, OnItemClickListener.ClickType.CLICK_INSTALL)
}
holder.install.goneIf(item.isInstalled) {
holder.install.setOnClickListener {
onItemClickListener.onItemClick(item, OnItemClickListener.ClickType.CLICK_INSTALL)

View File

@ -8,5 +8,4 @@ class ExternalGameViewHolder(binding: LayoutExternalGameItemBinding) : RecyclerV
val install = binding.btnInstall
val uninstall = binding.btnUninstall
val start = binding.btnStart
val update = binding.btnUpdate
}

View File

@ -16,7 +16,6 @@ import com.gh.gamecenter.databinding.FragmentInstallExternalGamesBinding
import com.gh.vspace.VHelper
import com.halo.assistant.HaloApp
import com.lg.vspace.VirtualAppManager
import com.lightgame.download.DownloadEntity
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
@ -106,15 +105,6 @@ class InstallExternalGameFragment : ToolbarFragment(), OnItemClickListener {
private fun install(externalGameUiState: ExternalGameUiState) {
val bit =
externalGameUiState.externalGameEntity.cpuAbi.let { if (it.size == 1 && it.contains("armeabi-v7a")) "32" else "64" }
VHelper.install(requireContext(), DownloadEntity().apply {
externalGameUiState.externalGameEntity.apply {
packageName = apkPackageName
path = apkPath
}
}, true)
if (VHelper.showDialogIfVSpaceIsNeeded(
requireContext(),
"",
@ -154,9 +144,7 @@ class InstallExternalGameFragment : ToolbarFragment(), OnItemClickListener {
com.gh.gamecenter.BuildConfig.VERSION_NAME,
HaloApp.getInstance().channel,
"",
"",
com.lg.core.BuildConfig.VERSION_NAME,
HaloApp.getInstance().oaid
""
)
requireActivity().startActivity(intent)
}

View File

@ -24,14 +24,6 @@
android:visibility="gone"
tools:visibility="visible" />
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text_update"
android:visibility="visible"
tools:visibility="visible" />
<Button
android:id="@+id/btn_uninstall"
android:layout_width="wrap_content"

View File

@ -1,6 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="install_game_from_external" type="id" />
<item name="install_plugin" type="id" />
<item name="install_plugin_32" type="id" />
</resources>

View File

@ -2,7 +2,6 @@
<resources>
<string name="title_install_external_game">从SD卡安装</string>
<string name="text_install">安装</string>
<string name="text_update">更新</string>
<string name="text_uninstall">卸载</string>
<string name="text_start">启动</string>
</resources>

View File

@ -11,6 +11,12 @@
<package android:name="com.lg.vspace" />
</queries>
<!-- 华为/荣耀角标 -->
<uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE "/>
<uses-permission android:name="com.hihonor.android.launcher.permission.CHANGE_BADGE" />
<!-- vivo角标 -->
<uses-permission android:name="com.vivo.notification.permission.BADGE_ICON" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<!-- 允许应用程序访问网络连接 -->
@ -86,30 +92,7 @@
com.tencent.qqmini,
com.tencent.qqmini.minigame.external,
com.tencent.qqmini.minigame.opensdk,
com.tencent.qqmini.union.ad,
com.lg.vspace,
io.lg.va.common,
com.va.floating,
com.lg.cloud,
com.lg.archive,
com.lg.vclient,
com.va.realname,
com.lg.vspace.flavor,
com.lg.update,
com.lg.login,
com.lg.accelerator,
com.lody.virtual,
com.lg.core,
com.lg.ads,
com.lg.common,
com.lg.vspace.network,
com.lody.virtual.lib.res,
com.va.host,
com.lg.vspace.plugin.host,
com.lg.plugin.constant,
com.bytedance.tools.codelocator,
org.chickenhook.restrictionbypass,
com.lody.virtual.sandhook,com.lg.vspace.common" />
com.tencent.qqmini.union.ad" />
<!-- 去掉 SDK 一些流氓权限 -->
<uses-permission
@ -340,14 +323,6 @@
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="com.gh.gamecenter.qa.answer.detail.AnswerDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.answer.edit.AnswerEditActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.InfoActivity"
android:screenOrientation="portrait" />
@ -356,10 +331,6 @@
android:name=".qa.questions.invite.QuestionsInviteActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.myqa.MyAskActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.questions.edit.QuestionEditActivity"
android:screenOrientation="portrait" />
@ -397,10 +368,6 @@
android:name="com.gh.gamecenter.qa.article.edit.ArticleEditActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.article.MyArticleActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.qa.article.draft.ArticleDraftActivity"
android:screenOrientation="portrait" />
@ -439,10 +406,6 @@
android:name="com.gh.gamecenter.history.HistoryActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.personalhome.rating.RatingActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.gamedetail.rating.logs.CommentLogsActivity"
android:screenOrientation="portrait" />
@ -515,9 +478,6 @@
android:name=".gamedetail.fuli.kaifu.ServersSubscribedGameListActivity"
android:screenOrientation="portrait" />
<activity
android:name=".qa.answer.draft.AnswerDraftActivity"
android:screenOrientation="portrait" />
<activity
android:name=".gamedetail.rating.RatingFoldActivity"
android:screenOrientation="portrait" />
@ -529,10 +489,6 @@
android:name=".video.poster.PosterEditActivity"
android:screenOrientation="portrait" />
<activity
android:name=".video.poster.PosterClipActivity"
android:screenOrientation="portrait" />
<activity
android:name=".forum.detail.ForumDetailActivity"
android:screenOrientation="portrait" />
@ -827,8 +783,7 @@
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />

View File

@ -6,8 +6,6 @@
<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;">
@ -15,8 +13,5 @@
<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>
</html>

View File

@ -34,18 +34,18 @@ try {
var script = document.createElement("script")
document.body.appendChild(script)
if (isDebug) {
script.src = "https://resource.ghzs.com/js/halo_app_test.js" + "?timestamp=" + Math.round(new Date().getTime() / 1000)
script.src = "https://dev-and-static.ghzs66.com/web/js/halo.js" + "?timestamp=" + Math.round(new Date().getTime() / 1000)
} else {
script.src = "https://resource.ghzs.com/js/halo.js" + "?timestamp=" + Math.round(new Date().getTime() / 1000 / 1000)
script.src = "https://and-static.ghzs66.com/web/js/halo.js" + "?timestamp=" + Math.round(new Date().getTime() / 1000 / 1000)
}
var style = document.createElement("link")
style.rel = "stylesheet"
style.type = "text/css"
if (isDebug) {
style.href = "https://resource.ghzs.com/css/halo_app_test.css" + "?timestamp=" + Math.round(new Date().getTime() / 1000)
style.href = "https://dev-and-static.ghzs66.com/web/css/halo.css" + "?timestamp=" + Math.round(new Date().getTime() / 1000)
} else {
style.href = "https://resource.ghzs.com/css/halo.css" + "?timestamp=" + Math.round(new Date().getTime() / 1000 / 1000)
style.href = "https://and-static.ghzs66.com/web/css/halo.css" + "?timestamp=" + Math.round(new Date().getTime() / 1000 / 1000)
}
document.head.appendChild(style)

View File

@ -203,10 +203,6 @@ object AdDelegateHelper {
return mDownloadManagerAd != null && !isMatchAdFreeRule(mDownloadManagerAd) && isMatchDownloadManagerAdDisplayRule()
}
fun shouldShowHelperLaunchAd(): Boolean {
return mVGameLaunchAd != null && !isMatchAdFreeRule(mVGameLaunchAd) && isMatchAdDisplayRule(mVGameLaunchAd, Constants.SP_LAST_HELPER_LAUNCH_AD_SHOW_TIME)
}
/**
* 是否需要显示游戏搜索广告
*/
@ -251,11 +247,10 @@ object AdDelegateHelper {
/**
* 是否大于广告管理展示间隔时长
*/
private fun isMatchDownloadManagerAdDisplayRule(): Boolean = isMatchAdDisplayRule(mDownloadManagerAd, Constants.SP_LAST_DOWNLOAD_MANAGER_AD_SHOW_TIME)
private fun isMatchAdDisplayRule(adConfig: AdConfig?, spKey: String): Boolean {
adConfig?.displayRule?.run {
private fun isMatchDownloadManagerAdDisplayRule(): Boolean {
mDownloadManagerAd?.displayRule?.run {
if (adDisplayInterval > 0) {
val lastShowTime = SPUtils.getLong(spKey, 0L)
val lastShowTime = SPUtils.getLong(Constants.SP_LAST_DOWNLOAD_MANAGER_AD_SHOW_TIME, 0L)
val durationInMinutes = (System.currentTimeMillis() - lastShowTime).toFloat() / 1000 / 60
return durationInMinutes > adDisplayInterval
} else {

View File

@ -1,44 +0,0 @@
package com.gh.ad
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.lg.vspace.ui.launcher.ILaunchAd
@Route(path = RouteConsts.provider.vaAd, name = "畅玩启动页广告")
class LaunchAdImpl : ILaunchAd {
override fun init(context: Context?) {
}
override fun requestAd(fragment: Fragment, container: ViewGroup, maskView: View) {
if (AdDelegateHelper.shouldShowHelperLaunchAd()) {
val launchAd = AdDelegateHelper.vGameLaunchAd
val showThirdPartyAd = launchAd?.displayRule?.adSource == AdDelegateHelper.AD_TYPE_SDK
val thirdPartyAd = launchAd?.thirdPartyAd
if (showThirdPartyAd && thirdPartyAd != null) {
AdDelegateHelper.requestThirdPartyBannerAd(
fragment,
container,
thirdPartyAd,
DisplayUtils.getScreenWidthInDp(fragment.requireActivity()),
) { isSuccess ->
maskView.goneIf(!isSuccess)
if (isSuccess) {
SPUtils.setLong(Constants.SP_LAST_HELPER_LAUNCH_AD_SHOW_TIME, System.currentTimeMillis())
}
}
}
}
}
}

View File

@ -4,6 +4,7 @@ import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.ad.AdDelegateHelper
import com.gh.common.util.FloatingBackViewManager
import com.gh.common.xapk.XapkInstaller
@ -14,12 +15,11 @@ import com.gh.gamecenter.SplashAdActivity
import com.gh.gamecenter.SplashScreenActivity
import com.gh.gamecenter.authorization.AuthorizationActivity
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.PackageFlavorHelper
import com.gh.gamecenter.feedback.view.suggest.SuggestionActivity
import com.gh.gamecenter.login.view.LoginActivity
import com.gh.gamecenter.core.provider.IPushProvider
import com.gh.vspace.VHelper
import com.halo.assistant.HaloApp
import com.lg.vspace.ui.launcher.LaunchActivity
// TODO移动到对应的模块
class GlobalActivityLifecycleObserver : Application.ActivityLifecycleCallbacks {
@ -40,7 +40,6 @@ class GlobalActivityLifecycleObserver : Application.ActivityLifecycleCallbacks {
&& activity !is SkipActivity
&& activity !is AuthorizationActivity
&& activity !is SplashAdActivity
&& activity !is SuggestionActivity
) {
activity.startActivity(SplashAdActivity.getIntent(activity))
}
@ -77,8 +76,6 @@ class GlobalActivityLifecycleObserver : Application.ActivityLifecycleCallbacks {
}
if (activity is AppCompatActivity
&& activity !is LaunchActivity
&& activity !is LoginActivity
&& activity !is SplashScreenActivity
&& activity !is SkipActivity
&& activity !is AuthorizationActivity
@ -87,6 +84,10 @@ class GlobalActivityLifecycleObserver : Application.ActivityLifecycleCallbacks {
}
XapkInstaller.updateCurrentInstallStatus()
// 清除桌面角标
val pushProvider = ARouter.getInstance().build(RouteConsts.provider.push).navigation() as? IPushProvider
pushProvider?.cleanBadgeNumber(activity.applicationContext)
}
override fun onActivityPaused(activity: Activity) {

View File

@ -45,7 +45,6 @@ import com.gh.gamecenter.login.user.LoginTag
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserRepository
import com.gh.gamecenter.login.utils.LoginHelper
import com.gh.gamecenter.login.utils.QuickLoginHelper
import com.gh.gamecenter.login.view.LoginActivity
import com.gh.gamecenter.personalhome.border.AvatarBorderActivity
import com.gh.gamecenter.setting.SettingBridge
@ -130,12 +129,12 @@ class DefaultJsApi(
@JavascriptInterface
fun login(msg: Any) {
if (SPUtils.getBoolean(Constants.SP_HAS_GET_PHONE_INFO) || NetworkUtils.isOpenMobileData(context)) {
QuickLoginHelper.startLogin(context, "浏览器")
} else {
// if (SPUtils.getBoolean(Constants.SP_HAS_GET_PHONE_INFO) || NetworkUtils.isOpenMobileData(context)) {
// QuickLoginHelper.startLogin(context, "浏览器")
// } else {
val intent = LoginActivity.getIntent(context, "浏览器")
context.startActivity(intent)
}
// }
}
@JavascriptInterface
@ -220,7 +219,7 @@ class DefaultJsApi(
runOnUiThread {
// 若畅玩列表中安装了,优先启动畅玩游戏
if (VHelper.isInstalled(packageName)) {
VHelper.validateVSpaceBeforeAction(context, packageName, null) {
if (!VHelper.showDialogIfVSpaceIsNeeded(context, "", "", "", "")) {
VHelper.launch(context, packageName)
}
} else {

View File

@ -16,7 +16,7 @@ class ValidateVSpaceHandler : DownloadChainHandler() {
}
if (asVGame) {
VHelper.validateVSpaceBeforeAction(context,gameEntity.getUniquePackageName(), gameEntity) {
VHelper.validateVSpaceBeforeAction(context, gameEntity) {
closure.invoke()
}
} else {

View File

@ -21,17 +21,14 @@ import com.gh.gamecenter.common.utils.EnvHelper;
import com.gh.gamecenter.core.utils.GsonUtils;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.entity.AppEntity;
import com.gh.gamecenter.entity.GameGuidePopupEntity;
import com.gh.gamecenter.entity.NewApiSettingsEntity;
import com.gh.gamecenter.entity.NewSettingsEntity;
import com.gh.gamecenter.entity.VNewSetting;
import com.gh.gamecenter.entity.VSetting;
import com.gh.gamecenter.feature.entity.SettingsEntity;
import com.gh.gamecenter.feature.entity.SimulatorEntity;
import com.gh.gamecenter.feature.utils.ContentBlockedHelper;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.gamecenter.retrofit.service.VApiService;
import com.gh.vspace.VHelper;
import com.halo.assistant.HaloApp;
@ -42,12 +39,8 @@ import org.json.JSONObject;
import java.io.IOException;
import java.util.Locale;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.BehaviorSubject;
import okhttp3.ResponseBody;
public class Config {
@ -64,8 +57,7 @@ public class Config {
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;
// http://www.ghzs666.com/article/${articleId}.html
public static final String URL_ARTICLE = "http://www.ghzs666.com/article/"; // ghzs/ghzs666 统一
public static final String URL_ARTICLE = "www.ghzs666.com/article/"; // ghzs/ghzs666 统一
private static final String SETTINGS_KEY = "settingsKey";
@ -76,10 +68,6 @@ public class Config {
private static NewApiSettingsEntity.NightMode mNightModeSetting;
private static SimulatorEntity mNewSimulatorEntity;
private static VSetting mVSetting;
private static VNewSetting mVNewSetting;
private static AppEntity mNew32UpdateEntity;
public static BehaviorSubject<VNewSetting> vNewSettingSubject = BehaviorSubject.create();
private static GameGuidePopupEntity mGameGuidePopupEntity;
private static SharedPreferences mDefaultSharedPreferences;
@ -106,8 +94,7 @@ public class Config {
getPreferences().edit().putString(SETTINGS_KEY, GsonUtils.toJson(settingsEntity)).apply();
mSettingsEntity = settingsEntity;
// 加载完设置后刷新下
PackageHelper.initList();
PackageHelper.refreshList();
}
@Nullable
@ -208,27 +195,6 @@ public class Config {
return mVSetting;
}
@Nullable
public static VNewSetting getVNewSettingEntity() {
if (mVNewSetting == null) {
try {
String json = SPUtils.getString(Constants.SP_V_NEW_SETTINGS);
if (!TextUtils.isEmpty(json)) {
mVNewSetting = GsonUtils.fromJson(json, VNewSetting.class);
vNewSettingSubject.onNext(mVNewSetting);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return mVNewSetting;
}
@Nullable
public static AppEntity getNew32UpdateEntity() {
return mNew32UpdateEntity;
}
/**
* 请求网络数据,尝试刷新畅玩相关配置
*/
@ -249,36 +215,6 @@ public class Config {
});
}
@SuppressLint("CheckResult")
public static void getNewSetting() {
VApiService vApi = RetrofitManager.getInstance().getVApi();
vApi.getNewSettings(BuildConfig.VERSION_NAME, Build.VERSION.SDK_INT).flatMap(new Function<VNewSetting, SingleSource<AppEntity>>() {
@Override
public SingleSource<AppEntity> apply(VNewSetting data) throws Exception {
mVNewSetting = data;
vNewSettingSubject.onNext(mVNewSetting);
SPUtils.setString(Constants.SP_V_NEW_SETTINGS, GsonUtils.toJson(data));
if (data.getVa() != null && data.getVa().getArch32() != null) {
String versionNameByPackageName = PackageUtils.getVersionNameByPackageName(data.getVa().getArch32().getPackageName());
return vApi.getNewPackageUpdate(
BuildConfig.VERSION_NAME,
versionNameByPackageName != null ? versionNameByPackageName : "",
HaloApp.getInstance().getChannel()
);
}
return Single.error(new IllegalStateException("VNewSetting entity is not expected"));
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BiResponse<AppEntity>() {
@Override
public void onSuccess(AppEntity data) {
mNew32UpdateEntity = data;
}
});
}
@Nullable
public static GameGuidePopupEntity getGameGuidePopupEntity() {
return mGameGuidePopupEntity;
@ -333,7 +269,6 @@ public class Config {
});
refreshVSettingEntity();
getNewSetting();
RetrofitManager.getInstance()
.getApi().getGameGuidePopup(Build.MANUFACTURER, Build.VERSION.RELEASE, Build.MODEL, channel, BuildConfig.VERSION_NAME)

View File

@ -19,6 +19,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DirectUtils
import com.gh.common.util.LogUtils
import com.gh.common.util.PackageHelper
import com.gh.common.util.PackageUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
@ -59,7 +60,7 @@ class PackageCheckDialogFragment : BaseDialogFragment() {
private val mDuration = 3000
private var mDisposable: Disposable? = null
private var mAdapter: PackageCheckAdapter? = null
private var mAllInstalledPackages = PackageUtils.getInstalledPackages(HaloApp.getInstance().application, 0)
private var mAllInstalledPackages = PackageHelper.getInstalledPackages(HaloApp.getInstance().application, 0)
var gameEntity: GameEntity? = null
var callBack: ConfirmListener? = null
@ -325,7 +326,7 @@ class PackageCheckDialogFragment : BaseDialogFragment() {
override fun onResume() {
super.onResume()
mAllInstalledPackages = PackageUtils.getInstalledPackages(HaloApp.getInstance().application, 0)
mAllInstalledPackages = PackageHelper.getInstalledPackages(HaloApp.getInstance().application, 0)
gameEntity?.packageDialog?.let {
if (isAllPackageInstalled(mAllInstalledPackages, it)) {
callBack?.onConfirm()
@ -363,7 +364,7 @@ class PackageCheckDialogFragment : BaseDialogFragment() {
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(busFour: EBPackage) {
if (busFour.isInstalledOrUninstalled()) {
mAllInstalledPackages = PackageUtils.getInstalledPackages(HaloApp.getInstance().application, 0)
mAllInstalledPackages = PackageHelper.getInstalledPackages(HaloApp.getInstance().application, 0)
mAdapter?.notifyDataSetChanged()
}
}
@ -416,7 +417,7 @@ class PackageCheckDialogFragment : BaseDialogFragment() {
return
}
val allInstalledPackages = PackageUtils.getInstalledPackages(HaloApp.getInstance().application, 0)
val allInstalledPackages = PackageHelper.getInstalledPackages(HaloApp.getInstance().application, 0)
if (isAllPackageInstalled(allInstalledPackages, packageDialogEntity)) {
callBack.onConfirm()
return

View File

@ -8,7 +8,6 @@ import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.core.provider.IAppProvider
import com.gh.gamecenter.core.provider.IFlavorProvider
import com.halo.assistant.HaloApp
import com.va.host.HostUtils
@Route(path = RouteConsts.provider.app, name = "Application暴露服务")
class AppProviderImpl : IAppProvider {
@ -87,6 +86,4 @@ class AppProviderImpl : IAppProvider {
override fun setSkippingThirdParty(isSkippingThirdParty: Boolean) {
HaloApp.getInstance().isSkippingThirdParty = isSkippingThirdParty
}
override fun getPluginVersion(): String = HostUtils.getPluginVersion()
}

View File

@ -22,34 +22,6 @@ class DirectProviderImpl : IDirectProvider {
DirectUtils.directToQqConversation(context, qq)
}
override fun directToCommodityDetail(context: Context, commodityId: String) {
DirectUtils.directToCommodityDetail(context, commodityId)
}
override fun directToEnergyRecord(context: Context) {
DirectUtils.directToEnergyRecord(context)
}
override fun directToEnergyRulePage(context: Context) {
DirectUtils.directToEnergyRulePage(context)
}
override fun directToInviteFriends(context: Context) {
DirectUtils.directToInviteFriends(context)
}
override fun directToExchangeRulePage(context: Context) {
DirectUtils.directToExchangeRulePage(context)
}
override fun directToExchangeCommodityPage(context: Context) {
DirectUtils.directToExchangeCommodityPage(context)
}
override fun directToLotteryParadisePage(context: Context) {
DirectUtils.directToLotteryParadisePage(context)
}
override fun directDouyin(context: Context, userId: String) {
DirectUtils.directDouyin(context, userId)
}
@ -97,26 +69,6 @@ class DirectProviderImpl : IDirectProvider {
DirectUtils.directToAmway(context, fixedTopAmwayCommentId, entrance, path)
}
override fun directToOrderCenter(context: Context) {
DirectUtils.directToOrderCenter(context)
}
override fun directToOrderDetail(context: Context, orderId: String) {
DirectUtils.directToOrderDetail(context, orderId)
}
override fun directToEnergyRecord(context: Context, position: Int) {
DirectUtils.directToEnergyRecord(context, position)
}
override fun directToMyPrizePage(context: Context) {
DirectUtils.directToMyPrizePage(context)
}
override fun directToWinOrderDetail(context: Context, orderId: String, activityId: String) {
DirectUtils.directToWinOrderDetail(context, orderId, activityId)
}
override fun directToQGame(context: Context) {
return DirectUtils.directToQGameHome(context)
}

View File

@ -3,6 +3,7 @@ package com.gh.common.provider
import android.content.Context
import android.content.pm.PackageInfo
import com.alibaba.android.arouter.facade.annotation.Route
import com.gh.common.util.PackageHelper
import com.gh.common.util.PackageUtils
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.core.provider.IPackageUtilsProvider
@ -23,7 +24,7 @@ class PackageUtilsProviderImpl : IPackageUtilsProvider {
}
override fun getInstalledPackages(context: Context, flag: Int): List<PackageInfo> {
return PackageUtils.getInstalledPackages(context, flag)
return PackageHelper.getInstalledPackages(context, flag)
}
override fun getApkSignatureByPackageName(context: Context, packageName: String): Array<String> {
@ -38,6 +39,10 @@ class PackageUtilsProviderImpl : IPackageUtilsProvider {
return PackageUtils.isSignedByGh(context, packageName)
}
override fun isInstalledWithLauncherIcon(context: Context, packageName: String): Boolean {
return PackageUtils.isInstalled(context, packageName)
}
override fun getInstalledTime(context: Context, packageName: String): Long {
return PackageUtils.getInstalledTime(context, packageName)
}

View File

@ -166,162 +166,160 @@ class SimulatorDownloadManager private constructor() {
this.gameName = gameName
this.gameType = gameCategoryChinese
PermissionHelper.checkGetInstalledAppsListBeforeAction(context, object : EmptyCallback {
override fun onCallback() {
val isInstalledNewSimulator =
SimulatorGameManager.isNewSimulatorInstalled(HaloApp.getInstance().application)
//当没有安装新版本模拟器时候 判断是否隐藏
if (simulator?.active == false && !isInstalledNewSimulator) {
showNoneEmulatorDialog(context)
return
}
var isInstalled = PackageUtils.isInstalledFromAllPackage(
context,
simulator?.apk?.packageName
)
//模拟器管理界面还是用之前的逻辑
if (isInstalledNewSimulator && location != SimulatorLocation.SIMULATOR_MANAGE) {
isInstalled = isInstalledNewSimulator
}
// val versionFromInstalledApp = PackageUtils.getVersionNameByPackageName(simulator?.apk?.packageName)
val shouldShowUpdate =
PackageUtils.isInstalledApkMatchedMd5(simulator?.apk?.packageName, simulator?.apk?.md5)
val showAlertTag = SPUtils.getString(SimulatorGameManager.SIMULATOR_UPDATE_SHOW_ALERT_TAG, "") //当天是否弹过
val todayIsShow = showAlertTag == TimeUtils.getToday()
downloadType = if (shouldShowUpdate && isInstalled) "update" else "download"
if (downloadType == "update" && todayIsShow && location != SimulatorLocation.SIMULATOR_MANAGE) {
return
}
if (downloadType == "download" && isInstalled) {
return
}
val title = if (shouldShowUpdate && isInstalled) "更新模拟器" else "安装模拟器"
val message =
if (shouldShowUpdate && isInstalled) "检测到模拟器存在更高版本,是否前往更新" else "模拟器游戏需要先下载安装对应的模拟器,才可以运行"
val positiveText =
if (shouldShowUpdate && isInstalled) "更新(${simulator?.apk?.size}" else "下载(${simulator?.apk?.size}"
val negativeText = if (shouldShowUpdate && isInstalled) "下次再说" else "取消"
val trackableEntity = TrackableEntity(
"模拟器下载",
key = if (shouldShowUpdate && isInstalled) "更新弹窗" else "下载弹窗",
logShowEvent = true
)
if (shouldShowUpdate && isInstalled) {
NewFlatLogUtils.logSimulatorUpdateAlertShow()
}
if (shouldShowUpdate && isInstalled) {
SensorsBridge.trackSimulatorUpdateDialogShow(
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
} else {
SensorsBridge.trackSimulatorInstallDialogShow(
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
}
DialogHelper.showDialog(
context,
title,
message,
positiveText,
negativeText,
trackMtaEvent = true,
cancelClickCallback = {
if (shouldShowUpdate && isInstalled) {
cancelCallback?.invoke()
NewFlatLogUtils.logSimulatorUpdateAlertClick("取消")
MtaHelper.onEvent(trackableEntity.event, trackableEntity.key, "点击下次再说")
SensorsBridge.trackSimulatorUpdateDialogClick(
buttonName = negativeText,
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
} else {
SensorsBridge.trackSimulatorInstallDialogClick(
buttonName = negativeText,
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
}
},
confirmClickCallback = {
showDownloadingDialog(context, simulator, gameId, gameName, gameCategoryChinese)
NewFlatLogUtils.logSimulatorUpdateAlertClick("更新")
MtaHelper.onEvent(
trackableEntity.event,
trackableEntity.key,
if (shouldShowUpdate && isInstalled) "点击更新" else "点击下载"
)
if (shouldShowUpdate && isInstalled) {
SensorsBridge.trackSimulatorUpdateDialogClick(
buttonName = positiveText,
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
} else {
SensorsBridge.trackSimulatorInstallDialogClick(
buttonName = positiveText,
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
}
},
touchOutsideCallback = {
if (shouldShowUpdate && isInstalled) {
SensorsBridge.trackSimulatorUpdateDialogClick(
buttonName = "关闭弹窗",
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
} else {
SensorsBridge.trackSimulatorInstallDialogClick(
buttonName = "关闭弹窗",
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
}
},
mtaEvent = trackableEntity.event, mtaKey = trackableEntity.key,
extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
)
if (downloadType == "update" && location != SimulatorLocation.SIMULATOR_MANAGE) {
SPUtils.setString(SimulatorGameManager.SIMULATOR_UPDATE_SHOW_ALERT_TAG, TimeUtils.getToday())
}
PermissionHelper.checkGetInstalledAppsListBeforeAction(context) { _ ->
val isInstalledNewSimulator =
SimulatorGameManager.isNewSimulatorInstalled(HaloApp.getInstance().application)
//当没有安装新版本模拟器时候 判断是否隐藏
if (simulator?.active == false && !isInstalledNewSimulator) {
showNoneEmulatorDialog(context)
return@checkGetInstalledAppsListBeforeAction
}
})
var isInstalled = PackageUtils.isInstalledFromAllPackage(
context,
simulator?.apk?.packageName
)
//模拟器管理界面还是用之前的逻辑
if (isInstalledNewSimulator && location != SimulatorLocation.SIMULATOR_MANAGE) {
isInstalled = isInstalledNewSimulator
}
// val versionFromInstalledApp = PackageUtils.getVersionNameByPackageName(simulator?.apk?.packageName)
val shouldShowUpdate =
PackageUtils.isInstalledApkMatchedMd5(simulator?.apk?.packageName, simulator?.apk?.md5)
val showAlertTag = SPUtils.getString(SimulatorGameManager.SIMULATOR_UPDATE_SHOW_ALERT_TAG, "") //当天是否弹过
val todayIsShow = showAlertTag == TimeUtils.getToday()
downloadType = if (shouldShowUpdate && isInstalled) "update" else "download"
if (downloadType == "update" && todayIsShow && location != SimulatorLocation.SIMULATOR_MANAGE) {
return@checkGetInstalledAppsListBeforeAction
}
if (downloadType == "download" && isInstalled) {
return@checkGetInstalledAppsListBeforeAction
}
val title = if (shouldShowUpdate && isInstalled) "更新模拟器" else "安装模拟器"
val message =
if (shouldShowUpdate && isInstalled) "检测到模拟器存在更高版本,是否前往更新" else "模拟器游戏需要先下载安装对应的模拟器,才可以运行"
val positiveText =
if (shouldShowUpdate && isInstalled) "更新(${simulator?.apk?.size}" else "下载(${simulator?.apk?.size}"
val negativeText = if (shouldShowUpdate && isInstalled) "下次再说" else "取消"
val trackableEntity = TrackableEntity(
"模拟器下载",
key = if (shouldShowUpdate && isInstalled) "更新弹窗" else "下载弹窗",
logShowEvent = true
)
if (shouldShowUpdate && isInstalled) {
NewFlatLogUtils.logSimulatorUpdateAlertShow()
}
if (shouldShowUpdate && isInstalled) {
SensorsBridge.trackSimulatorUpdateDialogShow(
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
} else {
SensorsBridge.trackSimulatorInstallDialogShow(
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
}
DialogHelper.showDialog(
context,
title,
message,
positiveText,
negativeText,
trackMtaEvent = true,
cancelClickCallback = {
if (shouldShowUpdate && isInstalled) {
cancelCallback?.invoke()
NewFlatLogUtils.logSimulatorUpdateAlertClick("取消")
MtaHelper.onEvent(trackableEntity.event, trackableEntity.key, "点击下次再说")
SensorsBridge.trackSimulatorUpdateDialogClick(
buttonName = negativeText,
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
} else {
SensorsBridge.trackSimulatorInstallDialogClick(
buttonName = negativeText,
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
}
},
confirmClickCallback = {
showDownloadingDialog(context, simulator, gameId, gameName, gameCategoryChinese)
NewFlatLogUtils.logSimulatorUpdateAlertClick("更新")
MtaHelper.onEvent(
trackableEntity.event,
trackableEntity.key,
if (shouldShowUpdate && isInstalled) "点击更新" else "点击下载"
)
if (shouldShowUpdate && isInstalled) {
SensorsBridge.trackSimulatorUpdateDialogClick(
buttonName = positiveText,
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
} else {
SensorsBridge.trackSimulatorInstallDialogClick(
buttonName = positiveText,
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
}
},
touchOutsideCallback = {
if (shouldShowUpdate && isInstalled) {
SensorsBridge.trackSimulatorUpdateDialogClick(
buttonName = "关闭弹窗",
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
} else {
SensorsBridge.trackSimulatorInstallDialogClick(
buttonName = "关闭弹窗",
gameId = gameId,
gameName = gameName,
gameType = gameCategoryChinese,
lastPageId = GlobalActivityManager.getLastPageEntity().pageId,
lastPageName = GlobalActivityManager.getLastPageEntity().pageName,
lastPageBusinessId = GlobalActivityManager.getLastPageEntity().pageBusinessId
)
}
},
mtaEvent = trackableEntity.event, mtaKey = trackableEntity.key,
extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
)
if (downloadType == "update" && location != SimulatorLocation.SIMULATOR_MANAGE) {
SPUtils.setString(SimulatorGameManager.SIMULATOR_UPDATE_SHOW_ALERT_TAG, TimeUtils.getToday())
}
}
}
fun showDownloadingDialog(

View File

@ -50,6 +50,8 @@ object ArchiveDownloadButtonHelper {
}
downloadBtn.setOnClickListener {
when {
// 检查是否已安装畅玩助手
!VHelper.isVSpaceInstalled(context) -> showVSpaceTipDialog(context, gameEntity)
// 检查是否已安装游戏
!VHelper.isInstalled(packageName) -> {
// 检查游戏是否在安装中

View File

@ -1,17 +1,11 @@
package com.gh.common.util;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.core.utils.CurrentActivityHolder;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.login.utils.QuickLoginHelper;
import com.gh.gamecenter.login.view.LoginActivity;
import com.gh.gamecenter.common.utils.NetworkUtils;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.gamecenter.login.user.UserManager;
import com.lightgame.utils.Utils;
@ -28,15 +22,15 @@ public class CheckLoginUtils {
LogUtils.login("dialog", null, entrance);
LogUtils.login("activity", null, entrance);
if (SPUtils.getBoolean(Constants.SP_HAS_GET_PHONE_INFO) || NetworkUtils.isOpenMobileData(context)) {
startQuickLogin(context, entrance);
} else {
// 有可能App未启动
Bundle bundle = new Bundle();
bundle.putString(EntranceConsts.KEY_ENTRANCE, entrance);
bundle.putString(EntranceConsts.KEY_TO, LoginActivity.class.getName());
EntranceUtils.jumpActivity(context, bundle);
}
// if (SPUtils.getBoolean(Constants.SP_HAS_GET_PHONE_INFO) || NetworkUtils.isOpenMobileData(context)) {
// startQuickLogin(context, entrance);
// } else {
// 有可能App未启动
Bundle bundle = new Bundle();
bundle.putString(EntranceConsts.KEY_ENTRANCE, entrance);
bundle.putString(EntranceConsts.KEY_TO, LoginActivity.class.getName());
EntranceUtils.jumpActivity(context, bundle);
// }
} else {
if (listener != null) {
listener.onLogin();
@ -44,16 +38,16 @@ public class CheckLoginUtils {
}
}
private static void startQuickLogin(Context context, String entrance) {
// 需要确保传入的 context 不为 application
if (!(context instanceof Activity)) {
context = CurrentActivityHolder.getCurrentActivity();
}
if (context != null) {
QuickLoginHelper.startLogin(context, entrance);
}
}
// private static void startQuickLogin(Context context, String entrance) {
// // 需要确保传入的 context 不为 application
// if (!(context instanceof Activity)) {
// context = CurrentActivityHolder.getCurrentActivity();
// }
//
// if (context != null) {
// QuickLoginHelper.startLogin(context, entrance);
// }
// }
public static void checkLogin(final Context context, Bundle nextToBundle, boolean isTriggerNextStep, String entrance, OnLoginListener listener) {
if (!isLogin()) {

View File

@ -1625,211 +1625,6 @@ object DirectUtils {
jumpActivityCompat(context, newBundle)
}
/**
* 跳转至商品详情
*/
@JvmStatic
fun directToCommodityDetail(context: Context, commodityId: String) {
var url: String = if (EnvHelper.isDevEnv) {
Constants.COMMODITY_DETAIL_ADDRESS_DEV
} else {
Constants.COMMODITY_DETAIL_ADDRESS
}
url = String.format(
Locale.CHINA,
"%s&shopid=%s&timestamp=%d",
url,
commodityId,
(Date().time / 1000 / 1000.toFloat()).roundToInt()
)
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至光能记录默认跳到光能记录第一个Tab
*/
@JvmStatic
fun directToEnergyRecord(context: Context) {
directToEnergyRecord(context, 0)
}
@JvmStatic
fun directToEnergyRecord(context: Context, position: Int) {
var url: String = if (EnvHelper.isDevEnv) {
Constants.ENERGY_RECORD_ADDRESS_DEV
} else {
Constants.ENERGY_RECORD_ADDRESS
}
url = String.format(
Locale.CHINA,
"%s&position=%s&timestamp=%d",
url,
position,
(Date().time / 1000 / 1000.toFloat()).roundToInt()
)
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至订单中心
*/
@JvmStatic
fun directToOrderCenter(context: Context) {
val url: String = if (EnvHelper.isDevEnv) {
Constants.ORDER_CENTER_ADDRESS_DEV
} else {
Constants.ORDER_CENTER_ADDRESS
}
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至订单详情
*/
@JvmStatic
fun directToOrderDetail(context: Context, orderId: String) {
var url: String = if (EnvHelper.isDevEnv) {
Constants.ORDER_DETAIL_ADDRESS_DEV
} else {
Constants.ORDER_DETAIL_ADDRESS
}
url = String.format(
Locale.CHINA,
"%s&order_id=%s&timestamp=%d",
url,
orderId,
(Date().time / 1000 / 1000.toFloat()).roundToInt()
)
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至邀请好友
*/
@JvmStatic
fun directToInviteFriends(context: Context) {
val url: String = if (EnvHelper.isDevEnv) {
Constants.INVITE_FRIENDS_ADDRESS_DEV
} else {
Constants.INVITE_FRIENDS_ADDRESS
}
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至等级页面
*/
@JvmStatic
fun directToLevelPage(context: Context) {
var url: String = if (isPublishEnv()) {
Constants.LEVEL_ADDRESS
} else {
Constants.LEVEL_ADDRESS_DEV
}
url = String.format(Locale.CHINA, "%s?timestamp=%d", url, (Date().time / 1000 / 1000.toFloat()).roundToInt())
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至兑换规则
*/
@JvmStatic
fun directToExchangeRulePage(context: Context) {
var url: String = if (isPublishEnv()) {
Constants.EXCHANGE_RULE_ADDRESS
} else {
Constants.EXCHANGE_RULE_ADDRESS_DEV
}
url = String.format(Locale.CHINA, "%s&timestamp=%d", url, (Date().time / 1000 / 1000.toFloat()).roundToInt())
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至光能规则
*/
@JvmStatic
fun directToEnergyRulePage(context: Context) {
var url: String = if (isPublishEnv()) {
Constants.ENERGY_RULE_ADDRESS
} else {
Constants.ENERGY_RULE_ADDRESS_DEV
}
url = String.format(Locale.CHINA, "%s&timestamp=%d", url, (Date().time / 1000 / 1000.toFloat()).roundToInt())
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至兑换商品
*/
@JvmStatic
fun directToExchangeCommodityPage(context: Context) {
var url: String = if (isPublishEnv()) {
Constants.EXCHANGE_COMMODITY_ADDRESS
} else {
Constants.EXCHANGE_COMMODITY_ADDRESS_DEV
}
url = String.format(Locale.CHINA, "%s&timestamp=%d", url, (Date().time / 1000 / 1000.toFloat()).roundToInt())
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至抽奖乐园
*/
@JvmStatic
fun directToLotteryParadisePage(context: Context) {
var url: String = if (isPublishEnv()) {
Constants.LOTTERY_PARADISE_ADDRESS
} else {
Constants.LOTTERY_PARADISE_ADDRESS_DEV
}
url = String.format(Locale.CHINA, "%s&timestamp=%d", url, (Date().time / 1000 / 1000.toFloat()).roundToInt())
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至我的奖品
*/
@JvmStatic
fun directToMyPrizePage(context: Context) {
var url: String = if (isPublishEnv()) {
Constants.MY_PRIZE_ADDRESS
} else {
Constants.MY_PRIZE_ADDRESS_DEV
}
url = String.format(Locale.CHINA, "%s&timestamp=%d", url, (Date().time / 1000 / 1000.toFloat()).roundToInt())
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至中奖订单详情
*/
@JvmStatic
fun directToWinOrderDetail(context: Context, orderId: String, activityId: String) {
var url: String = if (isPublishEnv()) {
Constants.WIN_ORDER_DETAIL_ADDRESS
} else {
Constants.WIN_ORDER_DETAIL_ADDRESS_DEV
}
url = String.format(
Locale.CHINA,
"%s&order_id=%s&activity_id=%s&timestamp=%d",
url,
orderId,
activityId,
(Date().time / 1000 / 1000.toFloat()).roundToInt()
)
directToFullScreenWebPage(context, url, true)
}
/**
* 跳转至地址信息

View File

@ -508,18 +508,11 @@ object DownloadObserver {
"space_schema_type",
if (downloadEntity.packageName == VHelper.VSPACE_32BIT_PACKAGENAME) "32位" else "64位"
)
} else if(downloadEntity.gameId == Constants.HALO_FUN_NEW_32_GAME_ID) {
SensorsBridge.trackEvent(
"HaloFunDownloadDone",
"space_schema_type",
"32位(新)"
)
}
if (downloadEntity.gameId != Constants.GHZS_GAME_ID
&& downloadEntity.getMetaExtra(Constants.EXTRA_DOWNLOAD_TYPE) != Constants.SIMULATOR_DOWNLOAD
&& downloadEntity.gameId != Constants.HALO_FUN_GAME_ID
&& downloadEntity.gameId != Constants.HALO_FUN_NEW_32_GAME_ID
) {
val trackJson = downloadEntity.customPageTrackDataJson
val kvs = if (!trackJson.isNullOrBlank()) {

View File

@ -282,7 +282,7 @@ object GameActivityDownloadHelper {
location: String,
traceEvent: ExposureEvent
) {
VHelper.validateVSpaceBeforeAction(context,gameEntity.getUniquePackageName(), gameEntity) {
VHelper.validateVSpaceBeforeAction(context, gameEntity) {
GamePermissionDialogFragment.show((context as AppCompatActivity), gameEntity, gameEntity.info) {
DialogUtils.checkDownload(
context,

View File

@ -35,8 +35,6 @@ object HomeBottomBarHelper {
text = "游戏库",
name = "游戏库",
position = 2,
iconSelect = "https://resource.ghzs.com/image/game/library/entrance/5e183202913fbd002c75f247.png",
iconUnselect = "https://resource.ghzs.com/image/game/library/entrance/5e1831fd913fbd003024641e.png",
animationCode = animationCode,
default = false,
display = Display()

View File

@ -50,7 +50,7 @@ public class InstallUtils {
public void handleMessage(Message msg) {
if (msg.what == INSTALL_WHAT && packageManager != null) {
ArrayList<String> list = new ArrayList<>();
List<PackageInfo> packageInfos = PackageUtils.getInstalledPackages(context, 0);
List<PackageInfo> packageInfos = PackageHelper.INSTANCE.getInstalledPackages(context, 0);
for (PackageInfo packageInfo : packageInfos) {
if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
list.add(packageInfo.packageName);

View File

@ -768,7 +768,7 @@ public class LibaoUtils {
}
public static boolean isAppInstalled(Context context, String packageName) {
List<PackageInfo> pinfo = PackageUtils.getInstalledPackages(context, 0);
List<PackageInfo> pinfo = PackageHelper.INSTANCE.getInstalledPackages(context, 0);
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName;

View File

@ -93,13 +93,12 @@ object NewFlatLogUtils {
// 畅玩助手更新弹窗展示事件
@JvmStatic
fun logHaloFunUpdateDialogShow(gameId: String, gameName: String, gameArchitecture: String, targetVaVersion: String) {
fun logHaloFunUpdateDialogShow(gameId: String, gameName: String, gameArchitecture: String) {
val json = json {
KEY_EVENT to "halo_fun_update_dialog_show"
"game_id" to gameId
"game_name" to gameName
"game_architecture" to gameArchitecture
"target_va_version" to targetVaVersion
parseAndPutMeta().invoke(this)
}
log(json)
@ -143,13 +142,12 @@ object NewFlatLogUtils {
// 畅玩助手更新弹窗点击事件
@JvmStatic
fun logHaloFunUpdateDialogClick(dialogType: String, buttonType: String, architecture: String, targetVaVersion: String) {
fun logHaloFunUpdateDialogClick(dialogType: String, buttonType: String, architecture: String) {
val json = json {
KEY_EVENT to "halo_fun_update_dialog_click"
"dialog_type" to dialogType
KEY_BUTTON_TYPE to buttonType
"architecture" to architecture
"target_va_version" to targetVaVersion
parseAndPutMeta().invoke(this)
}
log(json)

View File

@ -2,23 +2,53 @@ package com.gh.common.util
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.PermissionInfo
import android.os.Build
import android.provider.Settings
import com.gh.common.constant.Config
import com.gh.gamecenter.common.utils.PermissionHelper.isGetInstalledListPermissionDisabled
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.feature.entity.SettingsEntity
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import kotlin.collections.ArrayList
import kotlin.collections.HashSet
object PackageHelper {
private const val TAG = "PackageHelper"
private const val SP_GET_INSTALLED_API_AGREED = "get_installed_api_agreed"
private const val UNKNOWN = -1
private const val UNSUPPORTED = 0
private const val SUPPORTED = 1
private var lastInstalledPackageListTime = 0L
private var installedPackageList: List<PackageInfo> = arrayListOf()
private var isGetInstalledPackagesApiAgreed = false
private var isGetInstalledListPermissionSupported = UNKNOWN // 设备是否支持禁用获取已安装应用列表。-1 代表支持情况未知0 代表不支持, 1 代表支持
// 评论黑名单包名列表,避免用户安装了 Xposed Installer 这样的工具,也能在包含该安装包的游戏详情页评论
var commentPackageNameBlackList = arrayListOf<String>()
private var _commentPackageNameBlackList = arrayListOf<String>()
val commentPackageNameBlackList: ArrayList<String> = _commentPackageNameBlackList
// 关闭下载的包列表
var downloadPackageNameBlackList = arrayListOf<String>()
private var _downloadPackageNameBlackList = arrayListOf<String>()
val downloadPackageNameBlackList: ArrayList<String> = _downloadPackageNameBlackList
// 本地已安装的包去掉关闭下载的包后的列表
var validLocalPackageNameSet = hashSetOf<String>()
private var _validLocalPackageNameSet = hashSetOf<String>()
val validLocalPackageNameSet: HashSet<String> = _validLocalPackageNameSet
// 游戏包名匹配列表
var relatedPackageList = arrayListOf<SettingsEntity.GameWithPackages>()
private var _relatedPackageList = arrayListOf<SettingsEntity.GameWithPackages>()
val relatedPackageList: ArrayList<SettingsEntity.GameWithPackages> = _relatedPackageList
// 本地已安装包的列表
var localPackageNameSet = hashSetOf<String>()
@ -38,33 +68,26 @@ object PackageHelper {
}
@JvmStatic
fun initList() {
Config.getSettings()?.gameCommentBlackList?.let {
commentPackageNameBlackList = ArrayList(it)
}
Config.getSettings()?.gameDownloadBlackList?.let {
downloadPackageNameBlackList = ArrayList(it)
}
Config.getSettings()?.gamePackageMatch?.let {
relatedPackageList = ArrayList(it)
}
fun refreshList() {
Config.getSettings()?.gameCommentBlackList?.let { _commentPackageNameBlackList = ArrayList(it) }
Config.getSettings()?.gameDownloadBlackList?.let { _downloadPackageNameBlackList = ArrayList(it) }
Config.getSettings()?.gamePackageMatch?.let { _relatedPackageList = ArrayList(it) }
Config.getSettings()?.gameDownloadBlackList
updateValidPackageNameList()
}
private fun updateValidPackageNameList() {
validLocalPackageNameSet =
_validLocalPackageNameSet =
localPackageNameSet.filterNot { p -> downloadPackageNameBlackList.contains(p) }.toHashSet()
}
/*
/**
* 获取所有已安装的软件的包名、版本(非系统应用)
*/
private fun getAllPackageName(context: Context): HashSet<String> {
val set = HashSet<String>()
return try {
val packageInfos = PackageUtils.getInstalledPackages(context, 0)
val packageInfos = getInstalledPackages(context, 0)
for (packageInfo in packageInfos) {
if (packageInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
if (context.packageName != packageInfo.packageName) {
@ -79,4 +102,154 @@ object PackageHelper {
}
}
/**
* 弃用已安装列表缓存
*/
fun dumpInstalledListCache() {
lastInstalledPackageListTime = 0
}
/**
* 用户是否已经允许了调用获取已安装应用列表接口
* 优先用内存的值,没有再从 SP 中获取并更新
*/
fun isGetInstalledPackagesApiAgreed(): Boolean {
return isGetInstalledPackagesApiAgreed
|| (SPUtils.getBoolean(SP_GET_INSTALLED_API_AGREED).also { isGetInstalledPackagesApiAgreed = it })
}
/**
* 同意使用已安装应用列表 API
*/
fun agreeOnGetInstalledPackagesApi() {
isGetInstalledPackagesApiAgreed = true
SPUtils.setBoolean(SP_GET_INSTALLED_API_AGREED, true)
}
/**
* 获取已安装应用列表
*/
fun getInstalledPackages(context: Context?, flags: Int): List<PackageInfo> {
Utils.log(TAG, "即将获取已安装应用列表")
// Utils.log(TAG, "即将获取已安装应用列表" + Thread.currentThread().getStackTrace().contentToString().replace( ',', '\n' ))
// 用户未同意使用已安装应用列表 API返回空列表
if (!isGetInstalledPackagesApiAgreed()) {
Utils.log(TAG, "用户未同意使用已安装应用列表 API返回空列表")
return installedPackageList
}
// 简单 debounce 过于频繁的获取已安装应用列表调用
if (System.currentTimeMillis() - lastInstalledPackageListTime < 3000 && installedPackageList.isNotEmpty()) {
Utils.log(TAG, "使用了缓存的已安装应用列表")
return installedPackageList
}
var shouldGetNewInstalledPackagedList = false
// 当前设备是否支持限制获取已安装应用列表的功能
if (isSupportGetInstalledAppsPermission(context!!)) {
Utils.log(TAG, "当前设备支持限制获取已安装应用列表的功能")
// 当前设备是否支持禁用了获取已安装应用列表
if (!isGetInstalledListPermissionDisabled(context)) {
Utils.log(TAG, "当前设备没有限制获取已安装应用列表的功能")
shouldGetNewInstalledPackagedList = true
} else {
Utils.log(TAG, "当前设备已限制获取已安装应用列表的功能")
}
} else {
Utils.log(TAG, "当前设备不支持限制获取已安装应用列表的功能")
shouldGetNewInstalledPackagedList = true
}
if (shouldGetNewInstalledPackagedList) {
lastInstalledPackageListTime = System.currentTimeMillis()
installedPackageList = getInstalledPackagesInternal(context, flags)
}
return installedPackageList
}
/**
* 是否支持动态获取已安装应用列表权限
*/
fun isSupportGetInstalledAppsPermission(context: Context): Boolean {
// 若存在缓存,直接返回缓存结果。
if (isGetInstalledListPermissionSupported != UNKNOWN) {
return isGetInstalledListPermissionSupported != UNSUPPORTED
}
try {
// 根据官方提供的方法来判定是否支持限制获取已安装应用列表
val flag =
Settings.Secure.getInt(context.contentResolver, "oem_installed_apps_runtime_permission_enable", 0)
if (flag == 1) {
isGetInstalledListPermissionSupported = SUPPORTED
return true
}
// 部分未升级的手机没有上面配置项,有定义下面危险权限也认为是支持设备软件列表管控
val packageManager = context.packageManager
val permissionInfo = packageManager.getPermissionInfo("com.android.permission.GET_INSTALLED_APPS", 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
if (permissionInfo.protection == PermissionInfo.PROTECTION_DANGEROUS) {
isGetInstalledListPermissionSupported = SUPPORTED
return true
} else {
isGetInstalledListPermissionSupported = UNSUPPORTED
return false
}
} else {
isGetInstalledListPermissionSupported = UNSUPPORTED
return false
}
} catch (e: PackageManager.NameNotFoundException) {
isGetInstalledListPermissionSupported = UNSUPPORTED
return false
}
}
/**
* 在5.1系统手机使用PackageManager获取已安装应用容易发生Package manager has died异常
* https://stackoverflow.com/questions/13235793/transactiontoolargeeception-when-trying-tÏo-get-a-list-of-applications-installed/30062632#30062632
*/
private fun getInstalledPackagesInternal(context: Context, flags: Int): List<PackageInfo> {
Utils.log(TAG, "调用系统 API 获取已安装应用列表")
val pm = context.packageManager
try {
return pm.getInstalledPackages(flags)
} catch (ignored: java.lang.Exception) {
//we don't care why it didn't succeed. We'll do it using an alternative way instead
}
// use fallback:
val process: Process
val result: MutableList<PackageInfo> = java.util.ArrayList()
var bufferedReader: BufferedReader? = null
try {
process = Runtime.getRuntime().exec("pm list packages")
bufferedReader = BufferedReader(InputStreamReader(process.inputStream))
var line: String
while ((bufferedReader.readLine().also { line = it }) != null) {
val packageName = line.substring(line.indexOf(':') + 1)
val packageInfo = pm.getPackageInfo(packageName, flags)
result.add(packageInfo)
}
process.waitFor()
} catch (e: java.lang.Exception) {
e.printStackTrace()
if (e is InterruptedException) {
Thread.currentThread().interrupt()
}
} finally {
if (bufferedReader != null) try {
bufferedReader.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
return result
}
}

View File

@ -29,7 +29,6 @@ import com.gh.common.xapk.XapkInstaller;
import com.gh.gamecenter.BuildConfig;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.PackageFlavorHelper;
import com.gh.gamecenter.common.utils.PermissionHelper;
import com.gh.gamecenter.core.utils.MD5Utils;
import com.gh.gamecenter.core.utils.SentryHelper;
@ -68,14 +67,8 @@ import java.util.zip.ZipFile;
public class PackageUtils {
private static long mLastInstalledPackageListTime = 0L;
private static List<PackageInfo> mInstalledPackageList = null;
private static final String TAG = "PackageUtils";
// 设备是否支持禁用获取已安装应用列表。-1 代表支持情况未知0 代表不支持, 1 代表支持
private static int mIsSupportGetInstalledListPermission = -1;
public static String getInstallPackageInfoSourceDir(String packageName) {
try {
return HaloApp.getInstance().getApplication().getPackageManager().getPackageInfo(packageName,
@ -677,7 +670,7 @@ public class PackageUtils {
*/
public static ArrayList<String> getAllPackageName(Context context) {
ArrayList<String> list = new ArrayList<>();
List<PackageInfo> packageInfos = getInstalledPackages(context, 0);
List<PackageInfo> packageInfos = PackageHelper.INSTANCE.getInstalledPackages(context, 0);
for (PackageInfo packageInfo : packageInfos) {
if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
if (!context.getPackageName().equals(packageInfo.packageName)) {
@ -690,7 +683,7 @@ public class PackageUtils {
public static ArrayList<String> getAllPackageNameIncludeGh(Context context) {
ArrayList<String> list = new ArrayList<>();
List<PackageInfo> packageInfos = getInstalledPackages(context, 0);
List<PackageInfo> packageInfos = PackageHelper.INSTANCE.getInstalledPackages(context, 0);
for (PackageInfo packageInfo : packageInfos) {
if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
list.add(packageInfo.packageName);
@ -704,11 +697,9 @@ public class PackageUtils {
*/
public static ArrayList<String> getAllPackageNameIncludeSystemApps(Context context) {
ArrayList<String> list = new ArrayList<>();
List<PackageInfo> packageInfos = getInstalledPackages(context, 0);
List<PackageInfo> packageInfos = PackageHelper.INSTANCE.getInstalledPackages(context, 0);
for (PackageInfo packageInfo : packageInfos) {
if (!context.getPackageName().equals(packageInfo.packageName)) {
list.add(packageInfo.packageName);
}
list.add(packageInfo.packageName);
}
return list;
}
@ -717,7 +708,7 @@ public class PackageUtils {
JSONArray jsonArray = new JSONArray();
try {
PackageManager pm = context.getPackageManager();
List<PackageInfo> packageInfos = getInstalledPackages(context, 0);
List<PackageInfo> packageInfos = PackageHelper.INSTANCE.getInstalledPackages(context, 0);
for (PackageInfo packageInfo : packageInfos) {
if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
JSONObject jsonObject = new JSONObject();
@ -758,7 +749,6 @@ public class PackageUtils {
}
}
/**
* 启动应用
* 请使用 PackageLauncher.launchApp()
@ -778,22 +768,6 @@ public class PackageUtils {
}
}
/*
* 根据包名,获取软件名称
*/
public static String getNameByPackageName(Context context, String packageName) {
try {
PackageManager pm = context.getApplicationContext().getPackageManager();
ApplicationInfo applicationInfo = pm.getApplicationInfo(
packageName, 0);
return applicationInfo.loadLabel(pm).toString();
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* todo 统一判断
* <p>
@ -912,8 +886,8 @@ public class PackageUtils {
String packageName = context.getApplicationContext().getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
// The name of the process that this object is associated with.
if (appProcess.processName.equals(packageName) && appProcess.importance
== ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (appProcess.processName.equals(packageName)
&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
@ -924,132 +898,6 @@ public class PackageUtils {
return false;
}
/**
* 弃用已安装列表缓存
*/
public static void dumpInstalledListCache() {
mLastInstalledPackageListTime = 0;
}
public static List<PackageInfo> getInstalledPackages(Context context, int flags) {
Utils.log(TAG, "即将获取已安装应用列表");
// 简单 debounce 掉过于频繁的调用获取已安装列表调用
if (System.currentTimeMillis() - mLastInstalledPackageListTime < 1000
&& mInstalledPackageList != null
&& mInstalledPackageList.size() > 0) {
Utils.log(TAG, "使用了缓存的已安装应用列表");
return new ArrayList<>(mInstalledPackageList);
}
// 是否需要调用系统 API 获取最新的已安装应用列表
boolean shouldGetNewInstalledPackagedList = false;
// 当前设备是否支持限制获取已安装应用列表的功能
if (isSupportGetInstalledAppsPermission(context)) {
Utils.log(TAG, "当前设备支持限制获取已安装应用列表的功能");
// 当前设备是否支持禁用了获取已安装应用列表
if (!PermissionHelper.isGetInstalledListPermissionDisabled(context)) {
Utils.log(TAG, "当前设备没有限制获取已安装应用列表的功能");
shouldGetNewInstalledPackagedList = true;
} else {
Utils.log(TAG, "当前设备已限制获取已安装应用列表的功能");
}
} else {
Utils.log(TAG, "当前设备不支持限制获取已安装应用列表的功能");
shouldGetNewInstalledPackagedList = true;
}
if (shouldGetNewInstalledPackagedList) {
mLastInstalledPackageListTime = System.currentTimeMillis();
mInstalledPackageList = getInstalledPackagesInternal(context, flags);
}
if (mInstalledPackageList == null) {
mInstalledPackageList = new ArrayList<>();
}
return mInstalledPackageList;
}
public static boolean isSupportGetInstalledAppsPermission(Context context) {
// 若存在缓存,直接返回缓存结果。为 0 代表不支持,为 1 代表支持
if (mIsSupportGetInstalledListPermission != -1) {
return mIsSupportGetInstalledListPermission != 0;
}
try {
// 根据官方提供的方法来判定是否支持限制获取已安装应用列表
int flag = Settings.Secure.getInt(context.getContentResolver(), "oem_installed_apps_runtime_permission_enable", 0);
if (flag == 1) {
mIsSupportGetInstalledListPermission = 1;
return true;
}
// 部分未升级的手机没有上面配置项,有定义下面危险权限也认为是支持设备软件列表管控
PackageManager packageManager = context.getPackageManager();
PermissionInfo permissionInfo = packageManager.getPermissionInfo("com.android.permission.GET_INSTALLED_APPS", 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
if (permissionInfo.getProtection() == PermissionInfo.PROTECTION_DANGEROUS) {
mIsSupportGetInstalledListPermission = 1;
return true;
} else {
mIsSupportGetInstalledListPermission = 0;
return false;
}
} else {
mIsSupportGetInstalledListPermission = 0;
return false;
}
} catch (NameNotFoundException e) {
mIsSupportGetInstalledListPermission = 0;
return false;
}
}
/**
* 在5.1系统手机使用PackageManager获取已安装应用容易发生Package manager has died异常
* https://stackoverflow.com/questions/13235793/transactiontoolargeeception-when-trying-tÏo-get-a-list-of-applications-installed/30062632#30062632
*/
private static List<PackageInfo> getInstalledPackagesInternal(Context context, int flags) {
Utils.log(TAG, "调用系统 API 获取已安装应用列表");
final PackageManager pm = context.getPackageManager();
try {
return pm.getInstalledPackages(flags);
} catch (Exception ignored) {
//we don't care why it didn't succeed. We'll do it using an alternative way instead
}
// use fallback:
Process process;
List<PackageInfo> result = new ArrayList<>();
BufferedReader bufferedReader = null;
try {
process = Runtime.getRuntime().exec("pm list packages");
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
final String packageName = line.substring(line.indexOf(':') + 1);
final PackageInfo packageInfo = pm.getPackageInfo(packageName, flags);
result.add(packageInfo);
}
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
} finally {
if (bufferedReader != null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String getWebviewPath(Context context) {
final PackageInfo webViewPackageInfo = WebViewCompat.getCurrentWebViewPackage(context);
return webViewPackageInfo != null ? webViewPackageInfo.applicationInfo.sourceDir : null;

View File

@ -1,248 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.ProgressBar;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.R;
public class DownloadProgressBar extends ProgressBar {
public static final int MAX_LENGTH = 1000;
public static final int DOWNLOAD_NORMAL_STYLE = 0;
public static final int DOWNLOAD_IMAGE_STYLE = 2;
public enum DownloadType {
NORMAL,
NONE,
NONE_WITH_HINT,
PLUGIN,
LAUNCH_OR_OPEN,
INSTALL_NORMAL,
INSTALL_PLUGIN,
DOWNLOADING_NORMAL,
DOWNLOADING_PLUGIN,
RESERVABLE,
RESERVED,
H5_GAME,
UPDATING,
TEENAGER_MODEL,
SPECIAL_DOWNLOAD,
XAPK_UNZIPPING,
XAPK_SUCCESS,
XAPK_FAILURE,
}
private PorterDuffXfermode mDuffXFerMode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// 仅用于测量文字是否超出范围,不用于画文字
private TextPaint mFakeTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
private DownloadType mDownloadType;
private String mText;
private int mDownloadStyle;
private int mDefaultColor;
private int mTextSize;
private boolean mShowDownloadPercent = false;
private Rect mTextBound = new Rect();
public DownloadProgressBar(Context context) {
super(context);
}
public DownloadProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
if (attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.DownloadProgressBar);
mDownloadStyle = ta.getInteger(R.styleable.DownloadProgressBar_downloadStyle, DOWNLOAD_NORMAL_STYLE);
mTextSize = ta.getDimensionPixelSize(R.styleable.DownloadProgressBar_textSize, DisplayUtils.sp2px(getContext(), 14));
mShowDownloadPercent = ta.getBoolean(R.styleable.DownloadProgressBar_showDownloadPercent, false);
ta.recycle();
}
setMax(MAX_LENGTH);
setProgressDrawable(getResources().getDrawable(R.drawable.game_item_btn_download_style));
}
Bitmap srcBitmap;
Canvas srcCanvas;
RectF rectF;
private void create() {
srcBitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
srcCanvas = new Canvas(srcBitmap);
rectF = new RectF(0, 0, getProgress() * getWidth() / MAX_LENGTH, getMeasuredHeight());
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (TextUtils.isEmpty(mText)) return;
mPaint.setColor(mDefaultColor == 0 ? ContextCompat.getColor(getContext(), R.color.text_theme) : mDefaultColor); // 初始化颜色
mPaint.setTextSize(mTextSize);
mFakeTextPaint.setTextSize(mTextSize);
mFakeTextPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mFakeTextPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setXfermode(null);
create();
Paint.FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();
int baseline = (getHeight() - fontMetrics.bottom - fontMetrics.top) / 2;
mPaint.setTextAlign(Paint.Align.CENTER);
canvas.getClipBounds(mTextBound); //The dimensions of your canvas
int width = mTextBound.width() - 20; //10 to keep some space on the right for the "..."
String txt = TextUtils.ellipsize(mText, mFakeTextPaint, width, TextUtils.TruncateAt.END).toString();
srcCanvas.drawText(txt, getWidth() / 2, baseline, mPaint);
mPaint.setXfermode(mDuffXFerMode);
if (getProgress() != 0) {
int color = Color.WHITE;
if (DOWNLOAD_IMAGE_STYLE == mDownloadStyle) {
color = Color.BLACK;
}
mPaint.setColor(color); // 反向颜色
}
srcCanvas.drawRect(rectF, mPaint);
canvas.drawBitmap(srcBitmap, 0, 0, null);
}
public void setText(String text) {
mText = text;
invalidate();
}
public String getText() {
if (mText != null && mText.contains("%")) {
return getResources().getString(R.string.downloading);
}
return mText;
}
public void setText(@StringRes int res) {
if (mShowDownloadPercent && res == R.string.downloading) {
setText(getProgressPercent());
} else {
setText(getResources().getString(res));
}
}
public void setDownloadStyle(int downloadStyle) {
this.mDownloadStyle = downloadStyle;
}
@Override
public synchronized void setProgress(int progress) {
super.setProgress(progress);
if (getResources().getString(R.string.downloading).equals(mText)) {
setText(getProgressPercent());
}
}
private String getProgressPercent() {
return getProgress() / 10 + "%";
}
public void setDownloadType(DownloadType downloadType) {
switch (downloadType) {
case NORMAL:
case NONE_WITH_HINT:
case INSTALL_NORMAL:
case H5_GAME:
if (mDownloadStyle == DOWNLOAD_IMAGE_STYLE) {
setProgressDrawable(getResources().getDrawable(R.drawable.text_white_background));
mDefaultColor = Color.BLACK;
} else {
setProgressDrawable(getResources().getDrawable(R.drawable.download_button_normal_style));
mDefaultColor = Color.WHITE;
}
setProgress(0);
break;
case PLUGIN:
case INSTALL_PLUGIN:
setProgressDrawable(getResources().getDrawable(R.drawable.download_button_pluggable_style));
mDefaultColor = Color.WHITE;
setProgress(0);
break;
case NONE:
setProgressDrawable(getResources().getDrawable(R.drawable.button_round_gray_light));
mDefaultColor = ContextCompat.getColor(getContext(), R.color.text_tertiary);
setProgress(0);
break;
case LAUNCH_OR_OPEN:
if (mDownloadStyle == DOWNLOAD_IMAGE_STYLE) {
setProgressDrawable(getResources().getDrawable(R.drawable.detail_download_open_image_style));
mDefaultColor = Color.WHITE;
} else {
setProgressDrawable(getResources().getDrawable(R.drawable.download_button_normal_style));
mDefaultColor = Color.WHITE;
}
setProgress(0);
break;
case DOWNLOADING_NORMAL:
if (mDownloadStyle == DOWNLOAD_IMAGE_STYLE) {
setProgressDrawable(getResources().getDrawable(R.drawable.detail_downloading_normal_image_style));
mDefaultColor = Color.WHITE;
} else {
setProgressDrawable(getResources().getDrawable(R.drawable.detail_downloading_normal_style));
mDefaultColor = ContextCompat.getColor(getContext(), R.color.text_theme);
}
break;
case DOWNLOADING_PLUGIN:
setProgressDrawable(getResources().getDrawable(R.drawable.detail_downloading_normal_style));
mDefaultColor = ContextCompat.getColor(getContext(), R.color.text_theme);
break;
case RESERVABLE:
setProgressDrawable(getResources().getDrawable(R.drawable.button_reserve));
mDefaultColor = ContextCompat.getColor(getContext(), R.color.white);
break;
case UPDATING:
setProgressDrawable(getResources().getDrawable(R.drawable.download_button_updating_style));
mDefaultColor = ContextCompat.getColor(getContext(), R.color.white);
break;
case RESERVED:
setProgressDrawable(getResources().getDrawable(R.drawable.button_round_gray_light));
mDefaultColor = ContextCompat.getColor(getContext(), R.color.text_tertiary);
break;
case XAPK_FAILURE:
case XAPK_SUCCESS:
case XAPK_UNZIPPING:
setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_xapk_detail_style));
mDefaultColor = ContextCompat.getColor(getContext(), R.color.white);
break;
case TEENAGER_MODEL:
case SPECIAL_DOWNLOAD:
setProgressDrawable(getResources().getDrawable(R.drawable.download_button_normal_style));
mDefaultColor = ContextCompat.getColor(getContext(), R.color.white);
break;
}
mDownloadType = downloadType;
}
public DownloadType getDownloadType() {
return mDownloadType;
}
}

View File

@ -28,10 +28,10 @@ import org.json.JSONObject
import java.io.File
import java.net.URLEncoder
import java.util.*
import kotlin.collections.ArrayList
object BrowserInstallHelper {
// 随便选的 32321 居然在部分 vivo 手机上被占用,喷了
private const val PORT = 40705
private const val RESERVE_PORT = 40706
@ -40,15 +40,12 @@ object BrowserInstallHelper {
private val mContext by lazy { HaloApp.getInstance().application }
private var mUseReservePort = false
private val mAllInstalledPackageList: ArrayList<String> by lazy {
PackageUtils.getAllPackageNameIncludeSystemApps(HaloApp.getInstance().applicationContext).apply {
add(HaloApp.getInstance().applicationContext.packageName)
}
}
private var mValidInstalledPackageList: ArrayList<String> = arrayListOf()
private var mValidConditionMatchedCache: Boolean? = null
private fun getServer(port: Int): DownloadServer {
val server = DownloadServer(port)
for (packageName in mAllInstalledPackageList) {
for (packageName in getAllInstalledPackageList()) {
if (packageName.contains("com.freeme") || packageName.contains("com.zhuoyi")) {
server.isBuggyDevice = true
break
@ -57,6 +54,23 @@ object BrowserInstallHelper {
return server
}
private fun getAllInstalledPackageList(): ArrayList<String> {
when {
mValidInstalledPackageList.isNotEmpty() -> {
return mValidInstalledPackageList
}
else -> {
val allInstalledPackageList = PackageUtils.getAllPackageNameIncludeSystemApps(mContext)
if (allInstalledPackageList.isNotEmpty()) {
mValidInstalledPackageList = allInstalledPackageList
}
return mValidInstalledPackageList
}
}
}
fun downloadFile(filePath: String) {
if (!::mServer.isInitialized) mServer = if (mUseReservePort) getServer(RESERVE_PORT) else getServer(PORT)
if (!mServer.isAlive && !startServer()) {
@ -80,7 +94,7 @@ object BrowserInstallHelper {
Base64.encodeToString(URLEncoder.encode(downloadUrl).trim().toByteArray(), Base64.NO_WRAP)
DirectUtils.directToExternalBrowser(
mContext,
"https://down-and.ghzs.com/redirect?location=base64($encodedString)"
"https://down-and.ghzs6.com/redirect?location=base64($encodedString)"
)
} else {
DirectUtils.directToExternalBrowser(mContext, downloadUrl)
@ -237,32 +251,43 @@ object BrowserInstallHelper {
* 是否满足开启浏览器安装的条件
*/
private fun isConditionMatched(settingsEntity: NewSettingsEntity): Boolean {
if (mValidConditionMatchedCache != null) {
return mValidConditionMatchedCache!!
}
val packageList = getAllInstalledPackageList()
if (packageList.isEmpty()) return false
settingsEntity.installModel?.whiteList?.let {
for (packageName in it) {
if (mAllInstalledPackageList.contains(packageName)) {
return false
if (packageList.contains(packageName)) {
mValidConditionMatchedCache = false
break
}
}
}
settingsEntity.installModel?.packages?.let {
for (packageName in it) {
if (mAllInstalledPackageList.contains(packageName)) {
return true
if (packageList.contains(packageName)) {
mValidConditionMatchedCache = true
break
}
}
}
// 匹配部分字符串即可
settingsEntity.installModel?.regexPackages?.let {
for (packageNamePieces in it) {
for (installedPackageName in mAllInstalledPackageList) {
for (installedPackageName in packageList) {
if (installedPackageName.contains(packageNamePieces)) {
return true
mValidConditionMatchedCache = true
break
}
}
}
}
return false
return mValidConditionMatchedCache ?: false
}
fun onApkInstalled(path: String?) {

View File

@ -98,7 +98,6 @@ import com.gh.gamecenter.feature.utils.PlatformUtils;
import com.gh.gamecenter.home.custom.model.CustomPageShareRepository;
import com.gh.gamecenter.home.skip.PackageSkipActivity;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.login.utils.QuickLoginHelper;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.packagehelper.PackageViewModel;
import com.gh.gamecenter.retrofit.RetrofitManager;
@ -137,9 +136,6 @@ import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
@ -285,8 +281,6 @@ public class MainActivity extends BaseActivity {
Config.getGhzsSettings();
} else if (Config.getVSettingEntity() == null) {
Config.refreshVSettingEntity();
} else if (Config.getVNewSettingEntity() == null) {
Config.getNewSetting();
}
// 耗时操作
@ -324,8 +318,7 @@ public class MainActivity extends BaseActivity {
mMainWrapperViewModel.requestAllDialogData();
// TODO 去掉一键登录?
QuickLoginHelper.getPhoneInfo();
// QuickLoginHelper.getPhoneInfo();
// TODO 搞清楚为什么这里要获取微信相关配置
WechatBindHelper.getWechatConfig(null);
@ -742,11 +735,14 @@ public class MainActivity extends BaseActivity {
ToastUtils.showToast("游戏启动中,请稍后~");
handler.postDelayed(() -> {
if(VHelper.isInnerInstalled(gamePackageName)) {
launchGame(gamePackageName).invoke();
} else {
VHelper.postOnInitialized(launchGame(gamePackageName));
}
VHelper.postOnInitialized(() -> {
if (VHelper.isInstalled(gamePackageName)) {
VHelper.launch(this, gamePackageName, false, true);
} else {
ToastUtils.showToast("应用已被卸载!");
}
return null;
});
}, 500);
break;
case KEY_MARKET_DETAILS:
@ -764,18 +760,6 @@ public class MainActivity extends BaseActivity {
}, 500);
}
@NonNull
private Function0<Unit> launchGame(String gamePackageName) {
return () -> {
if (!VHelper.isInnerInstalled(gamePackageName) && !VHelper.isInstalled(gamePackageName)) {
ToastUtils.showToast("应用已被卸载!");
} else {
VHelper.launch(this, gamePackageName, false, true);
}
return null;
};
}
/**
* 应用跳转
*/
@ -943,8 +927,6 @@ public class MainActivity extends BaseActivity {
Config.getGhzsSettings();
} else if (Config.getVSettingEntity() == null) {
Config.refreshVSettingEntity();
} else if (Config.getVNewSettingEntity() == null) {
Config.getNewSetting();
}
mPackageViewModel.checkData();
@ -955,10 +937,8 @@ public class MainActivity extends BaseActivity {
// 接收登录和登出更新事件统计的 Meta
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(EBReuse reuse) {
boolean isLoginEvent = reuse.getType().equals(LOGIN_TAG);
if (isLoginEvent || reuse.getType().equals(LOGOUT_TAG)) {
if (reuse.getType().equals(LOGIN_TAG) || reuse.getType().equals(LOGOUT_TAG)) {
MetaUtil.INSTANCE.refreshMeta();
VHelper.INSTANCE.updateAuthorizeInfo(isLoginEvent);
}
}

View File

@ -111,7 +111,7 @@ public class ShareCardActivity extends ToolBarActivity {
String qrBody;
if (!TextUtils.isEmpty(newsId)) {
qrBody = "http://www.ghzs666.com/article/" + newsId + ".html?source=appshare200";
qrBody = "https://www.ghzs666.com/article/" + newsId + ".html?source=appshare200";
} else {
qrBody = "https://www.ghzs.com/?source=appshare200";
}

View File

@ -166,7 +166,7 @@ public class ShareCardPicActivity extends ToolBarActivity {
String qrBody;
if (!TextUtils.isEmpty(newsId)) {
qrBody = "http://www.ghzs666.com/article/" + newsId + ".html?source=appshare200";
qrBody = "https://www.ghzs666.com/article/" + newsId + ".html?source=appshare200";
} else {
qrBody = "https://www.ghzs.com/?source=appshare200";
}

View File

@ -3,7 +3,6 @@ package com.gh.gamecenter;
import static com.gh.gamecenter.common.constant.EntranceConsts.ENTRANCE_BROWSER;
import static com.gh.gamecenter.common.constant.EntranceConsts.ENTRANCE_PUSH;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_ANSWER;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_ARCHIVE_LOGIN;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_ARTICLE;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_CATEGORY;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_COLUMN;
@ -22,7 +21,6 @@ import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_QQ_GAME;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_QQ_GROUP;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_QQ_QUN;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_QUESTION;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_RESTART_GAME;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_SUGGESTION;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_TOOLBOX;
import static com.gh.gamecenter.common.constant.EntranceConsts.HOST_UPLOAD_VIDEO;
@ -66,10 +64,8 @@ import com.gh.gamecenter.core.utils.ToastUtils;
import com.gh.gamecenter.entity.SubjectRecommendEntity;
import com.gh.gamecenter.entity.VideoLinkEntity;
import com.gh.gamecenter.feature.utils.PlatformUtils;
import com.gh.gamecenter.login.view.LoginActivity;
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel;
import com.gh.gamecenter.video.videomanager.VideoManagerActivity;
import com.gh.vspace.VHelper;
import com.gh.vspace.shortcut.OnCreateShortcutResult;
import com.gh.vspace.shortcut.ShortcutManager;
import com.gh.vspace.shortcut.ShortcutPermissionTipsDialog;
@ -409,27 +405,6 @@ public class SkipActivity extends BaseActivity {
} catch (JSONException ignored) {
}
break;
case HOST_ARCHIVE_LOGIN:
String gamePkg = uri.getQueryParameter(EntranceConsts.KEY_GAME_PKG);
if(CheckLoginUtils.isLogin()) {
VHelper.INSTANCE.updateAuthorizeInfo(true);
} else {
Bundle newBundle = new Bundle();
newBundle.putString(EntranceConsts.KEY_TO, LoginActivity.class.getName());
EntranceUtils.jumpActivity(this, null, newBundle, (resultCode, data) -> {
if(CheckLoginUtils.isLogin()) {
VHelper.INSTANCE.updateAuthorizeInfo(true);
}
VHelper.launch(this, gamePkg, false, false);
finish();
});
return;
}
break;
case HOST_RESTART_GAME:
String restartGamePkg = uri.getQueryParameter(EntranceConsts.KEY_GAME_PKG);
VHelper.launch(this, restartGamePkg, false, true);
break;
default:
EntranceUtils.jumpActivity(this, new Bundle()); // 跳转至首页
return;

View File

@ -197,15 +197,7 @@ class SplashScreenActivity : BaseActivity() {
// 尝试获取安装应用列表权限并启动首页(不在乎结果)
private fun requestGetInstallListPermissionAndLaunchMainActivity() {
if (PackageUtils.isSupportGetInstalledAppsPermission(this)
&& PermissionHelper.isGetInstalledListPermissionDisabled(this)
) {
PermissionHelper.requestGetInstalledAppsListPermission(this, true) {
launchMainActivity()
}
} else {
launchMainActivity()
}
launchMainActivity()
}
// 删除更新后的光环助手包

View File

@ -18,6 +18,7 @@ import android.widget.TextView;
import androidx.collection.ArrayMap;
import androidx.core.content.ContextCompat;
import com.gh.common.util.PackageHelper;
import com.gh.common.util.PackageInstaller;
import com.gh.common.util.PackageUtils;
import com.gh.gamecenter.R;
@ -188,7 +189,7 @@ public class CleanApkAdapter extends BaseRecyclerAdapter<KcSelectGameViewHolder>
}
private int doType(String packageName) {
List<PackageInfo> pakageinfos = PackageUtils.getInstalledPackages(mContext, 0);
List<PackageInfo> pakageinfos = PackageHelper.INSTANCE.getInstalledPackages(mContext, 0);
for (PackageInfo pi : pakageinfos) {
if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
String pi_packageName = pi.packageName;

View File

@ -89,7 +89,7 @@ class AuthorizationActivity : ToolBarActivity() {
}
private fun initData() {
if (mToken.isNotEmpty()) return
if (mToken.isNotEmpty() || isFinishing) return
val loadingDialog = DialogUtils.showWaitDialog(this, "请稍后...")
mViewModel.getAccessToken(listOf(mContent), {
mToken = it

View File

@ -153,7 +153,7 @@ class NewInstalledGameFragment : ToolbarFragment() {
reuseNoneData.reuseNoneDataDescTv.text = " 及时获悉游戏最新的更新消息"
reuseNoneData.reuseResetLoadTv.text = "去开启"
reuseNoneData.reuseResetLoadTv.setOnClickListener {
PermissionHelper.requestGetInstalledAppsListPermission(requireActivity()) {
PermissionHelper.showGetInstalledAppsListPermissionDialogAndRequestPermission(requireActivity()) {
updateNoDataView()
PackageRepository.initData()
}

View File

@ -4,7 +4,6 @@ import android.view.View
import com.gh.common.exposure.ExposureListener
import com.gh.common.util.DirectUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.MainActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.EntranceConsts
@ -12,12 +11,10 @@ import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.FixLinearLayoutManager
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.EmptyCallback
import com.gh.gamecenter.databinding.FragmentGameUpdatableBinding
import com.gh.gamecenter.eventbus.EBDownloadStatus
import com.gh.gamecenter.packagehelper.PackageRepository
import com.gh.gamecenter.packagehelper.PackageViewModel
import com.gh.gamecenter.wrapper.MainWrapperFragment
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import org.greenrobot.eventbus.Subscribe
@ -40,7 +37,6 @@ class UpdatableGameFragment : LazyFragment() {
}
}
override fun getRealLayoutId() = R.layout.fragment_game_updatable
override fun onRealLayoutInflated(inflatedView: View) {
mBinding = FragmentGameUpdatableBinding.bind(inflatedView)
@ -104,15 +100,14 @@ class UpdatableGameFragment : LazyFragment() {
noDataContainer.reuseNoneDataDescTv.text = "及时获悉游戏最新的更新消息"
noDataContainer.reuseResetLoadTv.text = "去开启"
noDataContainer.reuseResetLoadTv.setOnClickListener {
PermissionHelper.requestGetInstalledAppsListPermission(
requireActivity(),
false,
object : EmptyCallback {
override fun onCallback() {
updateNoDataView()
PackageRepository.initData()
}
})
PermissionHelper.showGetInstalledAppsListPermissionDialogAndRequestPermission(
requireActivity()
) { isGranted ->
if (isGranted) {
updateNoDataView()
PackageRepository.initData()
}
}
}
} else {
noDataContainer.reuseNoneDataIv.visibility = View.VISIBLE

View File

@ -34,9 +34,7 @@ class AppEntity(
*/
var alert: String? = null,
// 关联64位更新
var relation: AppEntity? = null,
@SerializedName("_id")
var id: String? = null
var relation: AppEntity? = null
) : Parcelable {
fun isAlertEveryTime() = alert == "EVERY_TIME_OPEN"

View File

@ -1,42 +0,0 @@
package com.gh.gamecenter.entity
import com.google.gson.annotations.SerializedName
class VNewSetting {
@SerializedName("va")
var va: Va? = null
@SerializedName("va_plugin")
var vaPlugin: VaPlugin? = null
class Va(
@SerializedName("32-bit")
val arch32: VaArch? = null,
)
class VaArch(
val size: String,
@SerializedName("package")
val packageName: String,
@SerializedName("version")
val versionName: String,
@SerializedName("version_code")
val versionCode: Int,
val url: String
)
data class VaPlugin(
@SerializedName("_id")
val id: String?,
@SerializedName("version_name")
val versionName: String?,
@SerializedName("change_log")
var changeLog: String?,
@SerializedName("url_32")
val url32: String?,
@SerializedName("url_64")
val url64: String?,
)
}

View File

@ -413,7 +413,7 @@ class ArticleItemVideoView @JvmOverloads constructor(context: Context, attrs: At
val shareUrl = if (isPublishEnv()) {
"https://m.ghzs666.com/video/${it.id}"
} else {
"https://resource.ghzs.com/page/video_play/video/video.html?video=${it.id}"
"https://dev-and-static.ghzs66.com/page/video_play/video/video.html?video=${it.id}"
}
val additionalParams = AdditionalParamsEntity().apply {
contentType = "视频帖"

View File

@ -45,6 +45,12 @@ class UpdateDialogFragment : BaseDialogFragment() {
private var mIsDisplayingDownloadingStyle = false // 是否正在显示更新中样式
private val mDataWatcher = object : DataWatcher() {
override fun onDataInit(downloadEntity: DownloadEntity) {
super.onDataInit(downloadEntity)
onDataChanged(downloadEntity)
}
override fun onDataChanged(downloadEntity: DownloadEntity) {
if (downloadEntity.name.contains("光环助手")) {
if (mIsDisplayingDownloadingStyle) {
@ -74,13 +80,11 @@ class UpdateDialogFragment : BaseDialogFragment() {
return
}
DownloadManager.getInstance().addObserver(mDataWatcher)
mUpdateEntity = arguments?.getParcelable(UPDATE_ENTITY)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
showUpdateHintStyle(requireContext(), mUpdateEntity!!)
showUpdateHintStyle(requireContext(), mUpdateEntity!!, true)
return mBinding.root
}
@ -109,8 +113,14 @@ class UpdateDialogFragment : BaseDialogFragment() {
mDismissCallback?.onCallback()
}
override fun onDestroyView() {
super.onDestroyView()
override fun onStart() {
super.onStart()
DownloadManager.getInstance().addObserver(mDataWatcher)
}
override fun onStop() {
super.onStop()
DownloadManager.getInstance().removeObserver(mDataWatcher)
}
@ -120,7 +130,9 @@ class UpdateDialogFragment : BaseDialogFragment() {
* @param context 上下文
* @param updateEntity 更新实体
*/
private fun showUpdateHintStyle(context: Context, updateEntity: AppEntity) {
private fun showUpdateHintStyle(context: Context,
updateEntity: AppEntity,
invokeByViewCreated: Boolean) {
mIsDisplayingDownloadingStyle = false
val updateHintBinding = mBinding.updateHintContainerView
@ -200,12 +212,15 @@ class UpdateDialogFragment : BaseDialogFragment() {
)
}
SensorsBridge.trackVersionUpdateDialogShow(
keyDialogReminderTime = mUpdateEntity?.alert,
keyDialogClose = if (mUpdateEntity?.isForce == true) "关闭且强退" else "仅关闭"
)
if (invokeByViewCreated) {
SensorsBridge.trackVersionUpdateDialogShow(
keyDialogReminderTime = mUpdateEntity?.alert,
keyDialogClose = if (mUpdateEntity?.isForce == true) "关闭且强退" else "仅关闭"
)
DataLogUtils.uploadUpgradeLog(context, "notice") //上传更新通知弹窗数据
}
DataLogUtils.uploadUpgradeLog(context, "notice") //上传更新通知弹窗数据
}
/**
@ -294,13 +309,8 @@ class UpdateDialogFragment : BaseDialogFragment() {
if (DownloadStatus.done == downloadEntity.status) {
DownloadManager.getInstance().cancel(downloadEntity.url, false, true, false)
try {
dismiss()
} catch (ignored: IllegalArgumentException) {
// do nothing
}
if (updateEntity.isForce) {
AppExecutor.uiExecutor.executeWithDelay({ UpdateHelper.exitApp() }, 1000L)
tryWithDefaultCatch {
showUpdateHintStyle(requireContext(), updateEntity, false)
}
} else if (DownloadStatus.neterror == downloadEntity.status) {
ToastUtils.toast("网络错误,请稍后重试")

View File

@ -282,10 +282,10 @@ class RatingEditActivity : ToolBarActivity(), KeyboardHeightObserver {
}
}
mBinding.mWebView.addJavascriptObject(DefaultJsApi(this), null)
val url = if ("internal" == BuildConfig.FLAVOR) {
"https://resource.ghzs.com/page/comment_tag_editor_dev/index.html?timestamp=${System.currentTimeMillis()}"
val url = if (PackageFlavorHelper.IS_TEST_FLAVOR) {
"https://dev-and-static.ghzs66.com/page/comment_tag_editor/index.html?timestamp=${System.currentTimeMillis()}"
} else {
"https://resource.ghzs.com/page/comment_tag_editor/index.html?timestamp=${System.currentTimeMillis()}"
"https://and-static.ghzs66.com/page/comment_tag_editor/index.html?timestamp=${System.currentTimeMillis()}"
}
mBinding.mWebView.loadUrl(url)
}

View File

@ -47,7 +47,9 @@ class CustomHomeSlideListItemViewHolder(val binding: HomeSlideListItemCustomBind
GameItemViewHolder.initGameSubtitleAndAdLabel(it, binding.includeGame.gameSubtitleTv)
}
binding.bottomGradient.visibility = View.GONE
if (homeSlide.image != binding.slideBackground.tag) {
binding.bottomGradient.visibility = View.GONE
}
binding.slideBackground.setTag(ImageUtils.TAG_TARGET_WIDTH, mImageWith)
ImageUtils.displayWithCallback(
binding.slideBackground,

View File

@ -53,7 +53,9 @@ class CustomHomeSubSlideListItemViewHolder(val binding: HomeSubSlideListItemCust
val startColor = Color.HSVToColor(colorHSV)
val endColor = ColorUtils.setAlphaComponent(startColor, 0)
binding.slideMask.visibility = View.GONE
if (homeSlide.image != binding.slideBackground.tag) {
binding.slideMask.visibility = View.GONE
}
binding.slideMask.background = GradientDrawable().apply {
gradientType = GradientDrawable.LINEAR_GRADIENT
orientation = GradientDrawable.Orientation.BOTTOM_TOP
@ -67,7 +69,9 @@ class CustomHomeSubSlideListItemViewHolder(val binding: HomeSubSlideListItemCust
homeSlide.image,
object : BaseControllerListener<ImageInfo>() {
override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
binding.slideMask.visibility = View.VISIBLE
if (homeSlide.placeholderColor.isNotEmpty() && homeSlide.linkGame != null) {
binding.slideMask.visibility = View.VISIBLE
}
}
}
)

View File

@ -8,7 +8,10 @@ import com.facebook.drawee.controller.BaseControllerListener
import com.facebook.imagepipeline.image.ImageInfo
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.utils.RandomUtils
import com.gh.gamecenter.databinding.HomeSlideListItemBinding
import com.gh.gamecenter.entity.HomeSlide
@ -44,7 +47,9 @@ class HomeSlideListItemViewHolder(val binding: HomeSlideListItemBinding) : BaseR
GameItemViewHolder.initGameSubtitleAndAdLabel(it, binding.includeGame.gameSubtitleTv)
}
binding.bottomGradient.visibility = View.GONE
if (homeSlide.image != binding.slideBackground.tag) {
binding.bottomGradient.visibility = View.GONE
}
binding.slideBackground.setTag(ImageUtils.TAG_TARGET_WIDTH, mImageWith)
ImageUtils.displayWithCallback(
binding.slideBackground,

View File

@ -53,7 +53,9 @@ class HomeSubSlideListItemViewHolder(val binding: HomeSubSlideListItemBinding) :
val startColor = Color.HSVToColor(colorHSV)
val endColor = ColorUtils.setAlphaComponent(startColor, 0)
binding.slideMask.visibility = View.GONE
if (homeSlide.image != binding.slideBackground.tag) {
binding.slideMask.visibility = View.GONE
}
binding.slideMask.background = GradientDrawable().apply {
gradientType = GradientDrawable.LINEAR_GRADIENT
orientation = GradientDrawable.Orientation.BOTTOM_TOP
@ -67,7 +69,9 @@ class HomeSubSlideListItemViewHolder(val binding: HomeSubSlideListItemBinding) :
homeSlide.image,
object : BaseControllerListener<ImageInfo>() {
override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
binding.slideMask.visibility = View.VISIBLE
if (homeSlide.placeholderColor.isNotEmpty() && homeSlide.linkGame != null) {
binding.slideMask.visibility = View.VISIBLE
}
}
}
)

View File

@ -16,7 +16,6 @@ import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.ObservableUtil
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.secondOrNull
import com.gh.gamecenter.common.utils.toArrayList
import com.gh.gamecenter.common.utils.tryCatchInRelease
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.core.utils.SPUtils
@ -27,7 +26,6 @@ import com.gh.gamecenter.livedata.Event
import com.gh.gamecenter.manager.PackagesManager
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.vspace.VHelper
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
@ -60,8 +58,6 @@ object PackageRepository {
@Volatile
private var mIsInitialisingData = false
var installedPkgRefreshed = false
var vaPkgRefreshed = false
val gameUpdateLiveData = MutableLiveData<List<GameUpdateEntity>>()
val gameInstalledLiveData = MutableLiveData<List<GameInstall>>()
@ -83,20 +79,13 @@ object PackageRepository {
*/
@JvmStatic
fun initData() {
Utils.log("xxx", "PackageRepository::initData::mIsInitialisingData = $mIsInitialisingData")
if (mIsInitialisingData) return
mIsInitialisingData = true
installedPkgRefreshed = false
vaPkgRefreshed = false
runOnIoThread {
if (gameInstalled.isNotEmpty()) gameInstalled.clear()
if (mInstalledGameList.isNotEmpty()) mInstalledGameList.clear()
if (gameUpdate.isNotEmpty()) {
gameUpdate.clear()
Utils.log("xxx", "清除更新数据")
}
if (gameUpdate.isNotEmpty()) gameUpdate.clear()
if (mInstalledPkgList.isNotEmpty()) mInstalledPkgList.clear()
val list = PackageUtils.getAllPackageName(mApplication)
@ -104,38 +93,15 @@ object PackageRepository {
uploadAppList()
initFilterPackage(list) { filteredList ->
mIsInitialisingData = false
mInstalledPkgList.addAll(filteredList)
notifyInstallPkgData()
Utils.log("xxx", "PackageRepository::filteredList::${filteredList}")
loadInstalledGameDigestAndNotifyData(filteredList) {
installedPkgRefreshed = true
mIsInitialisingData = !(installedPkgRefreshed && vaPkgRefreshed)
}
loadInstalledGameDigestAndNotifyData(filteredList)
}
loadGhzsUpdate()
// 畅玩游戏更新
var allGames = VHelper.getAllVGameSnapshots()
if (allGames.isNullOrEmpty()) {
VHelper.refreshVGameSnapshot()
allGames = VHelper.getAllVGameSnapshots()
}
val allGamePkgNames = allGames.map { it.packageName }.toArrayList()
if (allGamePkgNames.isNotEmpty()) {
notifyInstallPkgData()
updateFilterPackage(allGamePkgNames) {
Utils.log("xxx", "PackageRepository::filteredList::${allGamePkgNames}")
loadInstalledGameDigestAndNotifyData(
filteredList = allGamePkgNames,
onWorkerThreadOnly = false,
isVGame = true
) {
vaPkgRefreshed = true
mIsInitialisingData = !(installedPkgRefreshed && vaPkgRefreshed)
}
}
}
}
}
@ -168,8 +134,7 @@ object PackageRepository {
PackageUtils.getGhVersionName(),
PackageUtils.getGhVersionCode(),
HaloApp.getInstance().channel,
Build.VERSION.SDK_INT
)
Build.VERSION.SDK_INT)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Response<AppEntity>() {
@ -244,7 +209,6 @@ object PackageRepository {
filteredList: ArrayList<String>,
onWorkerThreadOnly: Boolean = false,
isVGame: Boolean = false,
loadFinishCallback: (() -> Unit)? = null
) {
var isNotifyUpdate = false
val maxPageCount = (filteredList.size / PAGE_SIZE) + 1
@ -253,7 +217,6 @@ object PackageRepository {
val latch = ObservableUtil.latch(maxPageCount, {
if (isNotifyUpdate || gameUpdateLiveData.value == null) notifyGameUpdateData()
notifyGameInstallData()
loadFinishCallback?.invoke()
}, Any())
while (++page <= maxPageCount) {

View File

@ -3,10 +3,9 @@ package com.gh.gamecenter.packagehelper
import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.*
import com.gh.gamecenter.entity.GameUpdateEntity
import com.gh.gamecenter.feature.entity.GameInstall
import com.gh.gamecenter.entity.GameUpdateEntity
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import kotlin.collections.set
class PackageViewModel(
@ -80,7 +79,6 @@ class PackageViewModel(
if (mRepository.gameInstalled.size == 0
|| PackageFilterManager.hasPendingPackage()
) {
Utils.log("xxx", "PackageViewModel call initData")
mRepository.initData()
}
}

View File

@ -60,7 +60,7 @@ import com.gh.gamecenter.room.AppDatabase
import com.gh.gamecenter.setting.SettingBridge
import com.gh.gamecenter.wrapper.MainWrapperFragment
import com.gh.gamecenter.wrapper.MainWrapperViewModel
import com.gh.vspace.ITestCase
import com.gh.vspace.IExternalGamesUsage
import com.google.android.material.appbar.AppBarLayout
import com.halo.assistant.HaloApp
import com.jakewharton.rxbinding2.view.RxView
@ -695,11 +695,7 @@ class HaloPersonalFragment : BaseLazyFragment() {
(try {
Class.forName("com.gh.vspace.ExternalGameUsage")?.newInstance()
} catch (e: Exception) {
} as? ITestCase)?.apply {
addInstallExternalGameButton(mStubBinding.otherItems)
addInstallPluginButton(mStubBinding.otherItems)
addInstallPlugin32Button(mStubBinding.otherItems)
}
} as? IExternalGamesUsage)?.addInstallExternalGameButton(mStubBinding.otherItems)
}
mStubBinding.settingItem.run {

View File

@ -90,9 +90,6 @@ class UserHomeFragment : ToolbarFragment() {
getUserInfo()
getBadgeList()
getUserPlayedGameCount()
if (PackageFlavorHelper.IS_TEST_FLAVOR) {
getUserLevel()
}
}
mHomeBinding?.container?.setZoomView(mHomeBinding?.userBackgroundContainer)
@ -167,38 +164,12 @@ class UserHomeFragment : ToolbarFragment() {
if (mUserHomeViewModel.userId == UserManager.getInstance().userId) {
mUserHomeViewModel.availableBadges()
}
// if (mUserHomeViewModel.userId == UserManager.getInstance().userId) {
// mUserHomeViewModel.availableBadges()
// } else {
// mHomeBinding?.userBadgeTips?.visibility = View.VISIBLE
// if (it.isNotEmpty()) {
// mHomeBinding?.userBadge?.visibility = View.VISIBLE
// updateUserBadge(it)
// } else {
// mHomeBinding?.userBadge?.visibility = View.GONE
// }
// }
}
mUserHomeViewModel.availableBadgeCount.observeNonNull(this) {
mHomeBinding?.badgeTips?.visibility = if (it > 0) View.VISIBLE else View.GONE
}
// mUserHomeViewModel.availableBadgeCount.observeNonNull(this) {
// mHomeBinding?.viewBadgeMessageTip?.visibleIf(it > 0)
// if (mUserHomeViewModel.badges.value?.isEmpty() == true && it > 0) {
// mHomeBinding?.userBadgeList?.visibility = View.INVISIBLE
// mHomeBinding?.userBadgeTips?.visibility = View.VISIBLE
// mHomeBinding?.userBadgeTips?.text = "有${it}枚徽章可领取"
// } else if (mUserHomeViewModel.badges.value?.isEmpty() == false) {
// mHomeBinding?.userBadgeList?.visibility = View.VISIBLE
// mHomeBinding?.userBadgeTips?.visibility = View.GONE
// updateUserBadge(mUserHomeViewModel.badges.value!!)
// }
// }
mUserHomeViewModel.networkError.observeNonNull(this) {
mHomeBinding?.container?.visibility = View.GONE
mHomeBinding?.reuseNoConnection?.root?.visibility = View.VISIBLE
@ -214,28 +185,10 @@ class UserHomeFragment : ToolbarFragment() {
mPlayGameCount = it
})
mUserHomeViewModel.level.observeNonNull(this) {
mHomeBinding?.run {
levelContainer.visibility = View.VISIBLE
levelContainer.setOnClickListener {
if (mUserHomeViewModel.userId == UserManager.getInstance().userId) {
IntegralLogHelper.run {
log("click_grade_label", LOCATION)
log("view_grade", "等级中心页")
}
DirectUtils.directToLevelPage(requireContext())
}
}
val levelNum = if (it > 9) 9 else it
levelTv.text = "Lv$levelNum "
}
}
mMessageUnreadViewModel.liveData.observeNonNull(this) {
updateUnreadInfo(it)
}
mUserViewModel.editObsUserinfo.observeNonNull(this) {
it.data?.let { updatedUserInfo ->
if (mUserHomeViewModel.userId == UserManager.getInstance().userId) {
@ -542,7 +495,6 @@ class UserHomeFragment : ToolbarFragment() {
// 跳转更换背景页
userChangeBgBtn.setOnClickListener {
IntegralLogHelper.log("click_change _background", LOCATION)
SPUtils.setBoolean(Constants.SP_HAS_CLICK_CHANGE_BG, false)
changeBgTips.visibility = View.GONE
startActivity(PersonalityBackgroundActivity.getIntent(requireContext()))

View File

@ -33,7 +33,6 @@ class UserHomeViewModel(application: Application, var userId: String) : AndroidV
var availableBadge = MutableLiveData<BadgeEntity>()
var availableBadgeCount = MutableLiveData<Int>()
var playGamesCount = MutableLiveData<Int>()
var level = MutableLiveData<Int>()
fun getUserInfo() {
RetrofitManager.getInstance()
@ -133,19 +132,6 @@ class UserHomeViewModel(application: Application, var userId: String) : AndroidV
})
}
@SuppressLint("CheckResult")
fun getUserLevel() {
RetrofitManager.getInstance()
.api.getUserLevels(userId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : BiResponse<JsonObject>() {
override fun onSuccess(data: JsonObject) {
level.postValue(data["level"].asInt)
}
})
}
@SuppressLint("CheckResult")
fun postReport(reason: String, desc: String) {
val requestMap = hashMapOf<String, String>()

View File

@ -1,65 +0,0 @@
package com.gh.gamecenter.personalhome.rating
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.ViewModelProviders
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListActivity
import com.gh.gamecenter.common.baselist.NormalListViewModel
import com.gh.gamecenter.common.utils.updateStatusBarColor
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Single
class RatingActivity : ListActivity<MyRating, NormalListViewModel<MyRating>>() {
private var mAdapter: RatingAdapter? = null
private var mUserId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
mUserId = intent.getStringExtra(EntranceConsts.KEY_USER_ID)
super.onCreate(savedInstanceState)
if (mUserId == UserManager.getInstance().userId) {
setNavigationTitle("我的评分")
} else {
setNavigationTitle("Ta的评分")
}
updateStatusBarColor(R.color.ui_surface, R.color.ui_surface)
}
override fun provideListAdapter(): RatingAdapter {
if (mAdapter == null) mAdapter = RatingAdapter(this, mEntrance, mListViewModel)
return mAdapter!!
}
override fun provideDataSingle(page: Int): Single<MutableList<MyRating>> {
return RetrofitManager.getInstance().api.getMyRating(mUserId, page, "view:default")
}
override fun provideListViewModel(): NormalListViewModel<MyRating> {
val factory = NormalListViewModel.Factory(HaloApp.getInstance().application, this)
return ViewModelProviders.of(this, factory)
.get(NormalListViewModel::class.java) as NormalListViewModel<MyRating>
}
override fun isAutoResetViewBackgroundEnabled(): Boolean = true
override fun onDarkModeChanged() {
super.onDarkModeChanged()
updateStatusBarColor(R.color.ui_surface, R.color.ui_surface)
}
companion object {
fun getIntent(context: Context, userId: String, entrance: String, path: String): Intent {
val intent = Intent(context, RatingActivity::class.java)
intent.putExtra(EntranceConsts.KEY_ENTRANCE, BaseActivity.mergeEntranceAndPath(entrance, path))
intent.putExtra(EntranceConsts.KEY_USER_ID, userId)
return intent
}
}
}

View File

@ -1,88 +0,0 @@
package com.gh.gamecenter.personalhome.rating
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.common.util.NewsUtils
import com.gh.gamecenter.core.utils.NumberUtils
import com.gh.gamecenter.common.utils.fromHtml
import com.gh.gamecenter.common.utils.setTextWithHighlightedTextWrappedInsideWrapper
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.adapter.viewholder.PersonalHomeRatingViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.NormalListViewModel
import com.gh.gamecenter.databinding.PersonalHomeRatingBinding
class RatingAdapter(
context: Context,
private val mEntrance: String,
private val mListViewModel: NormalListViewModel<MyRating>
) : ListAdapter<MyRating>(context) {
override fun getItemViewType(position: Int): Int {
return if (position == itemCount - 1) {
ItemViewType.ITEM_FOOTER
} else {
ItemViewType.ITEM_BODY
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view: View
return when (viewType) {
ItemViewType.ITEM_FOOTER -> {
view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false)
FooterViewHolder(view)
}
else -> {
view = mLayoutInflater.inflate(R.layout.personal_home_rating, parent, false)
PersonalHomeRatingViewHolder(PersonalHomeRatingBinding.bind(view))
}
}
}
override fun getItemCount(): Int {
return if (mEntityList == null || mEntityList.isEmpty()) 0 else mEntityList.size + 1
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is PersonalHomeRatingViewHolder -> {
val entity = mEntityList[holder.adapterPosition]
val historyEntity = entity.transformHistoryEntity()
holder.binding.comment.text =
if (historyEntity.count.reply > 0) NumberUtils.transSimpleCount(historyEntity.count.reply) else ""
holder.binding.vote.isChecked = historyEntity.me.isVoted
holder.binding.vote.text =
if (historyEntity.count.vote > 0) NumberUtils.transSimpleCount(historyEntity.count.vote) else ""
holder.binding.ratingStart.rating = historyEntity.comment.star.toFloat()
holder.binding.userCommand.text = (mContext.getString(
R.string.personal_home_rating_command,
NewsUtils.getFormattedTime(entity.time),
entity.game.name
)).fromHtml()
holder.binding.content.setTextWithHighlightedTextWrappedInsideWrapper(
text = entity.content,
copyClickedText = true
)
holder.itemView.setOnClickListener {
GameDetailActivity.startGameDetailActivity(
mContext,
entity.game.id,
mEntrance,
isSkipGameComment = true
)
}
}
is FooterViewHolder -> {
holder.initItemPadding()
holder.initFooterViewHolder(mListViewModel, mIsLoading, mIsNetworkError, mIsOver)
}
}
}
}

View File

@ -1,71 +0,0 @@
package com.gh.gamecenter.qa.answer.detail;
import static com.gh.gamecenter.common.constant.Constants.GAME_DETAIL_COME_IN;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import com.gh.gamecenter.common.base.activity.ToolBarActivity;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.entity.SpecialColumn;
import com.halo.assistant.HaloApp;
/**
* Created by khy on 10/04/18.
*/
public class AnswerDetailActivity extends ToolBarActivity {
public static final String TAG = "AnswerDetailActivity";
@Override
public boolean showToolbarAtLeft() {
if (HaloApp.get(GAME_DETAIL_COME_IN, false) != null) {
return true;
}
return super.showToolbarAtLeft();
}
@NonNull
public static Intent getIntent(Context context, String answerId, String entrance, String path) {
return getIntent(context, answerId, entrance, path, false, null);
}
@NonNull
public static Intent getIntent(Context context, String answerId, String entrance, String path, boolean isOpenCommentManager) {
return getIntent(context, answerId, entrance, path, isOpenCommentManager, null);
}
@NonNull
public static Intent getIntent(Context context, String answerId, String entrance, String path, SpecialColumn specialColumn) {
return getIntent(context, answerId, entrance, path, false, specialColumn);
}
@NonNull
public static Intent getIntent(Context context, String answerId, String entrance, String path, boolean isOpenCommentManager, SpecialColumn specialColumn) {
Bundle bundle = new Bundle();
bundle.putString(EntranceConsts.KEY_ANSWER_ID, answerId);
bundle.putString(EntranceConsts.KEY_ENTRANCE, mergeEntranceAndPath(entrance, path));
bundle.putBoolean(EntranceConsts.KEY_SHOW_ANSWER_COMMENT, isOpenCommentManager);
bundle.putString(EntranceConsts.KEY_PATH, path);
bundle.putParcelable(EntranceConsts.KEY_DATA, specialColumn);
return getTargetIntent(context, AnswerDetailActivity.class, AnswerDetailContainerFragment.class, bundle);
}
@NonNull
public static Intent getRecommendsIntent(Context context, String answerId, String entrance, String path) {
Bundle bundle = new Bundle();
bundle.putString(EntranceConsts.KEY_ANSWER_ID, answerId);
bundle.putString(EntranceConsts.KEY_ENTRANCE, mergeEntranceAndPath(entrance, path));
bundle.putBoolean(EntranceConsts.KEY_RECOMMENDS_CONTENTS, true);
bundle.putString(EntranceConsts.KEY_PATH, path);
return getTargetIntent(context, AnswerDetailActivity.class, AnswerDetailContainerFragment.class, bundle);
}
@Override
protected Intent provideNormalIntent() {
return getTargetIntent(this, AnswerDetailActivity.class, AnswerDetailContainerFragment.class);
}
}

View File

@ -1,121 +0,0 @@
package com.gh.gamecenter.qa.answer.detail
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.common.util.SyncDataBetweenPageHelper
import com.gh.gamecenter.common.utils.observeNonNull
import com.gh.gamecenter.common.utils.viewModelProviderFromParent
import com.gh.gamecenter.databinding.FragmentAnswerDetailContainerBinding
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
class AnswerDetailContainerFragment : ToolbarFragment() {
private lateinit var mFragmentAdapter: AnswerDetailFragmentStatePagerAdapter
private lateinit var mContainerViewModel: AnswerDetailContainerViewModel
private lateinit var mBinding: FragmentAnswerDetailContainerBinding
private val fragments = ArrayList<AnswerDetailFragment>()
// 是否已经传了 argument 给第一个子 fragment
private var mHasPassedOneTimeArgumentToChild = false
override fun getLayoutId(): Int = 0
override fun getInflatedLayout(): View {
return FragmentAnswerDetailContainerBinding.inflate(LayoutInflater.from(requireContext()), null, false).apply {
mBinding = this
}.root
}
override fun onMenuItemClick(menuItem: MenuItem?) {
fragmentManager?.fragments?.let {
for (fragment in it) {
if (fragment is AnswerDetailFragment && fragment.isResumed) {
fragment.onMenuItemClick(menuItem!!)
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mContainerViewModel = viewModelProviderFromParent()
val answerId = arguments?.getString(EntranceConsts.KEY_ANSWER_ID) ?: ""
if (!mContainerViewModel.answerIdList.contains(answerId)) {
mContainerViewModel.answerIdList.add(answerId)
}
val tag = "android:switcher:${mBinding.viewpager.id}:"
mFragmentAdapter = AnswerDetailFragmentStatePagerAdapter(parentFragmentManager) { id, position ->
var fragment = childFragmentManager.findFragmentByTag("${tag}${position}") as? AnswerDetailFragment
if (fragment == null) {
fragment = AnswerDetailFragment().apply {
if (mHasPassedOneTimeArgumentToChild) {
this@AnswerDetailContainerFragment.arguments?.putBoolean(
EntranceConsts.KEY_SHOW_ANSWER_COMMENT,
false
)
this@AnswerDetailContainerFragment.arguments?.putBoolean(
EntranceConsts.KEY_RECOMMENDS_CONTENTS,
false
)
}
// 将外部的 argument 传给里面的 fragment
this.arguments = this@AnswerDetailContainerFragment.arguments
this.arguments?.putString(EntranceConsts.KEY_ANSWER_ID, id)
mHasPassedOneTimeArgumentToChild = true
fragments.add(this)
}
}
fragment
}
mFragmentAdapter.answerIdList = ArrayList(mContainerViewModel.answerIdList)
mBinding.viewpager.adapter = mFragmentAdapter
mContainerViewModel.answerListChange.observeNonNull(this) {
mFragmentAdapter.answerIdList = ArrayList(mContainerViewModel.answerIdList)
try {
mFragmentAdapter.notifyDataSetChanged()
} catch (e: Exception) {
e.printStackTrace()
}
}
mContainerViewModel.scroll.observeNonNull(this) {
val currentItem = mBinding.viewpager.currentItem
when (it) {
AnswerDetailContainerViewModel.SCROLL_TO_NEXT_ANSWER -> {
if (currentItem == mContainerViewModel.answerIdList.size) {
toast("到底了")
return@observeNonNull
} else {
mBinding.viewpager.currentItem = currentItem + 1
}
}
AnswerDetailContainerViewModel.SCROLL_TO_PREVIOUS_ANSWER -> {
if (currentItem == mContainerViewModel.answerIdList.size) {
toast("到顶了")
return@observeNonNull
} else {
mBinding.viewpager.currentItem = currentItem - 1
}
}
}
}
}
override fun onBackPressed(): Boolean {
val answerDetail = fragments[0].mViewModel.answerDetail
if (SyncDataBetweenPageHelper.setResultAndFinish(requireActivity(), answerDetail)) {
return true
}
return super.onBackPressed()
}
}

View File

@ -48,7 +48,6 @@ import com.gh.gamecenter.feature.entity.Questions
import com.gh.gamecenter.feature.entity.UserEntity
import com.gh.gamecenter.help.HelpAndFeedbackBridge
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.answer.edit.AnswerEditActivity
import com.gh.gamecenter.qa.comment.CommentActivity
import com.gh.gamecenter.qa.dialog.MoreFunctionPanelDialog
import com.gh.gamecenter.qa.editor.OnLinkClickListener
@ -854,44 +853,6 @@ open class AnswerDetailFragment : ToolbarFragment() {
}
}
}
mBinding.statusTv.setOnClickListener {
mViewModel.answerDetail?.let {
when (mAnswerStatus) {
ANSWERED_MY_ANSWER -> editAnswer(it)
ANSWERED_NOT_MY_ANSWER -> {
startActivityForResult(
AnswerDetailActivity.getIntent(
context,
mViewModel.answerDetail!!.me.myAnswerId,
mEntrance,
"答案详情"
), ANSWER_PATCH_REQUEST
)
}
NOT_ANSWERED_YET -> ifLogin("回答详情-[我来回答]") {
checkStoragePermissionBeforeAction {
val question = mViewModel.answerDetail!!.question
startActivityForResult(
AnswerEditActivity.getIntent(requireContext(), question, true, question.communityName),
ANSWER_POST_REQUEST
)
}
}
NOT_ANSWERED_BUT_HAVE_DRAFT -> ifLogin("回答详情-[继续回答]") {
checkStoragePermissionBeforeAction {
val question = mViewModel.answerDetail!!.question
startActivityForResult(
AnswerEditActivity.getIntent(requireContext(), question, true, question.communityName),
ANSWER_POST_REQUEST
)
}
}
}
}
}
mBinding.userIconIv.setOnClickListener {
DirectUtils.directToHomeActivity(requireContext(), mViewModel.answerDetail!!.user.id, mEntrance, "回答详情")
}
@ -1014,19 +975,6 @@ open class AnswerDetailFragment : ToolbarFragment() {
requireActivity().startActivityForResult(intent, CommentActivity.REQUEST_CODE)
}
private fun editAnswer(answerDetail: AnswerDetailEntity) {
startActivityForResult(
AnswerEditActivity.getIntent(
requireContext(),
mAnswerId,
answerDetail.question,
answerDetail.content,
answerDetail.community.name
),
ANSWER_PATCH_REQUEST
)
}
@SuppressLint("DefaultLocale", "SetTextI18n")
private fun updateView(answerDetail: AnswerDetailEntity) {
initMenu()
@ -1301,12 +1249,6 @@ open class AnswerDetailFragment : ToolbarFragment() {
}
}
interface CommentListener {
fun onCountChange(count: Int)
fun onCommentDraftChange(draft: String)
fun onCommentSuccess(commentId: String)
}
companion object {
private const val ANSWER_STATUS_UNKNOWN = 0
private const val ANSWERED_MY_ANSWER = 1

View File

@ -1,20 +0,0 @@
package com.gh.gamecenter.qa.answer.detail
import androidx.fragment.app.FragmentManager
class AnswerDetailFragmentStatePagerAdapter(
fm: FragmentManager,
private val mCreateNewAnswerDetailFragment: (answerId: String, position: Int) -> AnswerDetailFragment
) : androidx.fragment.app.FragmentStatePagerAdapter(fm) {
var answerIdList = arrayListOf<String>()
override fun getItem(position: Int): androidx.fragment.app.Fragment {
return mCreateNewAnswerDetailFragment.invoke(answerIdList[position], position)
}
override fun getCount(): Int {
return answerIdList.size
}
}

View File

@ -1,18 +0,0 @@
package com.gh.gamecenter.qa.answer.draft
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.constant.EntranceConsts
class AnswerDraftActivity : ToolBarActivity() {
companion object {
fun getIntent(context: Context, answerId: String? = null): Intent {
val bundle = Bundle()
bundle.putString(EntranceConsts.KEY_ANSWER_ID, answerId)
return getTargetIntent(context, AnswerDraftActivity::class.java, AnswerDraftFragment::class.java, bundle)
}
}
}

View File

@ -1,189 +0,0 @@
package com.gh.gamecenter.qa.answer.draft;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.gamecenter.common.callback.OnListClickListener;
import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.utils.PermissionHelper;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.common.baselist.ListAdapter;
import com.gh.gamecenter.common.baselist.ListViewModel;
import com.gh.gamecenter.common.baselist.LoadType;
import com.gh.gamecenter.databinding.AnswerDraftItemBinding;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.qa.answer.edit.AnswerEditActivity;
import com.gh.gamecenter.feature.entity.AnswerEntity;
import com.gh.gamecenter.qa.myqa.AnswerDraftViewHolder;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
/**
* Created by khy on 20/12/17.
*/
class AnswerDraftAdapter extends ListAdapter<AnswerEntity> {
private OnListClickListener mListClickListener;
private ListViewModel mListViewModel;
AnswerDraftAdapter(Context context,
OnListClickListener listClickListener,
ListViewModel longClickListener) {
super(context);
mListClickListener = listClickListener;
mListViewModel = longClickListener;
}
@Override
protected boolean areItemsTheSame(AnswerEntity oldItem, AnswerEntity newItem) {
return !TextUtils.isEmpty(oldItem.getId()) && oldItem.getId().equals(newItem.getId());
}
@Override
protected boolean areContentsTheSame(AnswerEntity oldItem, AnswerEntity newItem) {
return oldItem == newItem;
}
@Override
protected void setListData(List<AnswerEntity> updateData) {
if (updateData != null && mEntityList != null && updateData.size() == mEntityList.size()) {
mEntityList = new ArrayList<>(updateData);
notifyDataSetChanged();
return;
}
super.setListData(updateData);
}
@Override
public int getItemViewType(int position) {
if (position == getItemCount() - 1) return ItemViewType.ITEM_FOOTER;
return ItemViewType.ITEM_BODY;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case ItemViewType.ITEM_FOOTER:
view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false);
return new FooterViewHolder(view, mListClickListener);
case ItemViewType.ITEM_BODY:
view = mLayoutInflater.inflate(R.layout.answer_draft_item, parent, false);
return new AnswerDraftViewHolder(AnswerDraftItemBinding.bind(view));
default:
return null;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case ItemViewType.ITEM_BODY:
AnswerDraftViewHolder draftViewHolder = (AnswerDraftViewHolder) holder;
AnswerEntity answerEntity = mEntityList.get(position);
AnswerDraftItemBinding binding = draftViewHolder.getBinding();
SimpleDraweeView img = binding.answerDraftItemImg;
binding.answerDraftItemTitle.setText(answerEntity.getQuestions().getTitle());
binding.answerDraftItemContent.setText(answerEntity.getBrief());
binding.answerDraftItemCommunityName.setText(answerEntity.getCommunityName());
List<String> images = answerEntity.getImages();
if (images.size() > 0) {
for (int i = 0; i < images.size(); i++) {
if (!images.get(i).contains(".gif")) {
img.setVisibility(View.VISIBLE);
ImageUtils.display(img, images.get(i));
break;
}
if (i == images.size() - 1) {
img.setVisibility(View.GONE);
}
}
} else {
img.setVisibility(View.GONE);
}
binding.answerDraftItemDelete.setOnClickListener(v -> {
DialogHelper.showDialog(mContext, "警告", "确定要删除回答草稿吗?删除之后不可恢复", "确定", "取消", () -> deleteAnswerDraft(answerEntity), () -> {
}, false, "", "");
});
draftViewHolder.itemView.setOnClickListener(v -> {
PermissionHelper.checkStoragePermissionBeforeAction(
mContext, "", "", "", "",
() -> {
if (mContext instanceof AnswerDraftActivity) {
// 不需要回传任何数据
((AnswerDraftActivity) mContext).setResult(Activity.RESULT_OK);
((AnswerDraftActivity) mContext).finish();
} else if (answerEntity.getAnswerId().isEmpty()) {
mContext.startActivity(AnswerEditActivity.Companion.getIntent(
mContext,
answerEntity.getQuestions(),
answerEntity.getId(),
true,
answerEntity.getCommunityName()));
} else {
mContext.startActivity(AnswerEditActivity.Companion.getIntent(
mContext,
answerEntity.getAnswerId(),
answerEntity.getQuestions(),
"",// 会自动获取草稿所以该数据可以不填
answerEntity.getCommunityName(),
true,
true));
}
});
});
break;
case ItemViewType.ITEM_FOOTER:
FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
footerViewHolder.initItemPadding();
footerViewHolder.initFooterViewHolder(mListViewModel, mIsLoading, mIsNetworkError, mIsOver);
break;
}
}
@Override
public int getItemCount() {
return mEntityList == null || mEntityList.isEmpty() ? 0 : mEntityList.size() + FOOTER_ITEM_COUNT;
}
private void deleteAnswerDraft(AnswerEntity entity) {
RetrofitManager.getInstance()
.getApi()
.deleteAnswerDrafts(UserManager.getInstance().getUserId(), entity.getId())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response<ResponseBody>() {
@Override
public void onResponse(ResponseBody response) {
mListViewModel.load(LoadType.REFRESH);
}
@Override
public void onFailure(HttpException e) {
Utils.toast(mContext, R.string.loading_network_error);
}
});
}
}

View File

@ -1,97 +0,0 @@
package com.gh.gamecenter.qa.answer.draft;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.common.view.CustomDividerItemDecoration;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.baselist.ListAdapter;
import com.gh.gamecenter.common.baselist.ListFragment;
import com.gh.gamecenter.common.baselist.LoadType;
import com.gh.gamecenter.common.baselist.NormalListViewModel;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.qa.answer.edit.AnswerEditActivity;
import com.gh.gamecenter.feature.entity.AnswerEntity;
import com.gh.gamecenter.retrofit.RetrofitManager;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.List;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.Observable;
/**
* Created by khy on 20/12/17.
*/
public class AnswerDraftFragment extends ListFragment<AnswerEntity, NormalListViewModel> {
private AnswerDraftAdapter mAdapter;
@Nullable
private String mAnswerId;
public static AnswerDraftFragment getInstance(String entrance) {
AnswerDraftFragment fragment = new AnswerDraftFragment();
Bundle args = new Bundle();
args.putString(EntranceConsts.KEY_ENTRANCE, entrance);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mAnswerId = arguments.getString(EntranceConsts.KEY_ANSWER_ID);
}
super.onCreate(savedInstanceState);
if (getActivity() instanceof AnswerDraftActivity) {
setNavigationTitle("回答草稿");
}
}
@Override
protected ListAdapter provideListAdapter() {
return mAdapter == null ? mAdapter = new AnswerDraftAdapter(getContext(),
this,
mListViewModel) : mAdapter;
}
@Override
protected RecyclerView.ItemDecoration getItemDecoration() {
Drawable insetDivider = ContextCompat.getDrawable(requireContext(), R.drawable.divider_item_line_space_16);
CustomDividerItemDecoration itemDecoration = new CustomDividerItemDecoration(requireContext(), false, false, true, false);
if (insetDivider != null) {
itemDecoration.setDrawable(insetDivider);
}
return itemDecoration;
}
@Override
public Observable<List<AnswerEntity>> provideDataObservable(int page) {
return RetrofitManager.getInstance().getApi().getAnswerDrafts(
UserManager.getInstance().getUserId(),
UrlFilterUtils.getFilterQuery("answer_id", mAnswerId),
page);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(EBReuse reuse) {
if (AnswerEditActivity.ANSWER_DRAFT_CHANGE_TAG.equals(reuse.getType())) {
mListRv.scrollToPosition(0);
mBaseHandler.postDelayed(() -> mListViewModel.load(LoadType.REFRESH), 100);
}
}
}

View File

@ -1,573 +0,0 @@
package com.gh.gamecenter.qa.answer.edit
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.view.Gravity
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.base.BaseRichEditorActivity
import com.gh.common.util.*
import com.gh.gamecenter.ImageViewerActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.NotificationUgc
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.FragmentAnswerEditBinding
import com.gh.gamecenter.feature.entity.Questions
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.answer.detail.AnswerDetailActivity
import com.gh.gamecenter.qa.answer.draft.AnswerDraftActivity
import com.gh.gamecenter.video.VideoVerifyItemViewHolder
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel
import com.halo.assistant.HaloApp
import org.json.JSONObject
/**
* Created by khy on 10/04/18.
*/
@Deprecated("V5.0废弃")
class AnswerEditActivity : BaseRichEditorActivity<AnswerEditViewModel>(), KeyboardHeightObserver {
private lateinit var mMenuDraft: MenuItem
private lateinit var mMenuPost: MenuItem
private lateinit var mBinding: FragmentAnswerEditBinding
private var mProcessingDialog: WaitingDialogFragment? = null
private var mUploadImageCancelDialog: DialogHelper.DialogAlertDefaultBindingWrapper? = null
private var mCommunityName: String? = null
private var mOpenAnswerInNewPage: Boolean = false
private var mImageViewList: ArrayList<SimpleDraweeView>? = null
override fun mtaEventName(): String {
return "回答详情" // issues 定的就是回答详情
}
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
if (msg.what == AUTO_SAVE_DRAFT) {
saveDraft(false)
mBaseHandler.sendEmptyMessageDelayed(AUTO_SAVE_DRAFT, SAVE_DRAFTS_INTERVAL_TIME.toLong())
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == ANSWER_DRAFT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
mViewModel.getUserAnswerDrafts()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setToolbarMenu(R.menu.menu_answer_post)
mMenuDraft = mToolbar.menu.findItem(R.id.menu_draft)
mMenuPost = mToolbar.menu.findItem(R.id.menu_answer_post)
mCommunityName = intent?.getStringExtra(EntranceConsts.KEY_COMMUNITY_NAME)
mOpenAnswerInNewPage = intent?.getBooleanExtra(EntranceConsts.KEY_ANSWER_OPEN_IN_NEW_PAGE, false)!!
mBinding = FragmentAnswerEditBinding.bind(mContentView)
onClickView()
addObserver()
initQuestionContent()
if (TextUtils.isEmpty(mViewModel.answerId)) {
mBaseHandler.sendEmptyMessageDelayed(AUTO_SAVE_DRAFT, SAVE_DRAFTS_INTERVAL_TIME.toLong()) // 启动自动保存草稿
}
mRichEditor.setOnTextChangeListener { t ->
mBinding.appBar.setExpanded(false, true)
mBinding.answerPlaceholder.visibility =
if (t.contains("<img src") || !TextUtils.isEmpty(mRichEditor.text)) {
View.GONE
} else View.VISIBLE
checkPostButtonEnable()
}
mRichEditor.setOnInitialLoadListener { isReady ->
if (isReady) {
requestFocusAndMoveCursorToEnd()
}
}
if (!TextUtils.isEmpty(mViewModel.answerId)) {
setNavigationTitle(getString(R.string.answer_patch_title))
mViewModel.cacheAnswerContent = mViewModel.answerContent
mMenuDraft.isVisible = true
if (intent.getBooleanExtra(EntranceConsts.KEY_SHOW_EDIT_DRAFT, false)) {
mViewModel.getUserAnswerDrafts()
} else {
mRichEditor.setHtml(mViewModel.answerContent, false)
}
} else {
setNavigationTitle(getString(R.string.answer_edit_title))
mViewModel.getUserAnswerDrafts()
mMenuDraft.isVisible = false
}
checkPostButtonEnable()
mImageViewList = arrayListOf(
findViewById(R.id.question_images_1),
findViewById(R.id.question_images_2),
findViewById(R.id.question_images_3)
)
}
override fun provideViewModel(): AnswerEditViewModel {
val factory = AnswerEditViewModel.Factory(
HaloApp.getInstance().application,
intent?.getStringExtra(EntranceConsts.KEY_ANSWER_ID),
intent?.getStringExtra(EntranceConsts.KEY_ANSWER_CONTENT),
intent?.getStringExtra(EntranceConsts.KEY_DRAFT_ID),
intent?.getParcelableExtra(Questions::class.java.simpleName) ?: Questions()
)
mViewModel = ViewModelProviders.of(this, factory).get(AnswerEditViewModel::class.java)
return mViewModel
}
override fun getLayoutId(): Int {
return R.layout.fragment_answer_edit
}
override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
super.onKeyboardHeightChanged(height, orientation)
if (height > 0) mBinding.appBar.setExpanded(false, true)
}
override fun onMenuItemClick(item: MenuItem?): Boolean {
if (item?.itemId == R.id.menu_answer_post && !ClickUtils.isFastDoubleClick(R.id.menu_answer_post, 5000)) {
readyPost()
} else if (item?.itemId == R.id.menu_draft) {
startActivityForResult(AnswerDraftActivity.getIntent(this, mViewModel.answerId), ANSWER_DRAFT_REQUEST_CODE)
}
return super.onMenuItemClick(item)
}
private fun addObserver() {
mViewModel.postLiveData.observeNonNull(this) {
if (it.status == Status.SUCCESS) {
MtaHelper.onEvent("发表答案", "提交成功", mCommunityName)
if (mViewModel.checkIsAllUploadedAndToast()) {
toast("发布成功")
}
var answerId: String? = null
tryWithDefaultCatch {
answerId = JSONObject(it.data).getString("_id")
}
if (answerId == null) {
answerId = mViewModel.answerId
}
val data = Intent()
data.putExtra(EntranceConsts.KEY_ANSWER_CONTENT, getReplaceRealContent())
data.putExtra(EntranceConsts.KEY_ANSWER_ID, answerId ?: mViewModel.answerId)
setResult(Activity.RESULT_OK, data)
if (mOpenAnswerInNewPage) {
val intent = AnswerDetailActivity
.getIntent(this, answerId, mEntrance, "编辑答案")
startActivity(intent)
}
finish()
AppExecutor.uiExecutor.executeWithDelay(Runnable {
NotificationHelper.showNotificationHintDialog(NotificationUgc.ANSWER)
}, 1000)
} else if (it.status == Status.ERROR) {
val errorString = it.exception?.response()?.errorBody()?.string()
ErrorHelper.handleErrorWithCustomizedHandler(this, errorString, customizedHandler = { code ->
when (code) {
403037 -> consume {
if (TextUtils.isEmpty(mViewModel.draftId)) {
DialogHelper.showDialog(this, "发布失败", "问题已被删除,无法发布回答", "好吧", "", { finish() })
} else {
DialogHelper.showDialog(this,
"发布失败",
"问题已被删除,需要删除草稿吗?",
"删除草稿",
"暂不",
{
mViewModel.deleteAnswerDraft()
finish()
})
}
}
else -> false
}
})
}
}
mViewModel.processDialog.observeNonNull(this) {
if (it.isShow) {
if (mProcessingDialog?.dialog?.isShowing == true) {
mProcessingDialog?.uploadWaitingHint(it.msg)
} else {
mProcessingDialog = WaitingDialogFragment.newInstance(it.msg, false)
mProcessingDialog?.show(supportFragmentManager, null) {
if (mViewModel.uploadImageSubscription != null && !mViewModel.uploadImageSubscription!!.isDisposed) {
mUploadImageCancelDialog = DialogHelper.showDialog(
this, "提示", "图片正在上传中,确定取消吗?",
"确定", "取消", {
mViewModel.uploadImageSubscription?.dispose()
mUploadImageCancelDialog?.dismiss()
mProcessingDialog?.dismiss()
}, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
)
}
}
}
} else {
mUploadImageCancelDialog?.dismiss()
mProcessingDialog?.dismiss()
}
}
mViewModel.deleteDraftLiveDate.observe(this, Observer {
if (it == true) {
setResult(Activity.RESULT_OK)
finish()
}
})
mViewModel.draftsLiveData.observe(this, Observer {
mRichEditor.setHtml(it, false)
requestFocusAndMoveCursorToEnd()
checkPostButtonEnable()
})
mViewModel.saveDraftsLiveData.observeNonNull(this) {
if (it) {
val data = Intent()
data.putExtra(EntranceConsts.KEY_ANSWER_CONTENT, getReplaceRealContent())
setResult(SAVE_DRAFTS, data)
finish()
} else {
showDraftFailureDialog()
}
}
}
private fun requestFocusAndMoveCursorToEnd() {
try {
mRichEditor.scrollTo(0, 10000000)
mRichEditor.postDelayed({
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(mRichEditor, InputMethodManager.SHOW_IMPLICIT)
mRichEditor.focusEditor()
}, 400)
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun initQuestionContent() {
val question = mViewModel.question
question.title = HtmlUtils.filterHtmlLabel(question.title)
val video = if (!question.videos.isNullOrEmpty()) question.videos[0] else null
val videoSize = if (video != null) 1 else 0
mBinding.answerPlaceholder.text =
if (!question.description.isNullOrEmpty() || question.images.size > 0 || question.videos.isNotEmpty()) {
"请撰写回答(下拉查看问题详情)..."
} else "请撰写回答..."
mBinding.appBar.setExpanded(false)
mBinding.questionTitle.text = question.title
mBinding.questionDes.initWidth(resources.displayMetrics.widthPixels - 40F.dip2px())
mBinding.questionDes.maxLines = 3
mBinding.questionDes.setOriginalText(question.description)
mBinding.questionDes.goneIf(question.description.isNullOrEmpty())
mBinding.videoPlay.visibleIf(video != null)
mBinding.videoStatus.visibleIf(video != null && video.status != "pass")
mBinding.videoDuration.visibleIf(video?.status == "pass")
if (video?.status == "pass") {
mBinding.videoDuration.background = DrawableView.getOvalDrawable(R.color.black_alpha_50, 999f)
mBinding.videoDuration.text = video.duration
} else {
val status = if (!question.me.isContentOwner && !question.me.isModerator && video?.status == "fail") {
"pending"
} else video?.status ?: ""
VideoVerifyItemViewHolder.setVideoStatus(mBinding.videoStatus, status)
}
if (video != null) {
if (video.status == "pass") {
mBinding.questionImages1.display(video.poster)
} else {
mBinding.questionImages1.setImageResource(R.drawable.community_video_default_poster)
}
}
question.images.let { images ->
for (i in images.indices) {
val index = i + videoSize // view index
val position = index - videoSize // data index
if (images.size > position) {
when (index) {
0 -> ImageUtils.display(mBinding.questionImages1, images[position])
1 -> ImageUtils.display(mBinding.questionImages2, images[position])
2 -> {
ImageUtils.display(mBinding.questionImages3, images[position])
if (images.size + videoSize > 3) {
mBinding.questionImages3Mask.visibility = View.VISIBLE
mBinding.questionImages3Desc.visibility = View.VISIBLE
mBinding.questionImages3Desc.text = "+${images.size + videoSize - 3}"
}
}
}
}
}
mBinding.questionImagesContainer.visibility = if (images.size + videoSize > 0) {
View.VISIBLE
} else View.GONE
}
}
private fun readyPost() {
ifLogin("回答编辑-提交") {
mRichEditor.hideLinkStyle()
mRichEditor.postDelayed({
val answerContent = getReplaceRealContent()
mRichEditor.showLinkStyle()
if (mRichEditor.hasPlaceholderImage()) {
ToastUtils.showToast("图片上传ing")
return@postDelayed
}
if (checkData(answerContent)) {
mViewModel.postAnswer(answerContent)
}
}, 100)
}
}
private fun checkData(answerContent: String, isShowToast: Boolean = true): Boolean {
val answerLength = HtmlUtils.stripHtml(answerContent).length
if (answerLength < MIN_ANSWER_TEXT_LENGTH) {
if (isShowToast) ToastUtils.showToast(
getString(R.string.answer_beneath_length_limit),
if (mIsKeyBoardShow) Gravity.CENTER else -1
)
return false
} else if (answerLength > MAX_ANSWER_TEXT_LENGTH) {
if (isShowToast) ToastUtils.showToast("回答最多输入10000个字", if (mIsKeyBoardShow) Gravity.CENTER else -1)
return false
}
return true
}
private fun getReplaceRealContent(): String {
var answerContent = mRichEditor.html
for (s in mViewModel.mapImages.keys) {
val netUrl = mViewModel.mapImages[s]
if (netUrl != null) {
answerContent = answerContent.replace(FILE_HOST + s, netUrl)
}
}
return answerContent
}
private fun checkPostButtonEnable() {
val answerContent = getReplaceRealContent()
val isEnabled = checkData(answerContent, false)
mMenuPost.actionView?.alpha = if (isEnabled) 1f else 0.6f
}
override fun handleBackPressed(): Boolean {
return if (TextUtils.isEmpty(UserManager.getInstance().token)) {
false
} else if (!TextUtils.isEmpty(mViewModel.answerId)
&& TextUtils.isEmpty(mRichEditor.text)
&& !mRichEditor.html.contains("<img src")
)
false
else if (!TextUtils.isEmpty(mViewModel.answerId)) {
consume { showPatchBackDialog() }
} else if (TextUtils.isEmpty(mViewModel.answerId)
&& !TextUtils.isEmpty(mViewModel.cacheAnswerContent)
&& !mRichEditor.html.contains("<img src")
&& TextUtils.isEmpty(mRichEditor.text)
) {
consume {
DialogHelper.showDialog(this, "提示", "当前内容为空,退出即会删除该草稿,确定退出吗?", "确定", "取消", {
mViewModel.deleteAnswerDraft()
})
}
} else if (!TextUtils.isEmpty(mViewModel.cacheAnswerContent)
&& mViewModel.cacheAnswerContent == mRichEditor.html
) {
false
} else {
consume { saveDraft(true) }
}
}
override fun onDestroy() {
mProcessingDialog?.dismissAllowingStateLoss()
mProcessingDialog = null
super.onDestroy()
}
private fun showDraftFailureDialog() {
DialogHelper.showDialog(this, "提示", "确定退出?已撰写的内容将会丢失?", "继续撰写", "退出", cancelClickCallback = { finish() })
}
private fun showPatchBackDialog() {
DialogHelper.showDialog(this, "提示", "是否保存修改内容用于下次编辑?", "保存并退出", "不保存", { saveDraft(true) }, { finish() })
}
/**
* [forcedExit] -> 强行退出当前页面,不考虑接口请求成功与否
*/
private fun saveDraft(forcedExit: Boolean) {
val editContent = getReplaceRealContent()
if (mRichEditor.hasPlaceholderImage()) return
if (TextUtils.isEmpty(UserManager.getInstance().token)) {
return
} else if (forcedExit && TextUtils.isEmpty(editContent)) {
finish()
return
} else if (!forcedExit && TextUtils.isEmpty(editContent)) {
return
}
mViewModel.saveAnswerDrafts(editContent, forcedExit)
}
private fun onClickView() {
val videoSize = if (!mViewModel.question.videos.isNullOrEmpty()) 1 else 0
mBinding.questionImages1.setOnClickListener {
val question = mViewModel.question
if (!question.videos.isNullOrEmpty()) {
val videoEntity = question.videos[0]
if (videoEntity.status == "pass") {
DirectUtils.directToVideoDetail(
this,
videoEntity.id,
VideoDetailContainerViewModel.Location.SINGLE_VIDEO.value,
path = "回答详情"
)
} else if (videoEntity.status == "pending" ||
(!question.me.isContentOwner
&& !question.me.isModerator
&& videoEntity.status == "fail")
) {
toast("视频正在审核中")
} else if (videoEntity.status == "fail") {
toast("视频审核未通过")
}
} else {
showQuestionImageDetail(0)
}
}
mBinding.questionImages2.setOnClickListener {
showQuestionImageDetail(1 - videoSize)
}
mBinding.questionImages3.setOnClickListener {
showQuestionImageDetail(2 - videoSize)
}
}
private fun showQuestionImageDetail(position: Int) {
val images = ArrayList(mViewModel.question.images)
if (position <= images.size) {
val intent = ImageViewerActivity.getIntent(this, images, position, mImageViewList, "$mEntrance+(回答编辑)")
startActivity(intent)
}
}
override fun getVideoGuideKey(): String = ""
companion object {
const val SAVE_DRAFTS = 110
const val AUTO_SAVE_DRAFT = 1
const val SAVE_DRAFTS_INTERVAL_TIME = 15000
const val SAVE_DRAFTS_TOAST_COUNT = 3
const val MIN_ANSWER_TEXT_LENGTH = 6
const val MAX_ANSWER_TEXT_LENGTH = 10000
const val ANSWER_DRAFT_REQUEST_CODE = 112
const val ANSWER_DRAFT_CHANGE_TAG = "ANSWER_DRAFT_CHANGE_TAG"
/**
* 撰写回答
*/
fun getIntent(
context: Context,
question: Questions?,
showInNewPage: Boolean?,
communityName: String?,
showHintBackground: Boolean = false
): Intent {
val intent = Intent(context, AnswerEditActivity::class.java)
intent.putExtra(EntranceConsts.KEY_ANSWER_OPEN_IN_NEW_PAGE, showInNewPage)
intent.putExtra(EntranceConsts.KEY_COMMUNITY_NAME, communityName)
intent.putExtra(EntranceConsts.KEY_HINT, showHintBackground)
intent.putExtra(Questions::class.java.simpleName, question)
return intent
}
/**
* 撰写回答(存在回答草稿)
*/
fun getIntent(
context: Context,
question: Questions?,
draftId: String?,
showInNewPage: Boolean?,
communityName: String?
): Intent {
val intent = Intent(context, AnswerEditActivity::class.java)
intent.putExtra(EntranceConsts.KEY_ANSWER_OPEN_IN_NEW_PAGE, showInNewPage)
intent.putExtra(EntranceConsts.KEY_DRAFT_ID, draftId)
intent.putExtra(EntranceConsts.KEY_COMMUNITY_NAME, communityName)
intent.putExtra(Questions::class.java.simpleName, question)
return intent
}
/**
* 撰写回答
*/
fun getIntent(context: Context, question: Questions?, communityName: String?): Intent {
val intent = Intent(context, AnswerEditActivity::class.java)
intent.putExtra(EntranceConsts.KEY_COMMUNITY_NAME, communityName)
intent.putExtra(Questions::class.java.simpleName, question)
return intent
}
/**
* 修改回答
*/
fun getIntent(
context: Context,
answerId: String?,
question: Questions?,
content: String?,
communityName: String?,
showEditDraft: Boolean = false,
showInNewPage: Boolean = false
): Intent {
val intent = Intent(context, AnswerEditActivity::class.java)
intent.putExtra(EntranceConsts.KEY_ANSWER_ID, answerId)
intent.putExtra(EntranceConsts.KEY_ANSWER_CONTENT, content)
intent.putExtra(EntranceConsts.KEY_COMMUNITY_NAME, communityName)
intent.putExtra(EntranceConsts.KEY_SHOW_EDIT_DRAFT, showEditDraft)
intent.putExtra(Questions::class.java.simpleName, question)
intent.putExtra(EntranceConsts.KEY_ANSWER_OPEN_IN_NEW_PAGE, showInNewPage)
return intent
}
}
}

View File

@ -1,212 +0,0 @@
package com.gh.gamecenter.qa.answer.edit
import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.*
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.syncpage.SyncDataEntity
import com.gh.gamecenter.common.syncpage.SyncFieldConstants
import com.gh.gamecenter.common.syncpage.SyncPageRepository
import com.gh.gamecenter.R
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.mvvm.Resource
import com.gh.base.BaseRichEditorViewModel
import com.gh.base.RichType
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.qa.entity.AnswerDraftEntity
import com.gh.gamecenter.feature.entity.Questions
import com.gh.gamecenter.common.retrofit.Response
import com.lightgame.utils.Utils
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import okhttp3.internal.http.RealResponseBody
import org.greenrobot.eventbus.EventBus
import org.json.JSONException
import org.json.JSONObject
import retrofit2.HttpException
@Deprecated("V5.0废弃")
class AnswerEditViewModel(
application: Application,
var answerId: String?, // 以mAnswerId为标识如果mAnswerId不为空则是-修改答案(不需要保存草稿) 为空则是-编写答案
var answerContent: String?,
var draftId: String?,
var question: Questions
) : BaseRichEditorViewModel(application) {
private var mPostDraftsCount: Int = 0
var cacheAnswerContent: String? = null
val postLiveData = MediatorLiveData<Resource<String>>()
val deleteDraftLiveDate = MediatorLiveData<Boolean>()
val draftsLiveData = MediatorLiveData<String>()
val saveDraftsLiveData = MediatorLiveData<Boolean>() // 自动保存不会回调
fun postAnswer(editContent: String) {
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("提交中...", true))
val content = JSONObject()
try {
content.put("content", editContent)
} catch (e: Throwable) {
e.printStackTrace()
}
val body = RequestBody.create(MediaType.parse("application/json"), content.toString())
val observable = if (!TextUtils.isEmpty(answerId)) {
if (editContent == answerContent) { // 内容不变不需要请求服务器,直接返回成功即可
val responseBody = RealResponseBody("", 0, null)
Single.just<ResponseBody>(responseBody).toObservable()
} else {
mApi.patchQuestionAnswer(body, answerId)
}
} else {
mApi.postQuestionAnswer(body, question.id)
}
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Response<ResponseBody>() {
override fun onResponse(response: ResponseBody?) {
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("提交中...", false))
val data = response?.string()
postLiveData.postValue(Resource.success(data))
EventBus.getDefault().post(EBReuse(AnswerEditActivity.ANSWER_DRAFT_CHANGE_TAG))
if (TextUtils.isEmpty(answerId)) {
syncAnswerCount()
}
}
override fun onFailure(e: HttpException?) {
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("提交中...", false))
postLiveData.postValue(Resource.error(e))
}
})
}
private fun syncAnswerCount() {
SyncPageRepository.postSyncData(
SyncDataEntity(
question.id,
SyncFieldConstants.ANSWER_COUNT,
++question.answerCount,
checkInherited = true,
checkFieldEntity = true
)
)
}
fun deleteAnswerDraft() {
if (draftId.isNullOrEmpty()) {
deleteDraftLiveDate.postValue(true)
return
}
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("删除中...", true))
mApi
.deleteAnswerDrafts(UserManager.getInstance().userId, draftId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Response<ResponseBody>() {
override fun onResponse(response: ResponseBody?) {
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("删除中...", false))
deleteDraftLiveDate.postValue(true)
EventBus.getDefault().post(EBReuse(AnswerEditActivity.ANSWER_DRAFT_CHANGE_TAG))
}
override fun onFailure(e: HttpException?) {
processDialog.postValue(WaitingDialogFragment.WaitingDialogData("删除中...", false))
deleteDraftLiveDate.postValue(false)
Utils.toast(getApplication(), R.string.loading_network_error)
}
})
}
fun getUserAnswerDrafts() {
mApi
.getUserAnswerDrafts(
question.id,
UrlFilterUtils.getFilterQuery("answer_id", answerId),
Utils.getTime(getApplication())
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Response<AnswerDraftEntity>() {
override fun onResponse(draft: AnswerDraftEntity?) {
if (draft?.content != null) {
draftsLiveData.postValue(draft.content)
cacheAnswerContent = draft.content
}
draftId = draft?.id
if (!TextUtils.isEmpty(draft?.answerId)) { // answerId不为空 表示已经提交过答案了
answerId = draft?.answerId
}
}
})
}
fun saveAnswerDrafts(editContent: String, forcedExit: Boolean) {
val content = JSONObject()
try {
content.put("content", editContent)
content.put("question_id", question.id)
if (!answerId.isNullOrEmpty()) {
content.put("answer_id", answerId)
}
} catch (e: JSONException) {
e.printStackTrace()
}
val body = RequestBody.create(MediaType.parse("application/json"), content.toString())
mApi
.postAnswerDrafts(body, UserManager.getInstance().userId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Response<ResponseBody>() {
override fun onResponse(response: ResponseBody?) {
super.onResponse(response)
if (forcedExit) {
saveDraftsLiveData.postValue(true)
if (checkIsAllUploadedAndToast()) {
Utils.toast(getApplication(), "回答已保存到草稿箱")
}
EventBus.getDefault().post(EBReuse(AnswerEditActivity.ANSWER_DRAFT_CHANGE_TAG))
} else {
if (mPostDraftsCount >= AnswerEditActivity.SAVE_DRAFTS_TOAST_COUNT) {
mPostDraftsCount = 0
Utils.toast(getApplication(), "回答已保存到草稿箱")
} else {
mPostDraftsCount++
}
cacheAnswerContent = editContent
}
}
override fun onFailure(e: HttpException?) {
super.onFailure(e)
if (forcedExit) saveDraftsLiveData.postValue(false)
}
})
}
override fun getRichType(): RichType = RichType.ANSWER
class Factory(
private val mApplication: Application,
private val answerId: String?,
private val answerContent: String?,
private val draftId: String?,
private val question: Questions
) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return AnswerEditViewModel(mApplication, answerId, answerContent, draftId, question) as T
}
}
}

View File

@ -1,23 +0,0 @@
package com.gh.gamecenter.qa.article
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.EntranceConsts
class MyArticleActivity : ToolBarActivity() {
companion object {
const val PUBLISH_ARTICLE_REQUEST_CODE = 102
@JvmStatic
fun getIntent(context: Context, userId: String, entrance: String, path: String): Intent {
val bundle = Bundle()
bundle.putString(EntranceConsts.KEY_USER_ID, userId)
bundle.putString(EntranceConsts.KEY_ENTRANCE, BaseActivity.mergeEntranceAndPath(entrance, path))
return getTargetIntent(context, MyArticleActivity::class.java, MyArticleFragment::class.java, bundle)
}
}
}

View File

@ -1,100 +0,0 @@
package com.gh.gamecenter.qa.article
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.syncpage.ISyncAdapterHandler
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.databinding.CommunityAnswerItemBinding
import com.gh.gamecenter.forum.home.ForumArticleAskItemViewHolder
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.feature.entity.ArticleEntity
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity
class MyArticleAdapter(
context: Context,
private val mEntrance: String,
private val mPath: String
) : ListAdapter<ArticleEntity>(context), ISyncAdapterHandler {
override fun getItemViewType(position: Int): Int {
if (position == itemCount - 1) {
return ItemViewType.ITEM_FOOTER
}
return ItemViewType.ITEM_BODY
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view: View
return when (viewType) {
ItemViewType.ITEM_FOOTER -> {
view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false)
FooterViewHolder(view)
}
else -> {
view = mLayoutInflater.inflate(R.layout.community_answer_item, parent, false)
ForumArticleAskItemViewHolder(CommunityAnswerItemBinding.bind(view))
}
}
}
override fun getItemCount(): Int {
return if (mEntityList.size == 0) 0 else mEntityList.size + 1
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ForumArticleAskItemViewHolder) {
val entity = mEntityList[position]
holder.bindForumArticleItem(entity, mEntrance, mPath, position)
holder.binding.run {
userIcon.visibility = View.GONE
userName.visibility = View.GONE
userBadgeIcon.visibility = View.GONE
userBadgeName.visibility = View.GONE
concernBtn.visibility = View.GONE
timeContainer.visibility = View.GONE
title.layoutParams = (title.layoutParams as ViewGroup.MarginLayoutParams).apply {
topMargin = 20F.dip2px()
}
}
holder.itemView.setOnClickListener {
if (entity.type == "question") {
mContext.startActivity(NewQuestionDetailActivity.getIntent(mContext, entity.id, mEntrance, mPath))
} else {
mContext.startActivity(
ArticleDetailActivity.getIntent(
mContext,
entity.community,
entity.id,
mEntrance,
mPath
)
)
}
}
} else if (holder is FooterViewHolder) {
holder.initFooterViewHolder(mIsLoading, mIsNetworkError, mIsOver)
holder.initItemPadding()
}
}
override fun areContentsTheSame(oldItem: ArticleEntity?, newItem: ArticleEntity?): Boolean {
return oldItem?.id == newItem?.id
}
override fun areItemsTheSame(oldItem: ArticleEntity?, newItem: ArticleEntity?): Boolean {
return oldItem == newItem
}
override fun getSyncData(position: Int): Pair<String, Any>? {
if (position >= mEntityList.size) return null
val entity = mEntityList[position]
return Pair(entity.id, entity)
}
}

View File

@ -1,139 +0,0 @@
package com.gh.gamecenter.qa.article
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.baselist.NormalListViewModel
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.checkStoragePermissionBeforeAction
import com.gh.gamecenter.common.utils.ifLogin
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.view.CustomDividerItemDecoration
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.article.edit.ArticleEditActivity
import com.gh.gamecenter.feature.entity.ArticleEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable
class MyArticleFragment : ListFragment<ArticleEntity, NormalListViewModel<ArticleEntity>>() {
private var mTargetUserId = ""
private var mAdapter: MyArticleAdapter? = null
override fun provideListAdapter(): MyArticleAdapter {
if (mAdapter == null) {
val path = if (mTargetUserId == UserManager.getInstance().userId) {
"我的帖子"
} else {
"Ta的帖子"
}
mAdapter = MyArticleAdapter(requireContext(), mEntrance, path)
}
return mAdapter!!
}
override fun provideDataObservable(page: Int): Observable<MutableList<ArticleEntity>>? {
return RetrofitManager.getInstance().api.getMyArticleAndQuestion(mTargetUserId, page)
.flatMap { list ->
Observable.create { emitter ->
val articleList = list.map { it.transformArticleEntity() }.toMutableList()
emitter.onNext(articleList)
emitter.onComplete()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == MyArticleActivity.PUBLISH_ARTICLE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
mListViewModel.load(LoadType.REFRESH)
}
}
override fun provideListViewModel(): NormalListViewModel<ArticleEntity> {
val factory = NormalListViewModel.Factory(HaloApp.getInstance().application, this)
return ViewModelProviders.of(this, factory)
.get(NormalListViewModel::class.java) as NormalListViewModel<ArticleEntity>
}
override fun onCreate(savedInstanceState: Bundle?) {
mTargetUserId = arguments?.getString(EntranceConsts.KEY_USER_ID) ?: ""
super.onCreate(savedInstanceState)
if (activity is MyArticleActivity) {
if (mTargetUserId == UserManager.getInstance().userId) {
setNavigationTitle("我的帖子")
initMenu(R.menu.menu_article_publich)
} else {
setNavigationTitle("Ta的帖子")
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mCachedView.setBackgroundColor(R.color.ui_surface.toColor(requireContext()))
}
override fun onMenuItemClick(item: MenuItem?) {
if (item?.itemId == R.id.menu_article_publish) {
ifLogin("个人主页-Ta的文章-发文章") {
checkStoragePermissionBeforeAction {
startActivityForResult(
ArticleEditActivity.getIntent(requireContext()),
MyArticleActivity.PUBLISH_ARTICLE_REQUEST_CODE
)
}
}
}
}
override fun addSyncPageObserver(): Boolean {
return true
}
override fun provideSyncAdapter(): MyArticleAdapter? {
return mAdapter
}
override fun getItemDecoration(): RecyclerView.ItemDecoration {
val itemDecoration = CustomDividerItemDecoration(
requireContext(),
onlyDecorateTheFirstItem = false,
notDecorateTheFirstItem = false,
notDecorateTheLastItem = true,
notDecorateTheFirstTwoItems = false
)
itemDecoration.setDrawable(R.drawable.divider_item_line_space_16.toDrawable(requireContext())!!)
return itemDecoration
}
override fun onDarkModeChanged() {
super.onDarkModeChanged()
if (mListRv != null && mListRv.itemDecorationCount > 0) {
mListRv.removeItemDecorationAt(0)
mListRv.addItemDecoration(itemDecoration)
}
}
companion object {
@JvmStatic
fun getInstance(entrance: String?, userId: String): MyArticleFragment {
val fragment = MyArticleFragment()
val args = Bundle()
args.putString(EntranceConsts.KEY_ENTRANCE, entrance)
args.putString(EntranceConsts.KEY_USER_ID, userId)
fragment.arguments = args
return fragment
}
}
}

View File

@ -56,13 +56,13 @@ object ArticleDetailWebCacheManager {
}
val cacheUrlList = mutableListOf(
"https://static-web.ghzs.com/website-static/lib/polyfill.min.js",
"https://and-static.ghzs.com/web/dplayer/DPlayer.min.js"
"https://and-static.ghzs66.com/web/website-static/lib/polyfill.min.js",
"https://and-static.ghzs66.com/web/dplayer/DPlayer.min.js"
)
if (!EnvHelper.isDevEnv) {
cacheUrlList.add("https://resource.ghzs.com/js/halo.js")
cacheUrlList.add("https://resource.ghzs.com/css/halo.css")
cacheUrlList.add("https://and-static.ghzs66.com/web/js/halo.js")
cacheUrlList.add("https://and-static.ghzs66.com/web/css/halo.css")
}
val okHttpClient = OkHttpClient.Builder()
@ -73,7 +73,7 @@ object ArticleDetailWebCacheManager {
val retrofit = Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://resource.ghzs.com")
.baseUrl("https://and-static.ghzs66.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()

View File

@ -32,7 +32,6 @@ import com.gh.gamecenter.feature.entity.ArticleDraftEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.BbsType
import com.gh.gamecenter.qa.answer.edit.AnswerEditActivity
import com.gh.gamecenter.qa.article.draft.ArticleDraftActivity
import com.gh.gamecenter.qa.dialog.ChooseActivityDialogFragment
import com.gh.gamecenter.qa.dialog.ChooseForumActivity
@ -222,7 +221,7 @@ class ArticleEditActivity : BaseRichEditorActivity<ArticleEditViewModel>(), Keyb
SaveDraftType.AUTO -> {
if (pair.second) {
if (mPostDraftsCount >= AnswerEditActivity.SAVE_DRAFTS_TOAST_COUNT) {
if (mPostDraftsCount >= SAVE_DRAFTS_TOAST_COUNT) {
mPostDraftsCount = 0
Utils.toast(this, "帖子已保存到草稿箱")
} else {
@ -769,6 +768,7 @@ class ArticleEditActivity : BaseRichEditorActivity<ArticleEditViewModel>(), Keyb
companion object {
const val SAVE_DRAFTS_INTERVAL_TIME = 15000
const val ARTICLE_DRAFT_REQUEST_CODE = 105
const val SAVE_DRAFTS_TOAST_COUNT = 3
const val ARTICLE_DRAFT_CHANGE_TAG = "ANSWER_DRAFT_CHANGE_TAG"
const val ARTICLE_POSTED_TAG = "ARTICLE_POSTED_TAG"

View File

@ -16,7 +16,6 @@ import com.gh.gamecenter.core.utils.doOnEnd
import com.gh.gamecenter.databinding.ActivityCommentBinding
import com.gh.gamecenter.feature.entity.CommentEntity
import com.gh.gamecenter.gamecollection.detail.conversation.GameCollectionCommentConversationFragment
import com.gh.gamecenter.qa.answer.detail.AnswerDetailFragment
import com.gh.gamecenter.qa.comment.conversation.CommentConversationFragment
import com.lightgame.utils.Util_System_Keyboard
@ -54,7 +53,7 @@ class CommentActivity : BaseActivity() {
val useReplyApi: Boolean = intent.getBooleanExtra(USE_REPLY_API, false)
mShowInputOnly = intent.getBooleanExtra(SHOW_INPUT_ONLY, false)
val commentCallback = object : AnswerDetailFragment.CommentListener {
val commentCallback = object : CommentListener {
override fun onCountChange(count: Int) {
resultIntent.putExtra(COMMENT_COUNT, count)
setResult(Activity.RESULT_OK, resultIntent)
@ -466,4 +465,10 @@ class CommentActivity : BaseActivity() {
return intent
}
}
interface CommentListener {
fun onCountChange(count: Int)
fun onCommentDraftChange(draft: String)
fun onCommentSuccess(commentId: String)
}
}

View File

@ -38,7 +38,6 @@ import com.gh.gamecenter.databinding.ItemCommentEditImageBinding
import com.gh.gamecenter.eventbus.EBCommentSuccess
import com.gh.gamecenter.feature.entity.CommentEntity
import com.gh.gamecenter.feature.eventbus.EBDeleteComment
import com.gh.gamecenter.qa.answer.detail.AnswerDetailFragment
import com.gh.gamecenter.qa.comment.CommentActivity.Companion.GAME_COLLECTION_ID
import com.gh.gamecenter.qa.comment.CommentActivity.Companion.GAME_COLLECTION_TITLE
import com.gh.gamecenter.qa.comment.CommentActivity.Companion.QUESTION_ID
@ -95,7 +94,7 @@ open class NewCommentFragment : ListFragment<CommentEntity, NewCommentViewModel>
var mOffset: Int = 0
var mCommentCount: Int = 0
var mAdapter: ListAdapter<CommentEntity>? = null
var mCommentListener: AnswerDetailFragment.CommentListener? = null
var mCommentListener: CommentActivity.CommentListener? = null
private fun findView() {
commentContainer = mCachedView.findViewById(R.id.comment_container)
@ -357,7 +356,7 @@ open class NewCommentFragment : ListFragment<CommentEntity, NewCommentViewModel>
commentSendBtn.isEnabled = enable
}
fun setCommentListener(listener: AnswerDetailFragment.CommentListener) {
fun setCommentListener(listener: CommentActivity.CommentListener) {
mCommentListener = listener
}
@ -784,9 +783,8 @@ open class NewCommentFragment : ListFragment<CommentEntity, NewCommentViewModel>
showSoftKeyboardOnStartUp: Boolean,
commentCount: Int,
showInputOnly: Boolean,
listener: AnswerDetailFragment.CommentListener
)
: NewCommentFragment {
listener: CommentActivity.CommentListener
): NewCommentFragment {
return NewCommentFragment().apply {
mCommentListener = listener
with(
@ -809,7 +807,7 @@ open class NewCommentFragment : ListFragment<CommentEntity, NewCommentViewModel>
showInputOnly: Boolean,
useReplyApi: Boolean,
commentEntity: CommentEntity?,
listener: AnswerDetailFragment.CommentListener
listener: CommentActivity.CommentListener
)
: NewCommentFragment {
val commentType = if (useReplyApi) {
@ -841,7 +839,7 @@ open class NewCommentFragment : ListFragment<CommentEntity, NewCommentViewModel>
showInputOnly: Boolean,
useReplyApi: Boolean,
commentEntity: CommentEntity?,
listener: AnswerDetailFragment.CommentListener
listener: CommentActivity.CommentListener
)
: NewCommentFragment {
val commentType = if (useReplyApi) {
@ -874,7 +872,7 @@ open class NewCommentFragment : ListFragment<CommentEntity, NewCommentViewModel>
showInputOnly: Boolean,
isStairsComment: Boolean,
useReplyApi: Boolean,
listener: AnswerDetailFragment.CommentListener
listener: CommentActivity.CommentListener
)
: Fragment {
return if (isStairsComment) {
@ -927,7 +925,7 @@ open class NewCommentFragment : ListFragment<CommentEntity, NewCommentViewModel>
showInputOnly: Boolean,
useReplyApi: Boolean,
commentEntity: CommentEntity?,
listener: AnswerDetailFragment.CommentListener
listener: CommentActivity.CommentListener
)
: NewCommentFragment {
val commentType = if (useReplyApi) {

View File

@ -1,11 +0,0 @@
package com.gh.gamecenter.qa.entity
import com.google.gson.annotations.SerializedName
class AnswerDraftEntity(
@SerializedName("_id")
var id: String = "",
val content: String = "",
@SerializedName("answer_id")
val answerId: String = ""
)

View File

@ -27,7 +27,7 @@ class EditorInsertEntity(
entity.type = "answer"
entity.title = answer.questions.title?.eliminateDoubleQuote()
entity.brief = answer.brief?.eliminateDoubleQuote()
entity.icon = "http://static-web.ghzs.com/website-static/images/icon_new_reply.png"
entity.icon = "https://and-static.ghzs66.com/web/website-static/images/icon_new_reply.png"
return entity
}
@ -39,7 +39,7 @@ class EditorInsertEntity(
entity.type = "community_article"
entity.title = article.title.eliminateDoubleQuote()
entity.brief = article.brief.eliminateDoubleQuote()
entity.icon = "http://static-web.ghzs.com/website-static/images/icon_new_article.png"
entity.icon = "https://and-static.ghzs66.com/web/website-static/images/icon_new_article.png"
return entity
}
@ -60,7 +60,7 @@ class EditorInsertEntity(
entity.type = "game_collection"
entity.title = game.title
entity.brief = game.intro
entity.icon = "https://static-web.ghzs.com/website-static/images/icon_game_collection.png"
entity.icon = "https://and-static.ghzs66.com/web/website-static/images/icon_game_collection.png"
return entity
}
@ -71,7 +71,7 @@ class EditorInsertEntity(
entity.type = "video"
entity.title = video.title
entity.brief = video.des
entity.icon = "https://static-web.ghzs.com/website-static/images/icon_video.png"
entity.icon = "https://and-static.ghzs66.com/web/website-static/images/icon_video.png"
return entity
}
}

View File

@ -1,6 +0,0 @@
package com.gh.gamecenter.qa.myqa
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.databinding.AnswerDraftItemBinding
class AnswerDraftViewHolder(val binding: AnswerDraftItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)

View File

@ -1,40 +0,0 @@
package com.gh.gamecenter.qa.myqa;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.gh.gamecenter.common.base.activity.ToolBarActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.utils.ExtensionsKt;
/**
* Created by khy on 10/04/18.
*/
public class MyAskActivity extends ToolBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExtensionsKt.updateStatusBarColor(this, R.color.ui_surface, R.color.ui_surface);
}
@Override
protected boolean isAutoResetViewBackgroundEnabled() {
return true;
}
@Override
protected void onDarkModeChanged() {
super.onDarkModeChanged();
ExtensionsKt.updateStatusBarColor(this, R.color.ui_surface, R.color.ui_surface);
}
public static Intent getIntent(Context context) {
Bundle bundle = new Bundle();
bundle.putString(EntranceConsts.KEY_ENTRANCE, "(我的光环)+(我的问答)");
return getTargetIntent(context, MyAskActivity.class, MyAskWrapperFragment.class, bundle);
}
}

View File

@ -1,65 +0,0 @@
package com.gh.gamecenter.qa.myqa;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.base.fragment.BaseFragment_TabLayout;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.qa.article.MyArticleFragment;
import com.gh.gamecenter.qa.draft.CommunityDraftWrapperActivity;
import java.util.List;
/**
* Created by khy on 20/12/17.
*/
public class MyAskWrapperFragment extends BaseFragment_TabLayout {
@Override
protected void initFragmentList(List<Fragment> fragments) {
String entrance = null;
if (getArguments() != null) entrance = getArguments().getString(EntranceConsts.KEY_ENTRANCE);
fragments.add(MyAnswerFragment.getInstance(entrance));
fragments.add(MyArticleFragment.getInstance(entrance, UserManager.getInstance().getUserId()));
}
@Override
protected void initTabTitleList(List<String> tabTitleList) {
tabTitleList.add("我的回答");
tabTitleList.add("我的帖子");
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setNavigationTitle(R.string.my_forum);
initMenu(R.menu.menu_my_ask_wrapper);
if (mDividerLineView != null) {
mDividerLineView.setVisibility(View.VISIBLE);
}
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
MtaHelper.onEvent("我的光环_新", "我的问答", mTabTitleList.get(position) + "Tab");
}
@Override
public void onMenuItemClick(MenuItem menuItem) {
super.onMenuItemClick(menuItem);
if (menuItem.getItemId() == R.id.menu_draft) {
MtaHelper.onEvent("我的光环_新", "我的问答", "草稿");
startActivity(CommunityDraftWrapperActivity.getIntent(requireContext()));
}
}
}

View File

@ -40,7 +40,6 @@ import com.gh.gamecenter.feature.entity.Permissions
import com.gh.gamecenter.feature.entity.QuestionDraftEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.BbsType
import com.gh.gamecenter.qa.answer.edit.AnswerEditActivity
import com.gh.gamecenter.qa.article.draft.ArticleDraftActivity
import com.gh.gamecenter.qa.article.edit.ArticleEditActivity
import com.gh.gamecenter.qa.dialog.ChooseActivityDialogFragment
@ -470,7 +469,7 @@ class QuestionEditActivity : BaseRichEditorActivity<QuestionEditViewModel>(),
}
SaveDraftType.AUTO -> {
if (pair.second) {
if (mPostDraftsCount >= AnswerEditActivity.SAVE_DRAFTS_TOAST_COUNT) {
if (mPostDraftsCount >= SAVE_DRAFTS_TOAST_COUNT) {
mPostDraftsCount = 0
Utils.toast(this, "问题已保存到草稿箱")
} else {
@ -920,6 +919,7 @@ class QuestionEditActivity : BaseRichEditorActivity<QuestionEditViewModel>(),
companion object {
const val QUESTION_POSTED_TAG = "QUESTION_POSTED_TAG"
const val QUESTION_DRAFT_REQUEST_CODE = 105
const val SAVE_DRAFTS_TOAST_COUNT = 3
const val QUESTION_DRAFT_CHANGE_TAG = "ANSWER_DRAFT_CHANGE_TAG"
const val SAVE_DRAFTS_INTERVAL_TIME = 15000

View File

@ -408,7 +408,7 @@ class ForumTopVideoView @JvmOverloads constructor(context: Context, attrs: Attri
shareUrl = if (isPublishEnv()) {
"https://m.ghzs666.com/video/${it.id}"
} else {
"https://resource.ghzs.com/page/video_play/video/video.html?video=${it.id}"
"https://dev-and-static.ghzs66.com/page/video_play/video/video.html?video=${it.id}"
},
shareIcon = it.poster,
shareTitle = it.title,

View File

@ -41,7 +41,7 @@ public class InstallAndUninstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
PackageUtils.dumpInstalledListCache();
PackageHelper.INSTANCE.dumpInstalledListCache();
ExtensionsKt.doOnMainProcessOnly(() -> {
Utils.log("InstallAndUninstallReceiver:: onReceive->" + intent.getAction() + "==" + intent.getDataString());

View File

@ -112,7 +112,6 @@ import com.gh.gamecenter.feature.entity.MessageUnreadEntity;
import com.gh.gamecenter.feature.entity.NewsEntity;
import com.gh.gamecenter.feature.entity.PersonalEntity;
import com.gh.gamecenter.feature.entity.QuestionDraftEntity;
import com.gh.gamecenter.feature.entity.Questions;
import com.gh.gamecenter.feature.entity.ServerCalendarEntity;
import com.gh.gamecenter.feature.entity.ServerCalendarFormEntity;
import com.gh.gamecenter.feature.entity.ServerCalendarGame;
@ -128,7 +127,6 @@ import com.gh.gamecenter.home.custom.model.CustomPageData;
import com.gh.gamecenter.login.entity.UserInfoEntity;
import com.gh.gamecenter.personalhome.rating.MyRating;
import com.gh.gamecenter.qa.entity.AnswerDetailEntity;
import com.gh.gamecenter.qa.entity.AnswerDraftEntity;
import com.gh.gamecenter.qa.entity.ArticleDetailEntity;
import com.gh.gamecenter.qa.entity.AskSubjectEntity;
import com.gh.gamecenter.qa.entity.EditorInsertDefaultEntity;
@ -721,13 +719,6 @@ public interface ApiService {
@POST("answers/{answer_id}:unoppose")
Observable<ResponseBody> postAnswerUnoppose(@Path("answer_id") String answerId);
/**
* 获取用户的问题列表
*/
@GET("users/{user_id}/questions")
Observable<List<Questions>> getMyQuestions(@Path("user_id") String userId, @Query("page") int page,
@Query("channel") String channel, @Query("timestamp") long timestamp);
/**
* 获取用户的回答列表
*/
@ -735,18 +726,6 @@ public interface ApiService {
Observable<List<AnswerEntity>> getMyAnswers(@Path("user_id") String userId, @Query("page") int page,
@Query("channel") String channel, @Query("timestamp") long timestamp);
/**
* 获取用户的草稿列表
*/
@GET("users/{user_id}/answer_drafts")
Observable<List<AnswerEntity>> getAnswerDrafts(@Path("user_id") String userId, @Query("filter") String filter, @Query("page") int page);
/**
* 获取用户的关注问题列表
*/
@GET("users/{user_id}/follows/questions")
Observable<List<Questions>> getConcernQuestions(@Path("user_id") String user_id, @Query("page") int page);
/**
* 收藏回答
*/
@ -759,26 +738,6 @@ public interface ApiService {
@DELETE("users/{user_id}/favorites/answers/{answer_id}")
Observable<ResponseBody> deleteCollectionAnswer(@Path("user_id") String user_id, @Path("answer_id") String answerId);
/**
* 获取用户在相应问题的回答草稿
* filter:编辑文章时的草稿使用
*/
@GET("questions/{question_id}/answer_drafts")
Observable<AnswerDraftEntity> getUserAnswerDrafts(@Path("question_id") String questionId, @Query("filter") String filter, @Query("timestamp") long timestamp);
/**
* 保存用户回答的草稿
*/
@POST("users/{user_id}/answer_drafts")
Observable<ResponseBody> postAnswerDrafts(@Body RequestBody body, @Path("user_id") String user_id);
/**
* 删除用户草稿(撰写/编辑)
*/
@DELETE("users/{user_id}/answer_drafts/{draft_id}")
Observable<ResponseBody> deleteAnswerDrafts(@Path("user_id") String userId, @Path("draft_id") String draftId);
/**
* 获取用户收藏的回答列表
*/
@ -1035,12 +994,6 @@ public interface ApiService {
@GET("users/{user_id}/communities/articles?view=home_page")
Observable<List<ArticleEntity>> getMyArticle(@Path("user_id") String userId, @Query("page") int page);
/**
* 获取社区文章问题列表
*/
@GET("users/{user_id}/communities/articles?view=home_page&type=article-question")
Observable<List<AnswerEntity>> getMyArticleAndQuestion(@Path("user_id") String userId, @Query("page") int page);
/**
* 获取用户的文章草稿列表
*/
@ -2334,12 +2287,6 @@ public interface ApiService {
@POST("users/{user_id}:report")
Single<ResponseBody> reportUser(@Path("user_id") String userId, @Body RequestBody body);
/**
* 获取用户等级
*/
@GET("users/{user_id}/levels")
Single<JsonObject> getUserLevels(@Path("user_id") String userId);
/**
* 获取新分类2.0侧边栏
*/

View File

@ -1,11 +1,9 @@
package com.gh.gamecenter.retrofit.service
import com.gh.gamecenter.entity.AppEntity
import com.gh.gamecenter.entity.VNewSetting
import com.gh.gamecenter.entity.VSetting
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Query
interface VApiService {
@ -26,16 +24,4 @@ interface VApiService {
@GET("setting")
fun getSettings(@Query("version") version: String?, @Query("android") androidSdkVersion: Int): Single<VSetting>
@GET("new/setting")
fun getNewSettings(
@Query("version") version: String?,
@Query("android") androidSdkVersion: Int,
): Single<VNewSetting>
@GET("new/upgrade")
fun getNewPackageUpdate(
@Query("version") version: String?,
@Query("va_version") vaVersion: String?,
@Query("channel") channel: String,
): Single<AppEntity>
}

View File

@ -5,8 +5,8 @@ import android.app.Application
import android.content.pm.PackageManager
import com.gh.common.constant.Config
import com.gh.common.simulator.SimulatorGameManager
import com.gh.common.util.PackageHelper
import com.gh.gamecenter.common.utils.NetworkUtils
import com.gh.common.util.PackageUtils
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.feature.entity.ApkEntity
import com.gh.gamecenter.feature.entity.SimulatorEntity
@ -56,7 +56,7 @@ class SimulatorManagementViewModel(application: Application) :
return Single.create<List<SimulatorEntity>> { emitter ->
val simulatorEntityList = ArrayList<SimulatorEntity>()
val allInstalledPackages =
PackageUtils.getInstalledPackages(HaloApp.getInstance().application, PackageManager.GET_ACTIVITIES)
PackageHelper.getInstalledPackages(HaloApp.getInstance().application, PackageManager.GET_ACTIVITIES)
allInstalledPackages.forEach {
if (it.packageName.contains("com.gh")) {
val activityInfo =

View File

@ -358,7 +358,7 @@ class DetailPlayerView @JvmOverloads constructor(context: Context, attrs: Attrib
mBinding.censoringContainer.setOnClickListener {
DirectUtils.directToWebView(
context,
"https://resource.ghzs.com/page/video_rule/video_rule.html",
context.getString(R.string.upload_protocol_url),
mEntrance
)
}

View File

@ -1,65 +0,0 @@
package com.gh.gamecenter.video.poster
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.R
import com.gh.gamecenter.video.poster.video.VideoPosterFragment
import java.io.File
class PosterClipActivity : ToolBarActivity() {
override fun getLayoutId(): Int {
return R.layout.activity_poster_clip
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setNavigationTitle("剪辑封面")
val videoPath = intent.getStringExtra(EntranceConsts.KEY_PATH_VIDEO)
val fragment =
supportFragmentManager.findFragmentByTag(VideoPosterFragment::class.java.name) as? VideoPosterFragment
?: VideoPosterFragment.newInstance(videoPath, null)
supportFragmentManager
.beginTransaction()
.replace(R.id.layout_fragment_content, fragment, VideoPosterFragment::class.java.name)
.commitAllowingStateLoss()
findViewById<View>(R.id.menu_next).setOnClickListener {
val clipPath = cacheDir.absolutePath + File.separator + System.currentTimeMillis() + ".jpg"
fragment.savePicture(clipPath)
val intent = Intent()
intent.putExtra(EntranceConsts.KEY_PATH_VIDEO, videoPath)
intent.putExtra(EntranceConsts.KEY_POSTER_PATH, clipPath)
setResult(Activity.RESULT_OK, intent)
finish()
}
DisplayUtils.transparentStatusBar(this)
}
override fun provideNavigationIcon(): Int {
return R.drawable.ic_toolbar_back_white
}
override fun handleBackPressed(): Boolean {
DialogHelper.showDialog(this, "提示", "确定放弃剪辑封面吗?", "确定", "暂不", { finish() })
return true
}
companion object {
fun getIntent(context: Context, videoPath: String): Intent {
val intent = Intent(context, PosterClipActivity::class.java)
intent.putExtra(EntranceConsts.KEY_PATH_VIDEO, videoPath)
return intent
}
}
}

View File

@ -3,12 +3,16 @@ package com.gh.gamecenter.wrapper
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.view.View
import androidx.annotation.ColorRes
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.text.color
import androidx.core.view.doOnNextLayout
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gh.common.util.PackageHelper
import com.gh.gamecenter.R
import com.gh.gamecenter.ShellActivity
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
@ -24,6 +28,7 @@ import com.gh.gamecenter.databinding.FragmentMainBinding
import com.gh.gamecenter.databinding.PieceBottomTabBinding
import com.gh.gamecenter.entity.BottomTab
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.packagehelper.PackageRepository
import com.halo.assistant.HaloApp
import com.lightgame.listeners.OnBackPressedListener
import org.greenrobot.eventbus.EventBus
@ -62,6 +67,8 @@ class MainWrapperFragment : BaseBottomTabFragment<PieceBottomTabBinding>(), OnBa
setCurrentItem(mViewModel!!.defaultBottomTabIndex)
}
}
PackageRepository.addInstalledGame("com.woobest.sgwg.aligames")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
@ -77,6 +84,10 @@ class MainWrapperFragment : BaseBottomTabFragment<PieceBottomTabBinding>(), OnBa
mViewModel?.realNameInfoUpdateLiveData?.observe(viewLifecycleOwner) {
updateRealNameErrorContainer()
}
if (!PackageHelper.isGetInstalledPackagesApiAgreed()) {
showInstallApiHintView(mBinding)
}
}
fun setCurrentItem(page: Int) {
@ -255,6 +266,70 @@ class MainWrapperFragment : BaseBottomTabFragment<PieceBottomTabBinding>(), OnBa
}
}
private fun showInstallApiHintView(binding: FragmentMainBinding) {
val contentText = SpannableStringBuilder()
.color(R.color.text_theme.toColor(requireContext())) { append("您未授予已安装列表权限,可能") }
.color(R.color.secondary_red.toColor(requireContext())) { append("导致无法安装及更新") }
.color(R.color.text_theme.toColor(requireContext())) { append("建议开启权限!") }
binding.installApiContainer.visibility = View.VISIBLE
binding.installApiContainer.setOnClickListener {
// do nothing
}
binding.installApiCloseIv.enlargeTouchArea()
binding.installApiContentTv.text = contentText
binding.installApiCloseIv.setOnClickListener {
binding.installApiContainer.visibility = View.GONE
}
binding.installApiBtn.setOnClickListener {
val grantedClosure = {
binding.installApiContainer.visibility = View.GONE
PackageHelper.agreeOnGetInstalledPackagesApi()
// 进行包名初始化相关的操作
PackageRepository.initData()
PackageHelper.refreshLocalPackageList()
PackageHelper.refreshList()
}
if (PackageHelper.isSupportGetInstalledAppsPermission(requireContext())) {
// 若系统已经授予了获取应用列表的权限,直接进行授权成功回调
if (!PermissionHelper.isGetInstalledListPermissionDisabled(requireContext())) {
grantedClosure.invoke()
return@setOnClickListener
}
PermissionHelper.showGetInstalledAppsListPermissionDialogAndRequestPermission(requireContext() as FragmentActivity) { isGranted ->
// TODO 处理回调,上报日志等
if (isGranted) {
grantedClosure.invoke()
} else {
// TODO 处理拒绝权限的情况
}
}
} else {
val hintDialog = PermissionHelper.showGetInstalledAppsListPermissionDialogAndRequestPermission(requireContext() as FragmentActivity) {
// do nothing
}
val noticeDialog = DialogHelper.showDialog(
context = requireContext(),
title = "权限申请",
content = "是否允许“光环助手”获取已安装的应用信息",
confirmText = "开启",
cancelText = "拒绝",
confirmClickCallback = {
grantedClosure.invoke()
}
)
noticeDialog?.setOnDismissListener {
hintDialog?.dismiss()
}
}
}
}
override fun onDarkModeChanged() {
super.onDarkModeChanged()
changeBottomTabStyle(mBinding.viewPager.currentItem)

View File

@ -211,7 +211,7 @@ class MainWrapperRepository {
// 如果有优先级更高的选中 tab id则将优先级更高的选中 tab 设置为 default
if (mHighPrioritySelectedTopTabId.isNotEmpty() && mHighPrioritySelectedNavId == multiTabNav?.id) {
val selectedTab = multiTabNav.linkMultiTabNav.firstOrNull {
it.link?.link == mHighPrioritySelectedTopTabId
it.id == mHighPrioritySelectedTopTabId
}
// 将优先级更高的选中 tab 设置为 default
@ -225,7 +225,7 @@ class MainWrapperRepository {
defaultCustomPageId =
multiTabNav?.linkMultiTabNav?.find { it.link?.type == ViewPagerFragmentHelper.TYPE_CUSTOM_PAGE && it.default }?.link?.link ?: ""
multiTabNavLiveData.postValue(multiTabNav)
multiTabNavLiveData.value = multiTabNav
}
companion object : SingletonHolder<MainWrapperRepository>({ MainWrapperRepository() })

View File

@ -13,6 +13,7 @@ import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.graphics.ColorUtils
import androidx.core.view.doOnLayout
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import com.gh.common.constant.Config
@ -402,7 +403,9 @@ class SearchToolbarTabWrapperFragment : BaseTabWrapperFragment(), ISearchToolbar
val selectTab = it.getContentWithHandled()
if (selectTab is MainSelectedEvent.SelectedTab) {
if (selectTab.topTabIndex != -1) {
mViewPager?.setCurrentItem(selectTab.topTabIndex, false)
mViewPager?.doOnLayout {
mViewPager?.setCurrentItem(selectTab.topTabIndex, false)
}
}
}
}

View File

@ -4,10 +4,8 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
public interface ITestCase {
public interface IExternalGamesUsage {
void addInstallExternalGameButton(@NonNull ViewGroup viewParent);
void addInstallPluginButton(@NonNull ViewGroup viewParent);
void addInstallPlugin32Button(@NonNull ViewGroup viewParent);
}

View File

@ -2,11 +2,8 @@ package com.gh.vspace
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.database.sqlite.SQLiteDiskIOException
import android.os.*
import androidx.annotation.WorkerThread
import com.blankj.utilcode.util.LogUtils
import com.gh.download.simple.DownloadMessageHandler
import com.gh.download.simple.SimpleDownloadManager
import com.gh.gamecenter.common.retrofit.BiResponse
@ -25,11 +22,7 @@ import com.lg.download.DownloadStatus
import com.lg.download.httpclient.DefaultHttpClient
import com.lg.ndownload.DownloadConfigBuilder
import com.lg.vspace.VirtualAppManager
import com.lg.vspace.archive.data.Const
import com.lg.vspace.archive.ui.ArchiveManager
import com.lg.vspace.archive.ui.interfaces.ArchiveProgressPageListener
import com.lightgame.utils.Utils
import com.lody.virtual.client.core.VirtualCore
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import java.io.File
@ -50,31 +43,6 @@ object VArchiveHelper {
// 本地存档存放的位置
val archivePath by lazy { HaloApp.getInstance().filesDir.absolutePath + File.separator }
private var messenger: Messenger? = null
private val handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
when (msg.what) {
Const.MSG_USE_ARCHIVE -> {
msg.data?.let {
onApplyGameArchiveFinished(
packageName = it.getString(Const.EXTRA_PACKAGE_NAME, ""),
isSuccess = it.getBoolean(Const.EXTRA_IS_SUCCESS, false)
)
}
}
Const.MSG_GENERATE_ARCHIVE -> {
msg.data?.let {
onSaveGameArchiveFinished(
packageName = it.getString(Const.EXTRA_PACKAGE_NAME, ""),
isSuccess = it.getBoolean(Const.EXTRA_IS_SUCCESS, false)
)
}
}
}
messenger = null
}
}
fun init() {
DownloadMessageHandler.registerGlobalStatusChangedListener { simpleDownloadEntity, downloadStatus ->
when (downloadStatus) {
@ -194,26 +162,8 @@ object VArchiveHelper {
mSaveArchiveListener = saveArchiveListener
// 记录最近一次创建的存档文件
mLatestArchiveFile = archiveFile
if (VHelper.isLegacyInstalled(packageName)) {
val intent = VirtualAppManager.getGenerateArchiveIntent(context, config, packageName, archiveFile)
context.startActivity(intent)
} else {
if (VirtualCore.get().isRunInExtProcess(packageName)) {
val intent = VirtualAppManager.getGenerateArchiveIntent(context, config, packageName, archiveFile)
prepareExtIntent(intent)
context.startActivity(intent)
} else {
ArchiveManager.generatePackage(context, packageName, config, archiveFile,
object : ArchiveProgressPageListener {
override fun onCancel() {
}
override fun completed(isSuccess: Boolean) {
onSaveGameArchiveFinished(packageName, isSuccess)
}
})
}
}
val intent = VirtualAppManager.getGenerateArchiveIntent(context, config, packageName, archiveFile)
context.startActivity(intent)
}
/**
@ -229,43 +179,8 @@ object VArchiveHelper {
applyArchiveListener: ((String, Boolean) -> Unit)? = null
) {
mApplyArchiveListener = applyArchiveListener
if (VHelper.isLegacyInstalled(packageName)) {
val intent = VirtualAppManager.getUseArchiveIntent(context, packageName, config, archiveFile)
context.startActivity(intent)
} else {
if (VirtualCore.get().isRunInExtProcess(packageName)) {
val intent = VirtualAppManager.getUseArchiveIntent(context, packageName, config, archiveFile)
prepareExtIntent(intent)
context.startActivity(intent)
} else {
ArchiveManager.useArchive(context, packageName, archiveFile, config,
object : ArchiveProgressPageListener {
override fun onCancel() {
}
override fun completed(isSuccess: Boolean) {
LogUtils.d("存档使用 completed : $isSuccess")
if (applyArchiveListener != null) {
applyArchiveListener(packageName, isSuccess)
}
}
})
}
}
}
private fun prepareExtIntent(intent: Intent) {
intent.setClassName(
com.lg.vspace.BuildConfig.EXT_PACKAGE_NAME,
"com.lg.vspace.addon.launcher.RemoteGuideActivity"
)
intent.putExtra("callback", Bundle().also {
messenger = Messenger(handler)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
it.putBinder("messenger", messenger!!.binder)
}
})
val intent = VirtualAppManager.getUseArchiveIntent(context, packageName, config, archiveFile)
context.startActivity(intent)
}
/**

File diff suppressed because it is too large Load Diff

View File

@ -1,307 +0,0 @@
package com.gh.vspace
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.gh.common.exposure.ExposureUtils
import com.gh.common.exposure.ExposureUtils.DownloadType.DOWNLOAD
import com.gh.common.exposure.ExposureUtils.DownloadType.UPDATE
import com.gh.common.util.*
import com.gh.common.util.NewFlatLogUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseDraggableDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.DialogVspace32NewBinding
import com.gh.gamecenter.entity.AppEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.view.DownloadButton
import com.halo.assistant.HaloApp
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadConfig
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus.*
import com.lightgame.utils.AppManager
import java.io.File
class VSpace32NewDialogFragment : BaseDraggableDialogFragment() {
private var mAppEntity: AppEntity? = null
private var mGameId: String = ""
private var mGameName: String = ""
private val mDownloadUrl by lazy { mAppEntity?.url ?: "" }
private val mBinding by lazy { DialogVspace32NewBinding.inflate(layoutInflater) }
private var mIsLogInstallShow = false
private var mIsLogAutoInstallClick = false
private var mIsClickDownloadThisTime = false // 是否本次弹出Dialog点击的下载按钮
private val mDataWatcher = object : DataWatcher() {
override fun onDataChanged(downloadEntity: DownloadEntity) {
if (downloadEntity.url == mDownloadUrl && isAdded) {
updateDownloadButton(downloadEntity)
}
}
override fun onDataInit(downloadEntity: DownloadEntity) {
onDataChanged(downloadEntity)
}
}
override fun getRootView(): View = mBinding.root
override fun getDragCloseView(): View = mBinding.dragClose
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mAppEntity = arguments?.get(KEY_APP_ENTITY_32) as AppEntity
mGameId = arguments?.getString(EntranceConsts.KEY_GAME_ID) ?: ""
mGameName = arguments?.getString(EntranceConsts.KEY_GAME_NAME) ?: ""
}
@SuppressLint("ClickableViewAccessibility")
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return mBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val mViewModel = viewModelProvider<VSpaceDialogFragment.VSpaceDialogViewModel>()
mViewModel.packageLiveData.observe(this) {
if (it.packageName == VHelper.VSPACE_32BIT_NEW_PACKAGENAME) {
dismissAllowingStateLoss()
}
}
val downloadSnapshot = DownloadManager.getInstance()
.getDownloadEntitySnapshotByPackageName(VHelper.VSPACE_32BIT_NEW_PACKAGENAME)
mBinding.downloadBtn.text = if (downloadSnapshot?.status == done) "安装" else "下载"
mBinding.downloadBtn.buttonStyle = DownloadButton.ButtonStyle.NORMAL
mBinding.descTv.text = "$mGameName》需安装完整的畅玩服务组件,安装后即可给您带来急速的畅玩体验~"
mBinding.privacyPolicyTv.setOnClickListener {
NewFlatLogUtils.logHaloFunEvent("halo_fun_download_dialog_privacy_click")
DirectUtils.directToWebView(requireContext(), Constants.SMOOTH_GAME_PRIVACY_POLICY_ADDRESS)
}
if (downloadSnapshot?.status == done) {
NewFlatLogUtils.logHaloFunEvent("halo_fun_32_install_tip_dialog_show")
SensorsBridge.trackEvent("HaloFunExpandInstallDialogShow")
mIsLogInstallShow = true
} else {
NewFlatLogUtils.logHaloFun32DialogEvent("halo_fun_32_download_tip_dialog_show", mGameId, mGameName)
SensorsBridge.trackEvent("HaloFunExpandDownloadDialogShow", "game_id", mGameId, "game_name", mGameName)
}
mBinding.downloadBtn.setOnClickListener {
if (downloadSnapshot?.status == done) {
if (!File(downloadSnapshot.path).exists()) {
ToastUtils.toast("畅玩组件已损坏,即将重新下载")
DownloadManager.getInstance().cancel(downloadSnapshot.url)
DownloadManager.getInstance().add(downloadSnapshot)
} else {
PackageInstaller.install(requireContext(), downloadSnapshot)
NewFlatLogUtils.logHaloFunEvent("halo_fun_32_install_tip_dialog_click")
SensorsBridge.trackEvent("HaloFunExpandInstallButtonClick")
}
} else {
val downloadEntity = DownloadEntity()
val name = "畅玩游戏助手V" + mAppEntity?.version
val downloadId = PackageInstaller.createDownloadId(name)
downloadEntity.url = mDownloadUrl
downloadEntity.name = name
downloadEntity.platform = "官方版"
downloadEntity.gameId = Constants.HALO_FUN_NEW_32_GAME_ID
downloadEntity.path = PackageInstaller.getDownloadPathWithId(downloadId, "apk")
downloadEntity.packageName = VHelper.VSPACE_32BIT_NEW_PACKAGENAME
downloadEntity.addMetaExtra(DownloadConfig.KEY_PROGRESS_CALLBACK_INTERVAL, "200")
val gameEntity = GameEntity(downloadEntity.gameId, downloadEntity.name)
gameEntity.gameVersion = mAppEntity?.version ?: ""
// 确定下载类型
val downloadType =
if (arguments?.getBoolean(VSpaceDialogFragment.KEY_IS_UPDATE) == true) UPDATE else DOWNLOAD
downloadEntity.exposureTrace = ExposureUtils.logADownloadExposureEvent(
gameEntity,
downloadEntity.platform,
null,
downloadType
).toJson()
mIsClickDownloadThisTime = true
AppExecutor.uiExecutor.executeWithDelay({
DownloadManager.getInstance().cancel(mDownloadUrl)
DownloadManager.getInstance().add(downloadEntity)
}, 200)
DataCollectionUtils.uploadDownload(HaloApp.getInstance(), downloadEntity, "开始")
NewFlatLogUtils.logHaloFun32DialogEvent("halo_fun_32_download_tip_dialog_click", mGameId, mGameName)
SensorsBridge.trackEvent("HaloFunExpandDownloadDialogDownloadClick")
}
}
}
override fun onStart() {
super.onStart()
DownloadManager.getInstance().addObserver(mDataWatcher)
// 上面监听安装包名变化的 LiveData 监听有可能被冲掉了
// 手动再检查一下安装状态,避免出现已安装但是没有 dismiss 弹窗的问题
if (PackageUtils.isInstalledFromAllPackage(requireContext(), VHelper.VSPACE_32BIT_NEW_PACKAGENAME)) {
dismissAllowingStateLoss()
}
}
override fun onStop() {
super.onStop()
DownloadManager.getInstance().removeObserver(mDataWatcher)
}
private fun updateDownloadButton(downloadEntity: DownloadEntity) {
val downloadBtn = mBinding.downloadBtn
downloadBtn.progress = (downloadEntity.progress * 10).toInt()
when (downloadEntity.status) {
downloading -> {
downloadBtn.setText(R.string.pause)
downloadBtn.progress = (downloadEntity.percent * 10).toInt()
downloadBtn.buttonStyle = DownloadButton.ButtonStyle.DOWNLOADING_NORMAL
downloadBtn.setOnClickListener {
DownloadManager.getInstance().pause(mDownloadUrl)
}
}
pause -> {
downloadBtn.setText(R.string.resume)
downloadBtn.setOnClickListener {
DownloadManager.getInstance().resume(downloadEntity, true)
}
}
overflow,
timeout,
neterror,
diskisfull,
waiting,
subscribe -> {
downloadBtn.setText(R.string.waiting)
downloadBtn.buttonStyle = DownloadButton.ButtonStyle.DOWNLOADING_NORMAL
downloadBtn.setOnClickListener {
DownloadManager.getInstance().resume(downloadEntity, false)
}
}
done -> {
downloadBtn.setText(R.string.install)
downloadBtn.buttonStyle = DownloadButton.ButtonStyle.INSTALL_NORMAL
if (!mIsLogInstallShow) {
NewFlatLogUtils.logHaloFunEvent("halo_fun_32_install_tip_dialog_show")
NewFlatLogUtils.logHaloFunInstallTipDialogShow("32位")
SensorsBridge.trackEvent("HaloFunExpandInstallDialogShow")
mIsLogInstallShow = true
}
val isVSpace32DownloadOnly =
downloadEntity.getMetaExtra(Constants.EXTRA_DOWNLOAD_TYPE) == Constants.VSPACE_32_DOWNLOAD_ONLY
val isAutoInstall = SPUtils.getBoolean(Constants.SP_AUTO_INSTALL, true)
if (!isVSpace32DownloadOnly && isAutoInstall && !mIsLogAutoInstallClick && mIsClickDownloadThisTime) {
NewFlatLogUtils.logHaloFunEvent("halo_fun_32_install_tip_dialog_click")
SensorsBridge.trackEvent("HaloFunExpandInstallButtonClick")
mIsLogAutoInstallClick = true
}
downloadBtn.setOnClickListener {
if (!File(downloadEntity.path).exists()) {
ToastUtils.toast("畅玩组件已损坏,即将重新下载")
DownloadManager.getInstance().cancel(downloadEntity.url)
DownloadManager.getInstance().add(downloadEntity)
} else {
PackageInstaller.install(requireContext(), downloadEntity)
NewFlatLogUtils.logHaloFunEvent("halo_fun_32_install_tip_dialog_click")
SensorsBridge.trackEvent("HaloFunExpandInstallButtonClick")
}
}
}
cancel,
hijack,
notfound,
uncertificated,
unqualified -> {
downloadBtn.text = "下载"
downloadBtn.buttonStyle = DownloadButton.ButtonStyle.NORMAL
downloadBtn.setOnClickListener {
DownloadManager.getInstance().resume(downloadEntity, true)
}
}
else -> {
// do nothing
}
}
}
companion object {
const val KEY_APP_ENTITY_32 = "app_entity_32"
@JvmStatic
fun showDownloadDialog(
context: Context?,
appEntity32: AppEntity,
gameId: String = "",
gameName: String = ""
) {
val fragmentActivity: FragmentActivity = if (context is FragmentActivity) {
context
} else {
val currentActivity = AppManager.getInstance().currentActivity()
if (currentActivity is FragmentActivity) {
currentActivity
} else {
throw IllegalStateException("current activity context must be FragmentActivity")
}
}
// 防止重复弹出
if (hasDialogDisplayedInCurrentActivity(fragmentActivity)) return
val downloadDialog = VSpace32NewDialogFragment().apply {
arguments = Bundle().apply {
putParcelable(KEY_APP_ENTITY_32, appEntity32)
putString(EntranceConsts.KEY_GAME_ID, gameId)
putString(EntranceConsts.KEY_GAME_NAME, gameName)
}
}
downloadDialog.show(
fragmentActivity.supportFragmentManager,
VSpace32NewDialogFragment::class.java.name
)
}
private fun hasDialogDisplayedInCurrentActivity(fragmentActivity: FragmentActivity): Boolean {
val fragments: List<Fragment> = fragmentActivity.supportFragmentManager.fragments
fragments.forEach { fragment ->
if (fragment is VSpace32NewDialogFragment) return true
}
return false
}
}
}

View File

@ -1,303 +0,0 @@
package com.gh.vspace
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.gh.common.exposure.ExposureUtils
import com.gh.common.exposure.ExposureUtils.DownloadType.DOWNLOAD
import com.gh.common.exposure.ExposureUtils.DownloadType.UPDATE
import com.gh.common.util.DataCollectionUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.util.PackageInstaller
import com.gh.common.util.PackageUtils
import com.gh.gamecenter.feature.view.DownloadButton
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.DialogVspaceUpdate32NewBinding
import com.gh.gamecenter.entity.AppEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.halo.assistant.HaloApp
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadConfig
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus.*
import com.lightgame.utils.AppManager
import java.io.File
class VSpaceUpdate32NewDialogFragment : BaseDialogFragment() {
private var mAppEntity: AppEntity? = null
private var mGameId: String = ""
private var mGameName: String = ""
private val mDownloadUrl by lazy { mAppEntity?.url ?: "" }
private val mBinding by lazy { DialogVspaceUpdate32NewBinding.inflate(layoutInflater) }
private val mDataWatcher = object : DataWatcher() {
override fun onDataChanged(downloadEntity: DownloadEntity) {
if (downloadEntity.url == mDownloadUrl && isAdded) {
updateDownloadButton(downloadEntity)
}
}
override fun onDataInit(downloadEntity: DownloadEntity) {
onDataChanged(downloadEntity)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mAppEntity = arguments?.get(KEY_APP_ENTITY_32) as AppEntity
mGameId = arguments?.getString(EntranceConsts.KEY_GAME_ID) ?: ""
mGameName = arguments?.getString(EntranceConsts.KEY_GAME_NAME) ?: ""
}
@SuppressLint("ClickableViewAccessibility")
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return mBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val mViewModel = viewModelProvider<VSpaceDialogFragment.VSpaceDialogViewModel>()
mViewModel.packageLiveData.observe(this) {
if (it.packageName == VHelper.VSPACE_32BIT_NEW_PACKAGENAME) {
dismissAllowingStateLoss()
}
}
val downloadSnapshot = DownloadManager.getInstance()
.getDownloadEntitySnapshotByPackageName(VHelper.VSPACE_32BIT_NEW_PACKAGENAME)
mBinding.downloadBtn.text = if (downloadSnapshot?.status == done) "安装" else "下载"
mBinding.downloadBtn.buttonStyle = DownloadButton.ButtonStyle.NORMAL
mBinding.contentTv.text = "$mGameName》需安装完整的畅玩服务组件,安装后即可给您带来急速的畅玩体验~"
mBinding.downloadBtn.setOnClickListener {
NewFlatLogUtils.logHaloFun32DialogEvent("halo_fun_32_update_tip_dialog_click", mGameId, mGameName)
if (downloadSnapshot?.status == done) {
if (!File(downloadSnapshot.path).exists()) {
ToastUtils.toast("畅玩组件已损坏,即将重新下载")
DownloadManager.getInstance().cancel(downloadSnapshot.url)
DownloadManager.getInstance().add(downloadSnapshot)
} else {
PackageInstaller.install(requireContext(), downloadSnapshot)
}
} else {
val downloadEntity = DownloadEntity()
val name = "畅玩游戏助手V" + mAppEntity?.version
val downloadId = PackageInstaller.createDownloadId(name)
downloadEntity.url = mDownloadUrl
downloadEntity.name = name
downloadEntity.platform = "官方版"
downloadEntity.gameId = Constants.HALO_FUN_NEW_32_GAME_ID
downloadEntity.path = PackageInstaller.getDownloadPathWithId(downloadId, "apk")
downloadEntity.packageName = VHelper.VSPACE_32BIT_NEW_PACKAGENAME
downloadEntity.addMetaExtra(DownloadConfig.KEY_PROGRESS_CALLBACK_INTERVAL, "200")
val gameEntity = GameEntity(downloadEntity.gameId, downloadEntity.name)
gameEntity.gameVersion = mAppEntity?.version ?: ""
// 确定下载类型
val downloadType =
if (arguments?.getBoolean(VSpaceDialogFragment.KEY_IS_UPDATE) == true) UPDATE else DOWNLOAD
downloadEntity.exposureTrace = ExposureUtils.logADownloadExposureEvent(
gameEntity,
downloadEntity.platform,
null,
downloadType
).toJson()
AppExecutor.uiExecutor.executeWithDelay({
DownloadManager.getInstance().cancel(mDownloadUrl)
DownloadManager.getInstance().add(downloadEntity)
}, 200)
DataCollectionUtils.uploadDownload(HaloApp.getInstance(), downloadEntity, "开始")
}
}
}
override fun onStart() {
super.onStart()
DownloadManager.getInstance().addObserver(mDataWatcher)
// 上面监听安装包名变化的 LiveData 监听有可能被冲掉了
// 手动再检查一下安装状态,避免出现已安装但是没有 dismiss 弹窗的问题
if (PackageUtils.isInstalledFromAllPackage(requireContext(), VHelper.VSPACE_32BIT_NEW_PACKAGENAME)
&& mAppEntity?.version == PackageUtils.getVersionNameByPackageName(VHelper.VSPACE_32BIT_NEW_PACKAGENAME)
) {
dismissAllowingStateLoss()
}
}
override fun onStop() {
super.onStop()
DownloadManager.getInstance().removeObserver(mDataWatcher)
}
private fun updateDownloadButton(downloadEntity: DownloadEntity) {
val downloadBtn = mBinding.downloadBtn
downloadBtn.progress = (downloadEntity.progress * 10).toInt()
when (downloadEntity.status) {
downloading -> {
downloadBtn.setText(R.string.pause)
downloadBtn.progress = (downloadEntity.percent * 10).toInt()
downloadBtn.buttonStyle = DownloadButton.ButtonStyle.DOWNLOADING_NORMAL
downloadBtn.setOnClickListener {
DownloadManager.getInstance().pause(mDownloadUrl)
NewFlatLogUtils.logHaloFun32DialogEvent("halo_fun_32_update_tip_dialog_click", mGameId, mGameName)
}
}
pause -> {
downloadBtn.setText(R.string.resume)
downloadBtn.setOnClickListener {
DownloadManager.getInstance().resume(downloadEntity, true)
NewFlatLogUtils.logHaloFun32DialogEvent("halo_fun_32_update_tip_dialog_click", mGameId, mGameName)
}
}
overflow,
timeout,
neterror,
diskisfull,
waiting,
subscribe -> {
downloadBtn.setText(R.string.waiting)
downloadBtn.buttonStyle = DownloadButton.ButtonStyle.DOWNLOADING_NORMAL
downloadBtn.setOnClickListener {
DownloadManager.getInstance().resume(downloadEntity, false)
NewFlatLogUtils.logHaloFun32DialogEvent("halo_fun_32_update_tip_dialog_click", mGameId, mGameName)
}
}
done -> {
downloadBtn.setText(R.string.install)
downloadBtn.buttonStyle = DownloadButton.ButtonStyle.INSTALL_NORMAL
downloadBtn.setOnClickListener {
if (!File(downloadEntity.path).exists()) {
ToastUtils.toast("畅玩组件已损坏,即将重新下载")
DownloadManager.getInstance().cancel(downloadEntity.url)
DownloadManager.getInstance().add(downloadEntity)
} else {
PackageInstaller.install(requireContext(), downloadEntity)
NewFlatLogUtils.logHaloFun32DialogEvent(
"halo_fun_32_update_tip_dialog_click",
mGameId,
mGameName
)
}
}
}
cancel,
hijack,
notfound,
uncertificated,
unqualified -> {
downloadBtn.text = "下载"
downloadBtn.buttonStyle = DownloadButton.ButtonStyle.NORMAL
downloadBtn.setOnClickListener {
DownloadManager.getInstance().resume(downloadEntity, true)
NewFlatLogUtils.logHaloFun32DialogEvent("halo_fun_32_update_tip_dialog_click", mGameId, mGameName)
}
}
else -> {
// do nothing
}
}
}
companion object {
const val KEY_APP_ENTITY_32 = "app_entity_32"
const val KEY_AUTO_DOWNLOAD = "auto_download"
const val KEY_IS_UPDATE = "is_update"
@JvmStatic
fun showDownloadDialog(
context: Context?,
appEntity32: AppEntity,
autoDownload: Boolean = false,
isUpdate: Boolean = false,
gameId: String = "",
gameName: String = ""
) {
val fragmentActivity: FragmentActivity = if (context is FragmentActivity) {
context
} else {
val currentActivity = AppManager.getInstance().currentActivity()
if (currentActivity is FragmentActivity) {
currentActivity
} else {
throw IllegalStateException("current activity context must be FragmentActivity")
}
}
// 防止重复弹出
if (hasDialogDisplayedInCurrentActivity(fragmentActivity)) return
NewFlatLogUtils.logHaloFun32DialogEvent("halo_fun_32_update_tip_dialog_show", gameId, gameName)
val downloadDialog = VSpaceUpdate32NewDialogFragment().apply {
arguments = Bundle().apply {
putParcelable(KEY_APP_ENTITY_32, appEntity32)
putString(EntranceConsts.KEY_GAME_ID, gameId)
putString(EntranceConsts.KEY_GAME_NAME, gameName)
putBoolean(KEY_AUTO_DOWNLOAD, autoDownload)
putBoolean(KEY_IS_UPDATE, isUpdate)
}
}
downloadDialog.show(
fragmentActivity.supportFragmentManager,
VSpaceUpdate32NewDialogFragment::class.java.name
)
}
@JvmStatic
fun showDownloadDialog(
context: Context?,
appEntity32: AppEntity,
gameEntity: GameEntity?,
autoDownload: Boolean = false,
isUpdate: Boolean = false
) {
showDownloadDialog(
context,
appEntity32,
autoDownload,
isUpdate,
gameEntity?.id ?: "",
gameEntity?.name ?: ""
)
}
private fun hasDialogDisplayedInCurrentActivity(fragmentActivity: FragmentActivity): Boolean {
val fragments: List<Fragment> = fragmentActivity.supportFragmentManager.fragments
fragments.forEach { fragment ->
if (fragment is VSpaceUpdate32NewDialogFragment) return true
}
return false
}
}
}

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