refactor(mvvm): 收敛 ViewModel 基类并移除反射与废弃可见性回调

- BaseViewModel/BaseAndroidViewModel 抽出 MvvmUiStateDelegate,消除两份重复的 LiveData 与订阅管理
- 新增 SingleLiveEvent,error/success 改为一次性事件,避免页面重建后重复提示
- BaseMvvmActivity/BaseMvvmFragment 改为 abstract getViewModelClass(),删除泛型反射创建
- BaseFragment 以宿主选中+已 resume 计算可见性,HomeActivity 统一分发,移除 setUserVisibleHint
- 删除未被使用的 BaseMvvmDialogFragment,RestartFragment 直接继承 BaseDialogFragment
- UsageFragment 的请求登记与同步时间落盘下沉到 UsageViewModel,ViewModel 内不再弹 Toast
- DeviceFragment 的版本比较下沉到 DeviceViewModel,改用一次性事件触发跳转
This commit is contained in:
tongtong committed 2026-11-11 17:34:47 +08:00
1 parent 1aca29e0d5
commit 859a0e996f
19 files changed
+515 -601

No files matched your search

@@ -1,30 +1,44 @@
package com.fuying.sn.core.base;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
/**
* DialogFragment 基类,提供与 {@link BaseFragment} 一致的懒加载入口。
*
* <p>Dialog 不在 ViewPager 中,可见性直接由自身生命周期决定,
* 因此不再实现已废弃的 {@code setUserVisibleHint()}。
*/
public abstract class BaseDialogFragment extends DialogFragment {
protected boolean isViewInitiated;
protected boolean isVisibleToUser;
protected boolean isDataInitiated;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
isViewInitiated = true;
prepareFetchData();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
this.isVisibleToUser = isVisibleToUser;
public void onResume() {
super.onResume();
isVisibleToUser = true;
prepareFetchData();
}
@Override
public void onPause() {
isVisibleToUser = false;
super.onPause();
}
public abstract void fetchData();
public boolean prepareFetchData() {
@@ -40,5 +54,4 @@ public abstract class BaseDialogFragment extends DialogFragment {
}
return false;
}
}
@@ -2,20 +2,26 @@ package com.fuying.sn.core.base;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
/**
* Fragment 基类,提供标准的懒加载框架
* <p>
* 兼容两种宿主场景:
* 1. ViewPager(v1) + FragmentPagerAdapter:通过 {@link #setUserVisibleHint} 判断可见性(老接口,deprecated)
* 2. ViewPager2 / FragmentTransaction.setMaxLifecycle:通过 onResume/onPause 判断可见性
* <p>
* 懒加载核心思路:
* 1. 视图创建完成({@code isViewInitiated}) + 当前页可见({@code isVisibleToUser}) 两个条件同时满足时,
* 才触发首次加载({@link #onLazyLoad()}),之后切回该页不再重复触发。
*
* <p>可见性由两个条件共同决定:
* 1. 宿主告知"当前是否为选中页"({@link #setPageSelected(boolean)});
* 2. 自身生命周期已进入 onResume。
*
* <p>这样既覆盖 ViewPager 场景,又不再依赖已废弃的
* {@code setUserVisibleHint()}(该方法在 ViewPager 之外根本不会被调用,
* 且与 setMaxLifecycle 等新机制冲突)。
*
* <p>懒加载核心思路:
* 1. 视图创建完成 + 对用户可见两个条件同时满足时,才触发首次加载({@link #onLazyLoad()}),
* 之后切回该页不再重复触发。
* 2. {@link #fetchData()} 每次可见都会回调,用于需要刷新的场景。
* 3. View 销毁重建后自动重置懒加载状态,保证重建后的页面能重新渲染。
*/
@@ -30,31 +36,29 @@ public abstract class BaseFragment extends Fragment {
/** 首次数据是否已初始化 */
protected boolean isDataInitiated;
/** 宿主(ViewPager)告知的选中状态 */
private boolean isPageSelected;
/** 自身是否处于 onResume 之后 */
private boolean isResumed;
@Override
public void onViewCreated(@androidx.annotation.NonNull android.view.View view, @Nullable Bundle savedInstanceState) {
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
isViewInitiated = true;
// 视图已创建,检查是否满足懒加载条件
prepareFetchData();
updateVisibility();
}
@Override
public void onResume() {
super.onResume();
// ViewPager2 / setMaxLifecycle 场景下没有 setUserVisibleHint 回调,用 onResume 判断可见性;
// 兼容 ViewPager(v1):off-screen 页 getUserVisibleHint()==false,不会被误判为可见
if (!isViewInitiated || isHidden() || !getUserVisibleHint()) {
return;
}
setVisibleToUser(true);
isResumed = true;
updateVisibility();
}
@Override
public void onPause() {
// ViewPager2 / setMaxLifecycle 场景下用 onPause 判断不可见
if (isViewInitiated && !isHidden() && getUserVisibleHint()) {
setVisibleToUser(false);
}
isResumed = false;
updateVisibility();
super.onPause();
}
@@ -69,27 +73,40 @@ public abstract class BaseFragment extends Fragment {
}
/**
* ViewPager(v1) + FragmentPagerAdapter 场景下,通过此回调精确判断当前页是否可见
* 宿主页面切换时通知本页是否被选中。
*
* <p>替代已废弃的 {@code setUserVisibleHint()}:由持有 ViewPager 的 Activity
* 在 onPageSelected 中统一分发,各 Fragment 不再各自等待系统回调。
*
* @param selected 是否当前选中页
*/
@Override
@Deprecated
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (!isViewInitiated) {
public void setPageSelected(boolean selected) {
if (isPageSelected == selected) {
return;
}
setVisibleToUser(isVisibleToUser);
isPageSelected = selected;
updateVisibility();
}
/**
* 统一更新可见性并触发懒加载判断
* 汇总可见性:选中页 + 已 resume + 视图已创建 + 未被 hide,四者同时成立才算可见。
*/
private void setVisibleToUser(boolean visible) {
if (this.isVisibleToUser == visible) {
private void updateVisibility() {
boolean visible = isPageSelected && isResumed && isViewInitiated && !isHidden();
if (isVisibleToUser == visible) {
return;
}
this.isVisibleToUser = visible;
prepareFetchData();
isVisibleToUser = visible;
onVisibilityChanged(visible);
if (visible) {
prepareFetchData();
}
}
/**
* 可见性变化回调,子类可重写做进入/退出处理。
*/
protected void onVisibilityChanged(boolean visible) {
}
/**
@@ -5,7 +5,6 @@ import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
@@ -16,120 +15,70 @@ import io.reactivex.rxjava3.disposables.Disposable;
* 继承 {@link AndroidViewModel},可通过 {@link #getAppContext()} 获取 Application 级别的 Context。
* Application Context 生命周期与进程一致,不会造成内存泄漏。
*
* 职责:
* - 持有 UI 状态(LiveData)
* - 处理业务逻辑
* - 暴露数据给 View 层
* - 通过 {@link #addDisposable(Disposable)} 统一管理 RxJava 异步任务
* - 可通过 {@link #getAppContext()} 获取 Application Context(安全)
* 通用 UI 状态与订阅管理复用 {@link MvvmUiStateDelegate},与 {@link BaseViewModel} 保持一致,
* 两者只差父类,除 Application 访问外不应出现行为差异。
*
* 禁止:
* - 持有任何 View 引用(Activity / Fragment / View)
* - 使用 Activity Context 或持有 View 的 Context(只能使用 Application)
* - 直接进行网络请求或数据库操作(必须通过 Repository)
* - 在 ViewModel 中弹 Toast / Dialog / Snackbar
* - 手动创建 Thread / Executor / AsyncTask 执行异步任务(必须使用 RxJava + {@link #addDisposable(Disposable)})
* - 忘记将 Disposable add 到 {@link #mDisposables} 中
* - 在 ViewModel 中弹 Toast / Dialog / Snackbar(改用 {@link #setSuccess(String)} / {@link #setError(String)})
*/
public abstract class BaseAndroidViewModel extends AndroidViewModel implements IMvvmUiState {
// ============================================================
// 通用 UI 状态
// ============================================================
/** 全局加载状态 */
private final MutableLiveData<Boolean> mLoadingLiveData = new MutableLiveData<>(false);
/** 全局错误提示 */
private final MutableLiveData<String> mErrorLiveData = new MutableLiveData<>();
/** 全局成功提示 */
private final MutableLiveData<String> mSuccessLiveData = new MutableLiveData<>();
// ============================================================
// RxJava 异步管理(核心)
// ============================================================
/** 通用 UI 状态与订阅集合的共享实现 */
private final MvvmUiStateDelegate mUiState = new MvvmUiStateDelegate();
/**
* CompositeDisposable 用于统一管理所有 RxJava 订阅。
* 在 onCleared() 中自动 dispose,防止内存泄漏。
* CompositeDisposable 用于统一管理所有 RxJava 订阅,在 onCleared() 中自动 dispose。
*/
protected final CompositeDisposable mDisposables = new CompositeDisposable();
// ============================================================
// 构造方法
// ============================================================
protected final CompositeDisposable mDisposables = mUiState.disposables();
public BaseAndroidViewModel(@NonNull Application application) {
super(application);
}
// ============================================================
// 对外暴露(只读)
// ============================================================
@Override
public LiveData<Boolean> getLoadingLiveData() {
return mLoadingLiveData;
return mUiState.getLoadingLiveData();
}
@Override
public LiveData<String> getErrorLiveData() {
return mErrorLiveData;
return mUiState.getErrorLiveData();
}
@Override
public LiveData<String> getSuccessLiveData() {
return mSuccessLiveData;
return mUiState.getSuccessLiveData();
}
// ============================================================
// 受保护的方法(子类调用)
// ============================================================
protected void setLoading(boolean loading) {
mLoadingLiveData.postValue(loading);
mUiState.setLoading(loading);
}
protected void setError(String message) {
mErrorLiveData.postValue(message);
mUiState.setError(message);
}
protected void setSuccess(String message) {
mSuccessLiveData.postValue(message);
mUiState.setSuccess(message);
}
/**
* 便捷方法:将 Disposable 添加到 {@link #mDisposables} 中管理。
* 子类在发起 RxJava 请求时调用此方法。
*/
protected void addDisposable(Disposable disposable) {
mDisposables.add(disposable);
mUiState.addDisposable(disposable);
}
// ============================================================
// Context 安全访问
// ============================================================
/**
* 获取 Application Context(安全,不会泄漏)。
* 子类可通过此方法访问:
* - getApplication().getSharedPreferences(...)
* - getApplication().getResources().getString(...)
* - getApplication().getSystemService(...)
*/
@NonNull
protected Application getAppContext() {
return getApplication();
}
// ============================================================
// 生命周期
// ============================================================
@Override
protected void onCleared() {
super.onCleared();
// ViewModel 销毁时,自动取消所有正在执行的 RxJava 任务
if (!mDisposables.isDisposed()) {
mDisposables.clear();
}
mUiState.clear();
}
}
@@ -2,8 +2,6 @@ package com.fuying.sn.core.base.mvvm;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
@@ -12,16 +10,14 @@ import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import com.fuying.sn.core.base.BaseTransparentActivity;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import com.fuying.sn.core.common.util.ToastUtil;
/**
* MVVM Activity 基类
*
* 职责:
* - 绑定 DataBinding
* - 初始化 ViewModel(默认通过反射自动创建)
* - 初始化 ViewModel(子类通过 {@link #getViewModelClass()} 显式声明,不使用反射)
* - 订阅 ViewModel 中的 LiveData({@link #observeViewModel()})
* - 订阅全局通用状态({@link #observeCommonState()})
* - 页面创建完成后加载数据({@link #onLoadData()})
@@ -45,11 +41,8 @@ import java.lang.reflect.ParameterizedType;
*/
public abstract class BaseMvvmActivity<VM extends ViewModel, VDB extends ViewDataBinding> extends BaseTransparentActivity {
private static final String TAG = BaseMvvmActivity.class.getSimpleName();
protected VM mViewModel;
protected VDB mViewDataBinding;
protected Class<VM> vmClass;
// ============================================================
// 生命周期
@@ -84,15 +77,17 @@ public abstract class BaseMvvmActivity<VM extends ViewModel, VDB extends ViewDat
// 抽象方法(子类必须实现)
// ============================================================
/** 创建 ViewModel 实例(默认通过反射自动创建,子类可按需重写) */
/**
* 声明本页使用的 ViewModel 类型。
*
* <p>历史上这里通过解析泛型参数反射创建 ViewModel,反射失败时只能得到 null 且难以排查;
* 改为子类显式返回具体 Class,编译期即可发现遗漏。
*/
protected abstract Class<VM> getViewModelClass();
/** 创建 ViewModel 实例(默认按 {@link #getViewModelClass()} 创建,子类可按需重写) */
protected VM createViewModel() {
vmClass = (Class<VM>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
boolean isAbstract = Modifier.isAbstract(vmClass.getModifiers());
if (isAbstract) {
Log.e(TAG, "ViewModel is abstract: " + vmClass.getSimpleName());
return null;
}
return new ViewModelProvider(this).get(vmClass);
return new ViewModelProvider(this).get(getViewModelClass());
}
/** 初始化 DataBinding(如设置 setClick、绑定表达式等) */
@@ -159,11 +154,11 @@ public abstract class BaseMvvmActivity<VM extends ViewModel, VDB extends ViewDat
}
protected void showError(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
ToastUtil.show(message);
}
protected void showSuccess(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
ToastUtil.show(message);
}
// ============================================================
@@ -1,7 +1,6 @@
package com.fuying.sn.core.base.mvvm;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
@@ -11,7 +10,7 @@ import io.reactivex.rxjava3.disposables.Disposable;
* MVVM ViewModel 基类(无 Context 版本)
*
* 职责:
* - 持有 UI 状态(LiveData)
* - 持有 UI 状态(LiveData),通用状态与一次性提示统一由 {@link MvvmUiStateDelegate} 提供
* - 处理业务逻辑
* - 暴露数据给 View 层
* - 通过 {@link #addDisposable(Disposable)} 统一管理 RxJava 异步任务
@@ -19,68 +18,48 @@ import io.reactivex.rxjava3.disposables.Disposable;
* 禁止:
* - 持有任何 View 引用(Activity / Fragment / View / Context)
* - 直接进行网络请求或数据库操作(必须通过 Repository)
* - 在 ViewModel 中弹 Toast / Dialog / Snackbar
* - 在 ViewModel 中弹 Toast / Dialog / Snackbar(改用 {@link #setSuccess(String)} / {@link #setError(String)})
* - 手动创建 Thread / Executor / AsyncTask 执行异步任务(必须使用 RxJava + {@link #addDisposable(Disposable)})
* - 忘记将 Disposable add 到 {@link #mDisposables} 中
*
* 若需要 Context / Application(如 SharedPreferences、AlarmManager 等),请继承
* 若需要 Context / Application(如 SharedPreferences、PackageManager 等),请继承
* {@link BaseAndroidViewModel},通过 {@code getAppContext()} 获取 Application Context。
*/
public abstract class BaseViewModel extends ViewModel implements IMvvmUiState {
// ============================================================
// 通用 UI 状态
// ============================================================
/** 全局加载状态 */
private final MutableLiveData<Boolean> mLoadingLiveData = new MutableLiveData<>(false);
/** 全局错误提示 */
private final MutableLiveData<String> mErrorLiveData = new MutableLiveData<>();
/** 全局成功提示 */
private final MutableLiveData<String> mSuccessLiveData = new MutableLiveData<>();
// ============================================================
// RxJava 异步管理(核心)
// ============================================================
/** 通用 UI 状态与订阅集合的共享实现 */
private final MvvmUiStateDelegate mUiState = new MvvmUiStateDelegate();
/**
* CompositeDisposable 用于统一管理所有 RxJava 订阅。
* 在 onCleared() 中自动 dispose,防止内存泄漏。
* CompositeDisposable 用于统一管理所有 RxJava 订阅,在 onCleared() 中自动 dispose。
*/
protected final CompositeDisposable mDisposables = new CompositeDisposable();
// ============================================================
// 对外暴露(只读)
// ============================================================
protected final CompositeDisposable mDisposables = mUiState.disposables();
@Override
public LiveData<Boolean> getLoadingLiveData() {
return mLoadingLiveData;
return mUiState.getLoadingLiveData();
}
@Override
public LiveData<String> getErrorLiveData() {
return mErrorLiveData;
return mUiState.getErrorLiveData();
}
@Override
public LiveData<String> getSuccessLiveData() {
return mSuccessLiveData;
return mUiState.getSuccessLiveData();
}
// ============================================================
// 受保护的方法(子类调用)
// ============================================================
protected void setLoading(boolean loading) {
mLoadingLiveData.postValue(loading);
mUiState.setLoading(loading);
}
protected void setError(String message) {
mErrorLiveData.postValue(message);
mUiState.setError(message);
}
protected void setSuccess(String message) {
mSuccessLiveData.postValue(message);
mUiState.setSuccess(message);
}
/**
@@ -88,19 +67,12 @@ public abstract class BaseViewModel extends ViewModel implements IMvvmUiState {
* 子类在发起 RxJava 请求时调用此方法,确保 ViewModel 销毁时自动取消订阅。
*/
protected void addDisposable(Disposable disposable) {
mDisposables.add(disposable);
mUiState.addDisposable(disposable);
}
// ============================================================
// 生命周期
// ============================================================
@Override
protected void onCleared() {
super.onCleared();
// ViewModel 销毁时,自动取消所有正在执行的 RxJava 任务
if (!mDisposables.isDisposed()) {
mDisposables.clear();
}
mUiState.clear();
}
}
@@ -6,17 +6,20 @@ import androidx.lifecycle.LiveData;
* MVVM ViewModel 通用 UI 状态接口
*
* {@link BaseViewModel} 与 {@link BaseAndroidViewModel} 均实现本接口,
* 使基类({@link BaseMvvmActivity} / {@link BaseMvvmFragment} / {@link BaseMvvmDialogFragment})
* 能以统一的 {@code VM extends ViewModel} 泛型约束订阅 loading / error / success 状态。
* 使基类({@link BaseMvvmActivity} / {@link BaseMvvmFragment})能以统一的
* {@code VM extends ViewModel} 泛型约束订阅 loading / error / success 状态。
*
* loading 是状态(重建后需要恢复);error / success 是一次性事件,
* 由 {@link SingleLiveEvent} 实现,只消费一次,不会因页面重建重复提示。
*/
public interface IMvvmUiState {
/** 全局加载状态(只读) */
LiveData<Boolean> getLoadingLiveData();
/** 全局错误提示(只读) */
/** 全局错误提示(只读,一次性事件) */
LiveData<String> getErrorLiveData();
/** 全局成功提示(只读) */
/** 全局成功提示(只读,一次性事件) */
LiveData<String> getSuccessLiveData();
}
@@ -0,0 +1,74 @@
package com.fuying.sn.core.base.mvvm;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
/**
* ViewModel 通用状态的共享实现。
*
* <p>{@link BaseViewModel} 与 {@link BaseAndroidViewModel} 只差一个父类(ViewModel /
* AndroidViewModel),Java 单继承无法再抽公共父类,因此把 loading / error / success 状态
* 与 RxJava 订阅管理抽到本类,两个基类通过组合复用,避免两份完全相同的实现各自维护。
*
* <p>error / success 使用 {@link SingleLiveEvent}:它们表达的是"提示一次"的动作,
* 不能因为页面重建而被重复消费。
*/
final class MvvmUiStateDelegate implements IMvvmUiState {
/** 全局加载状态(状态型,重建后需要恢复,所以用普通 LiveData) */
private final MutableLiveData<Boolean> mLoadingLiveData = new MutableLiveData<>(false);
/** 全局错误提示(一次性事件) */
private final SingleLiveEvent<String> mErrorLiveData = new SingleLiveEvent<>();
/** 全局成功提示(一次性事件) */
private final SingleLiveEvent<String> mSuccessLiveData = new SingleLiveEvent<>();
private final CompositeDisposable mDisposables = new CompositeDisposable();
@Override
public LiveData<Boolean> getLoadingLiveData() {
return mLoadingLiveData;
}
@Override
public LiveData<String> getErrorLiveData() {
return mErrorLiveData;
}
@Override
public LiveData<String> getSuccessLiveData() {
return mSuccessLiveData;
}
void setLoading(boolean loading) {
mLoadingLiveData.postValue(loading);
}
void setError(String message) {
mErrorLiveData.postValue(message);
}
void setSuccess(String message) {
mSuccessLiveData.postValue(message);
}
void addDisposable(Disposable disposable) {
mDisposables.add(disposable);
}
/** 供基类暴露给子类的订阅集合 */
CompositeDisposable disposables() {
return mDisposables;
}
/** ViewModel 销毁时统一取消订阅 */
void clear() {
if (!mDisposables.isDisposed()) {
mDisposables.clear();
}
}
}
@@ -0,0 +1,43 @@
package com.fuying.sn.core.base.mvvm;
import androidx.annotation.MainThread;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* 一次性事件 LiveData。
*
* <p>普通 LiveData 是"状态",新订阅者(如屏幕旋转后重建的页面)会立刻再收到最后一次值,
* 导致 Toast、跳转、弹窗这类"动作"被重复执行。本类只把值投递给第一个消费它的观察者,
* 之后的重新订阅不会再收到旧事件。
*
* <p>注意:仅适用于单观察者场景(本项目的 Activity / Fragment 各自持有自己的 ViewModel),
* 多观察者同时订阅时只有一个能收到事件。
*
* @param <T> 事件数据类型
*/
public class SingleLiveEvent<T> extends MutableLiveData<T> {
/** 是否有未消费的事件 */
private final AtomicBoolean mPending = new AtomicBoolean(false);
@MainThread
@Override
public void observe(LifecycleOwner owner, Observer<? super T> observer) {
super.observe(owner, value -> {
if (mPending.compareAndSet(true, false)) {
observer.onChanged(value);
}
});
}
@MainThread
@Override
public void setValue(T value) {
mPending.set(true);
super.setValue(value);
}
}
@@ -1,236 +0,0 @@
package com.fuying.sn.core.base.mvvm.fragment;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import com.fuying.sn.core.base.BaseDialogFragment;
import com.fuying.sn.core.base.mvvm.IMvvmUiState;
import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;
/**
* MVVM DialogFragment 基类
*
* 职责:
* - 绑定 DataBinding
* - 初始化 ViewModel(默认通过反射自动创建)
* - 订阅 ViewModel 中的 LiveData({@link #observeViewModel()})
* - 订阅全局通用状态({@link #observeCommonState()})
* - 页面创建完成后加载数据({@link #onLoadData()})
* - 将用户操作转发给 ViewModel
*
* 禁止:
* - 在 DialogFragment 中直接进行网络请求或数据库操作(必须通过 ViewModel → Repository)
* - 持有可变 LiveData 的引用(应通过 LiveData 回调观察)
* - 在 DialogFragment 中写业务逻辑
*
* @param <VM> ViewModel 类型,必须继承 {@link BaseViewModel} 或 {@link BaseAndroidViewModel}
* @param <VDB> ViewDataBinding 类型
*/
public abstract class BaseMvvmDialogFragment<VM extends ViewModel, VDB extends ViewDataBinding> extends BaseDialogFragment {
protected final String mTag = this.getClass().getSimpleName();
protected boolean mIsVisible;
protected boolean mHasPrepare;
protected VM mViewModel;
protected VDB mViewDataBinding;
private WeakReference<Context> ctx;
public Context getCtx() {
return ctx == null ? null : ctx.get();
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
ctx = new WeakReference<>(context);
}
// ============================================================
// 生命周期
// ============================================================
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ViewModel 初始化
try {
mViewModel = createViewModel();
} catch (Exception e) {
Log.e(mTag, "ViewModel initialization failed: " + e.getMessage());
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// DataBinding 初始化
mViewDataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
return mViewDataBinding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mViewDataBinding.setLifecycleOwner(getViewLifecycleOwner());
// 订阅通用状态
observeCommonState();
// 订阅业务状态
observeViewModel();
initDataBinding();
initView(savedInstanceState);
// 加载数据
onLoadData();
mHasPrepare = true;
if (mIsVisible || getUserVisibleHint()) {
mIsVisible = true;
onEnter();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
mHasPrepare = false;
// 及时解绑 Binding,防止内存泄漏
mViewDataBinding = null;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (mIsVisible == isVisibleToUser) return;
mIsVisible = isVisibleToUser;
if (mIsVisible) {
if (mHasPrepare) {
onEnter();
}
} else {
if (mHasPrepare) {
onExit();
}
}
}
@Override
public void fetchData() {
}
// ============================================================
// 抽象方法(子类必须实现)
// ============================================================
/** 创建 ViewModel 实例(默认通过反射自动创建,子类可按需重写) */
protected VM createViewModel() {
Class<VM> vmClass = (Class<VM>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
return new ViewModelProvider(this).get(vmClass);
}
@LayoutRes
protected abstract int getLayoutId();
/** 初始化 DataBinding(如设置 setClick、绑定表达式等) */
protected abstract void initDataBinding();
/** 初始化视图(如设置 Adapter、Listener 等) */
protected abstract void initView(Bundle savedInstanceState);
/** 订阅 ViewModel 中的业务 LiveData */
protected abstract void observeViewModel();
// ============================================================
// 可选重写
// ============================================================
/**
* 页面创建完成后加载数据
* 子类可重写此方法触发首次数据加载
*/
protected void onLoadData() {
// 默认空实现
}
/**
* 订阅全局通用状态(loading / error / success)
*/
protected void observeCommonState() {
if (!(mViewModel instanceof IMvvmUiState)) return;
IMvvmUiState vm = (IMvvmUiState) mViewModel;
vm.getLoadingLiveData().observe(getViewLifecycleOwner(), loading -> {
if (loading != null && loading) {
showLoading();
} else {
hideLoading();
}
});
vm.getErrorLiveData().observe(getViewLifecycleOwner(), error -> {
if (error != null && !error.isEmpty()) {
showError(error);
}
});
vm.getSuccessLiveData().observe(getViewLifecycleOwner(), msg -> {
if (msg != null && !msg.isEmpty()) {
showSuccess(msg);
}
});
}
// ============================================================
// UI 辅助方法(子类可重写)
// ============================================================
protected void showLoading() {
}
protected void hideLoading() {
}
protected void showError(String message) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
protected void showSuccess(String message) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
protected void onEnter() {
}
protected void onExit() {
}
public boolean isAttached() {
return getCtx() != null && isAdded();
}
}
@@ -7,7 +7,6 @@ import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
@@ -19,45 +18,39 @@ import androidx.lifecycle.ViewModelProvider;
import com.fuying.sn.core.base.BaseFragment;
import com.fuying.sn.core.base.mvvm.IMvvmUiState;
import com.fuying.sn.core.common.util.ToastUtil;
import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;
/**
* MVVM Fragment 基类
* <p>
* 职责:
* - 绑定 DataBinding
* - 初始化 ViewModel(默认通过反射自动创建)
* - 初始化 ViewModel(子类通过 {@link #getViewModelClass()} 显式声明,不使用反射)
* - 订阅 ViewModel 中的 LiveData({@link #observeViewModel()})
* - 订阅全局通用状态({@link #observeCommonState()})
* - 页面创建完成后加载数据({@link #onLoadData()})
* - 支持懒加载({@link #onEnter()} / {@link #onExit()})
* - 将用户操作转发给 ViewModel
* <p>
* 可见性由 {@link BaseFragment} 统一计算(宿主选中 + 已 resume),
* 本类只把可见性变化转成 {@link #onEnter()} / {@link #onExit()} 回调。
* <p>
* 禁止:
* - 在 Fragment 中直接进行网络请求或数据库操作(必须通过 ViewModel → Repository)
* - 持有可变 LiveData 的引用(应通过 LiveData 回调观察)
* - 在 Fragment 中写业务逻辑
* - 使用 getActivity() 强转后直接操作 Activity(应通过 ViewModel 通信)
*
* @param <VM> ViewModel 类型,必须继承 {@link BaseViewModel} 或 {@link BaseAndroidViewModel}
* @param <VM> ViewModel 类型,必须继承 {@link com.fuying.sn.core.base.mvvm.BaseViewModel}
* 或 {@link com.fuying.sn.core.base.mvvm.BaseAndroidViewModel}
* @param <VDB> ViewDataBinding 类型
*/
public abstract class BaseMvvmFragment<VM extends ViewModel, VDB extends ViewDataBinding> extends BaseFragment {
protected final String mTag = this.getClass().getSimpleName();
/**
* 是否可见(用于懒加载逻辑)
*/
protected boolean mIsVisible;
/**
* View 是否准备完毕
*/
protected boolean mHasPrepare;
protected VM mViewModel;
protected VDB mViewDataBinding;
@@ -84,7 +77,7 @@ public abstract class BaseMvvmFragment<VM extends ViewModel, VDB extends ViewDat
try {
mViewModel = createViewModel();
} catch (Exception e) {
Log.e(mTag, "ViewModel initialization failed: " + e.getMessage());
Log.e(mTag, "ViewModel 初始化失败: " + e.getMessage());
}
}
@@ -112,36 +105,24 @@ public abstract class BaseMvvmFragment<VM extends ViewModel, VDB extends ViewDat
// 加载数据
onLoadData();
mHasPrepare = true;
// 检查初始可见性
if (mIsVisible || getUserVisibleHint()) {
mIsVisible = true;
onEnter();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
mHasPrepare = false;
// 及时解绑 Binding,防止内存泄漏
mViewDataBinding = null;
}
/**
* 可见性变化:转成进入/退出回调,保持子类原有的懒加载语义。
*/
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (mIsVisible == isVisibleToUser) return;
mIsVisible = isVisibleToUser;
if (mIsVisible) {
if (mHasPrepare) {
onEnter();
}
protected void onVisibilityChanged(boolean visible) {
if (visible) {
onEnter();
} else {
if (mHasPrepare) {
onExit();
}
onExit();
}
}
@@ -150,11 +131,17 @@ public abstract class BaseMvvmFragment<VM extends ViewModel, VDB extends ViewDat
// ============================================================
/**
* 创建 ViewModel 实例(默认通过反射自动创建,子类可按需重写)
* 声明本 Fragment 使用的 ViewModel 类型。
*
* <p>改为显式声明后不再解析泛型反射创建,编译期即可发现遗漏。
*/
protected abstract Class<VM> getViewModelClass();
/**
* 创建 ViewModel 实例(默认按 {@link #getViewModelClass()} 创建,子类可按需重写)
*/
protected VM createViewModel() {
Class<VM> vmClass = (Class<VM>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
return new ViewModelProvider(this).get(vmClass);
return new ViewModelProvider(this).get(getViewModelClass());
}
@LayoutRes
@@ -189,7 +176,7 @@ public abstract class BaseMvvmFragment<VM extends ViewModel, VDB extends ViewDat
/**
* 订阅全局通用状态(loading / error / success)
* 子类可在 {@link #observeViewModel()} 中调用 super.observeCommonState(),或直接重写
* error / success 是一次性事件,只会提示一次。
*/
protected void observeCommonState() {
if (!(mViewModel instanceof IMvvmUiState)) return;
@@ -228,11 +215,11 @@ public abstract class BaseMvvmFragment<VM extends ViewModel, VDB extends ViewDat
}
protected void showError(String message) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
ToastUtil.show(message);
}
protected void showSuccess(String message) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
ToastUtil.show(message);
}
// ============================================================
@@ -23,11 +23,10 @@ import androidx.fragment.app.FragmentTransaction;
import com.fuying.sn.R;
import com.fuying.sn.core.base.BaseDialogFragment;
import com.fuying.sn.core.base.mvvm.fragment.BaseMvvmDialogFragment;
import com.fuying.sn.databinding.FragmentDialogRestartBinding;
import com.fuying.sn.core.common.util.Utils;
public class RestartFragment extends BaseMvvmDialogFragment {
public class RestartFragment extends BaseDialogFragment {
private static final String TAG = "RestartFragment";
@@ -123,24 +122,4 @@ public class RestartFragment extends BaseMvvmDialogFragment {
public void fetchData() {
}
@Override
protected int getLayoutId() {
return 0;
}
@Override
protected void initDataBinding() {
}
@Override
protected void initView(Bundle savedInstanceState) {
}
@Override
protected void observeViewModel() {
}
}
@@ -22,7 +22,6 @@ import com.fuying.sn.core.data.dto.DeviceInfo;
import com.fuying.sn.core.data.dto.SnInfo;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.databinding.FragmentDeviceBinding;
import com.fuying.sn.platform.app.ApkUtils;
import com.fuying.sn.platform.system.JgyUtils;
import com.fuying.sn.platform.time.TimeUtils;
import com.fuying.sn.core.common.util.Utils;
@@ -45,6 +44,11 @@ public class DeviceFragment extends BaseMvvmFragment<DeviceViewModel, FragmentDe
// 记录上次成功触发的时间
private final long[] lastClickTime = {0};
@Override
protected Class<DeviceViewModel> getViewModelClass() {
return DeviceViewModel.class;
}
@Override
protected int getLayoutId() {
return R.layout.fragment_device;
@@ -121,19 +125,19 @@ public class DeviceFragment extends BaseMvvmFragment<DeviceViewModel, FragmentDe
public void onChanged(AppInfo appInfo) {
if (appInfo != null) {
mViewDataBinding.tvUpdateVersion.setText(appInfo.getApp_version_name());
if (ApkUtils.isUpdate(mContext, appInfo)) {
Intent intent = new Intent(mContext, UpdateActivity.class);
intent.putExtra("appInfo", appInfo);
startActivity(intent);
Toaster.show("有新的版本需要更新");
} else {
// Toaster.show("已是最新版本");
}
} else {
Toaster.show("已是最新版本");
}
}
});
// 升级判断已在 ViewModel 完成,这里只处理"需要跳转更新页"这一个动作
mViewModel.updateAvailable.observe(this, new Observer<AppInfo>() {
@Override
public void onChanged(AppInfo appInfo) {
Intent intent = new Intent(mContext, UpdateActivity.class);
intent.putExtra("appInfo", appInfo);
startActivity(intent);
}
});
mViewModel.checkUpdate(false);
}
@@ -1,33 +1,57 @@
package com.fuying.sn.feature.device;
import android.app.Application;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import com.fuying.sn.BuildConfig;
import com.fuying.sn.core.base.mvvm.BaseViewModel;
import com.fuying.sn.core.base.mvvm.BaseAndroidViewModel;
import com.fuying.sn.core.base.mvvm.SingleLiveEvent;
import com.fuying.sn.core.data.dto.AppInfo;
import com.fuying.sn.core.data.dto.BaseResponse;
import com.fuying.sn.core.data.dto.DeviceInfo;
import com.fuying.sn.core.data.dto.SnInfo;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.core.data.repository.TimeConfigRepository;
import com.fuying.sn.platform.app.ApkUtils;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.observers.DisposableObserver;
public class DeviceViewModel extends BaseViewModel {
/**
* 设备信息页的 ViewModel。
*
* <p>升级判断(本地版本与服务端版本比较)属于业务逻辑,放在这里完成;
* 视图层只负责展示版本号与跳转,不再自行比较版本。
* 需要 PackageManager 比较版本号,因此继承 {@link BaseAndroidViewModel} 获取 Application Context。
*/
public class DeviceViewModel extends BaseAndroidViewModel {
private static final String TAG = "DeviceViewModel";
private final DeviceRepository mRepository = DeviceRepository.getInstance();
public MutableLiveData<SnInfo> mSnInfoMutableLiveData = new MutableLiveData<>();
public DeviceViewModel(Application application) {
super(application);
}
public final MutableLiveData<SnInfo> mSnInfoMutableLiveData = new MutableLiveData<>();
/** 检测到可升级版本(一次性事件,视图层收到后跳转更新页) */
public final SingleLiveEvent<AppInfo> updateAvailable = new SingleLiveEvent<>();
public final MutableLiveData<DeviceInfo> mDeviceInfoMutableLiveData = new MutableLiveData<>();
public final MutableLiveData<AppInfo> mAppInfoMutableLiveData = new MutableLiveData<>();
public void getSnInfo() {
Disposable disposable = mRepository.getSnInfoControl()
.subscribeWith(new DisposableObserver<BaseResponse<SnInfo>>() {
@Override
public void onNext(@NonNull BaseResponse<SnInfo> snInfoBaseResponse) {
Log.e("getSnInfo", "onNext: " + snInfoBaseResponse);
Log.e(TAG, "getSnInfo onNext: " + snInfoBaseResponse);
if (snInfoBaseResponse.code == 200) {
SnInfo snInfo = snInfoBaseResponse.data;
// 统一交由 TimeConfigRepository 落库 + 回调,保证数据源唯一
@@ -40,23 +64,21 @@ public class DeviceViewModel extends BaseViewModel {
@Override
public void onError(@NonNull Throwable e) {
Log.e("getSnInfo", "onError: " + e.getMessage());
Log.e(TAG, "getSnInfo onError: " + e.getMessage());
}
@Override
public void onComplete() {
Log.e("getSnInfo", "onComplete: ");
Log.e(TAG, "getSnInfo onComplete: ");
}
});
mDisposables.add(disposable);
}
public MutableLiveData<DeviceInfo> mDeviceInfoMutableLiveData = new MutableLiveData<>();
public void getDeviceInfo() {
Disposable disposable = mRepository.getDeviceInfoObservable()
.subscribe(mDeviceInfoMutableLiveData::setValue, error -> {
Log.e("DeviceViewModel", "getDeviceInfo: ", error);
Log.e(TAG, "getDeviceInfo: ", error);
if (error instanceof DeviceRepository.ResponseException) {
mDeviceInfoMutableLiveData.setValue(null);
}
@@ -64,32 +86,39 @@ public class DeviceViewModel extends BaseViewModel {
mDisposables.add(disposable);
}
public MutableLiveData<AppInfo> mAppInfoMutableLiveData = new MutableLiveData<>();
public void checkUpdate(boolean response) {
/**
* 检查是否有新版本。
*
* @param userTriggered 是否由用户手动触发(手动触发时才在"无更新"场景给出提示)
*/
public void checkUpdate(boolean userTriggered) {
Disposable disposable = mRepository.getUpdateObservable(BuildConfig.APPLICATION_ID)
.subscribeWith(new DisposableObserver<BaseResponse<AppInfo>>() {
@Override
public void onNext(@NonNull BaseResponse<AppInfo> appInfoBaseResponse) {
Log.e("checkUpdate", "onNext: " + appInfoBaseResponse);
Log.e(TAG, "checkUpdate onNext: " + appInfoBaseResponse);
if (appInfoBaseResponse.code == 200) {
AppInfo appInfo = appInfoBaseResponse.data;
mAppInfoMutableLiveData.setValue(appInfo);
} else {
if (response) {
mAppInfoMutableLiveData.setValue(null);
if (appInfo != null && ApkUtils.isUpdate(getAppContext(), appInfo)) {
// 是否可升级由此处判断,视图层只负责跳转
updateAvailable.setValue(appInfo);
setSuccess("有新的版本需要更新");
}
} else if (userTriggered) {
mAppInfoMutableLiveData.setValue(null);
setSuccess("已是最新版本");
}
}
@Override
public void onError(@NonNull Throwable e) {
Log.e("checkUpdate", "onError: " + e.getMessage());
Log.e(TAG, "checkUpdate onError: " + e.getMessage());
}
@Override
public void onComplete() {
Log.e("checkUpdate", "onComplete: ");
Log.e(TAG, "checkUpdate onComplete: ");
}
});
mDisposables.add(disposable);
@@ -16,6 +16,7 @@ import androidx.viewpager.widget.ViewPager;
import com.blankj.utilcode.util.NetworkUtils;
import com.fuying.sn.BuildConfig;
import com.fuying.sn.R;
import com.fuying.sn.core.base.BaseFragment;
import com.fuying.sn.core.base.mvvm.BaseMvvmActivity;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.core.common.util.DebugPasswordVerifier;
@@ -46,7 +47,6 @@ public class HomeActivity extends BaseMvvmActivity<HomeViewModel, ActivityHomeBi
private List<Fragment> mFragments;
private FragmentManager mFragmentManager;
private BaseFragmentPagerAdapter mBaseFragmentPagerAdapter;
private ViewPager.OnPageChangeListener mListener;
private int defaultCurrent = 0;
@Override
@@ -69,6 +69,11 @@ public class HomeActivity extends BaseMvvmActivity<HomeViewModel, ActivityHomeBi
return R.layout.activity_home;
}
@Override
protected Class<HomeViewModel> getViewModelClass() {
return HomeViewModel.class;
}
@Override
protected void initDataBinding() {
mViewDataBinding.setClick(new BtnClick());
@@ -82,9 +87,34 @@ public class HomeActivity extends BaseMvvmActivity<HomeViewModel, ActivityHomeBi
mFragmentManager = getSupportFragmentManager();
mBaseFragmentPagerAdapter = new BaseFragmentPagerAdapter(mFragmentManager, mFragments);
mViewDataBinding.viewPager.setAdapter(mBaseFragmentPagerAdapter);
mViewDataBinding.viewPager.setOnPageChangeListener(mListener);
mViewDataBinding.viewPager.setOffscreenPageLimit(4);
mViewDataBinding.viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
updatePageSelection(position);
}
});
mViewDataBinding.mainSlidingTabLayout.setViewPager(mViewDataBinding.viewPager, mAllTitle);
// 初始页不会回调 onPageSelected,这里主动同步一次选中状态
updatePageSelection(mViewDataBinding.viewPager.getCurrentItem());
}
/**
* 通知各 Fragment 当前选中页。
*
* <p>原先各 Fragment 依赖已废弃的 setUserVisibleHint() 判断可见性,
* 现由持有 ViewPager 的宿主统一分发,Fragment 内部不再等待系统回调。
*/
private void updatePageSelection(int selectedPosition) {
if (mFragments == null) {
return;
}
for (int i = 0; i < mFragments.size(); i++) {
Fragment fragment = mFragments.get(i);
if (fragment instanceof BaseFragment) {
((BaseFragment) fragment).setPageSelected(i == selectedPosition);
}
}
}
@Override
@@ -88,6 +88,11 @@ public class MainActivity extends BaseMvvmActivity<MainViewModel, ActivityMainBi
return R.layout.activity_main;
}
@Override
protected Class<MainViewModel> getViewModelClass() {
return MainViewModel.class;
}
@Override
protected void initDataBinding() {
mViewDataBinding.setClick(new BtnClick());
@@ -25,6 +25,11 @@ public class UpdateActivity extends BaseMvvmActivity<UpdateViewModel, ActivityUp
return R.layout.activity_update;
}
@Override
protected Class<UpdateViewModel> getViewModelClass() {
return UpdateViewModel.class;
}
@Override
protected void initDataBinding() {
mViewDataBinding.setClick(new BtnClick());
@@ -56,9 +56,7 @@ import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.Simple
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class UsageFragment extends BaseMvvmFragment<UsageViewModel, FragmentUsageBinding> {
private static final String TAG = "UsageFragment";
@@ -75,20 +73,10 @@ public class UsageFragment extends BaseMvvmFragment<UsageViewModel, FragmentUsag
private AppControlDetailAdapter mAppControlDetailAdapter;
// 一次 loadData 周期内登记的请求集合,用于判断整体是否全部请求完成。
// 取代原先硬编码的 TOTAL_REQUESTS,因为实际请求数量取决于 onSettingData 的结果
// (限制场景会额外发出 controlStatus / remainingTime / appControlDetail 三个请求)。
private static final String REQ_SETTING = "setting";
private static final String REQ_USE_TIME = "useTime";
private static final String REQ_CONTROL_STATUS = "controlStatus";
private static final String REQ_REMAINING_TIME = "remainingTime";
private static final String REQ_APP_CONTROL_DETAIL = "appControlDetail";
private final Set<String> mPendingRequests = new HashSet<>();
// 本次 loadData 周期登记的总请求数(含根据 onSettingData 动态补充的请求),
// 用于判断整体是否全部成功
private int mTotalRequests = 0;
private int mSuccessCount = 0;
@Override
protected Class<UsageViewModel> getViewModelClass() {
return UsageViewModel.class;
}
@Override
protected int getLayoutId() {
@@ -115,7 +103,6 @@ public class UsageFragment extends BaseMvvmFragment<UsageViewModel, FragmentUsag
initChart();
initTabs();
// 进入页面时先展示上一次缓存的同步时间
updateLastSyncTime();
selectTab(0);
}
@@ -141,75 +128,32 @@ public class UsageFragment extends BaseMvvmFragment<UsageViewModel, FragmentUsag
mViewModel.loading.observe(getViewLifecycleOwner(), this::onLoading);
mViewModel.error.observe(getViewLifecycleOwner(), this::onError);
mViewModel.lastSyncTime.observe(getViewLifecycleOwner(), this::onLastSyncTime);
loadData();
}
private void loadData() {
// 重置请求登记,统计本次 loadData 是否全部请求成功。
// 先登记一定会发出的两个请求:设置信息与使用时长。
mPendingRequests.clear();
mSuccessCount = 0;
mPendingRequests.add(REQ_SETTING);
mPendingRequests.add(REQ_USE_TIME);
mTotalRequests = mPendingRequests.size();
mViewModel.loadSettingData();
loadAppUseTime();
// 整页刷新与请求统计统一由 ViewModel 负责,视图层只负责触发与定位
mViewModel.loadAll(mQueryType, mIsAll ? 1 : 0);
AmapManager.getInstance().startLocation();
}
/**
* 登记一个整体请求。仅 loadData 周期内发出的请求需要登记,
* 由 onSettingData 根据数据动态补充登记额外请求。
* 把同步时间戳渲染到界面。
*/
private void registerRequest(String tag) {
if (mPendingRequests.add(tag)) {
mTotalRequests++;
}
}
/**
* 统计本次 loadData 内各请求的完成情况。
* 当全部已登记的请求都完成且都成功时,保存当前时间戳到 MMKV 并刷新同步时间显示。
* 注意:本方法仅用于 loadData 周期登记的请求;切换 Tab / fetchData 触发的单独
* loadAppUseTime 不会登记,因此不会计入整体同步时间。
*/
private void onRequestFinished(String tag, boolean success) {
if (!mPendingRequests.remove(tag)) {
// 该请求未被登记(如非 loadData 触发的单独请求),不计入整体同步时间
return;
}
if (success) {
mSuccessCount++;
}
if (mPendingRequests.isEmpty()) {
// 所有已登记的请求都已完成,全部成功才算本次同步成功
if (mSuccessCount >= mTotalRequests) {
long now = System.currentTimeMillis();
mMMKV.encode(CommonConfig.LAST_SYNC_TIME_KEY, now);
updateLastSyncTime();
}
mSuccessCount = 0;
}
}
/**
* 读取 MMKV 中缓存的同步时间戳并展示到 tv_last_sync_time。
*/
private void updateLastSyncTime() {
long ts = mMMKV.decodeLong(CommonConfig.LAST_SYNC_TIME_KEY, 0);
if (ts > 0) {
mViewDataBinding.tvLastSyncTime.setText("最新数据同步时间:" + TimeUtils.transferLongToDate(ts));
private void onLastSyncTime(Long timestamp) {
if (timestamp != null && timestamp > 0) {
mViewDataBinding.tvLastSyncTime.setText("最新数据同步时间:" + TimeUtils.transferLongToDate(timestamp));
} else {
mViewDataBinding.tvLastSyncTime.setText("最新数据同步时间:暂无");
}
}
private void onSettingData(BaseResponse<SystemSettingsSet> response) {
boolean success = response.code == 200 && response.data != null && response.data.getUser() != null;
onRequestFinished(REQ_SETTING, success);
if (!success) {
if (response == null || response.code != 200 || response.data == null
|| response.data.getUser() == null) {
return;
}
SystemSettings systemSettings = response.data.getUser();
@@ -219,13 +163,6 @@ public class UsageFragment extends BaseMvvmFragment<UsageViewModel, FragmentUsag
mViewDataBinding.tvRemainingTime.setText("");
mViewDataBinding.tvNoData.setVisibility(View.GONE);
mViewDataBinding.recyclerView.setVisibility(View.VISIBLE);
// 限制场景下动态补充登记额外请求,使其计入整体同步时间统计
registerRequest(REQ_CONTROL_STATUS);
registerRequest(REQ_REMAINING_TIME);
registerRequest(REQ_APP_CONTROL_DETAIL);
mViewModel.loadControlCombined();
mViewModel.loadAppControlDetail();
} else {
mViewDataBinding.tvControlType.setText("不限制");
mViewDataBinding.tvControlType.setBackground(mContext.getResources().getDrawable(R.drawable.tv_time_unlimited_background));
@@ -243,8 +180,6 @@ public class UsageFragment extends BaseMvvmFragment<UsageViewModel, FragmentUsag
private void onControlCombined(ControlStatusCombined combined) {
boolean statusOk = combined.controlStatus != null;
boolean remainOk = combined.remainingTime != null;
onRequestFinished(REQ_CONTROL_STATUS, statusOk);
onRequestFinished(REQ_REMAINING_TIME, remainOk);
if (!statusOk) {
// 管控状态获取失败:整体置为“不支持”
@@ -304,7 +239,6 @@ public class UsageFragment extends BaseMvvmFragment<UsageViewModel, FragmentUsag
}
private void onAppControlDetail(List<AppControlDetail> details) {
onRequestFinished(REQ_APP_CONTROL_DETAIL, details != null);
mAppControlDetailAdapter.setAppTimeControlInfos(details);
}
@@ -438,7 +372,6 @@ public class UsageFragment extends BaseMvvmFragment<UsageViewModel, FragmentUsag
private void onAppUseTime(BaseResponse<AppUseTimeData> response) {
AppUseTimeData resp = response.data;
onRequestFinished(REQ_USE_TIME, response.code == 200 && resp != null && !resp.getApp_list().isEmpty());
if (resp == null || resp.getApp_list().isEmpty()) {
// 数据为空时清空图表已有内容
mBarChart.clear();
@@ -5,6 +5,8 @@ import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import com.fuying.sn.core.base.mvvm.BaseViewModel;
import com.fuying.sn.core.base.mvvm.SingleLiveEvent;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.core.data.dto.BaseResponse;
import com.fuying.sn.core.data.dto.SystemSettingsSet;
import com.fuying.sn.core.domain.model.AppControlDetail;
@@ -14,9 +16,11 @@ import com.fuying.sn.core.domain.model.ControlStatusInfo;
import com.fuying.sn.core.domain.model.RemainingTimeBean;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.core.data.repository.StatisticsRepository;
import com.hjq.toast.Toaster;
import com.tencent.mmkv.MMKV;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
@@ -24,13 +28,31 @@ import io.reactivex.rxjava3.functions.Consumer;
/**
* UsageFragment 对应的 ViewModel。
* <p>
* 职责:持有 UI 状态(LiveData)、调用 StatisticsRepository 获取数据,
* 网络与 IO 由 Repository 负责。
* 由基类使用 CompositeDisposable 管理订阅,在 onCleared 时释放。
* 职责:持有 UI 状态(LiveData)、编排整页请求、统计本轮同步是否全部成功并落盘同步时间。
* 视图层只负责把数据渲染到控件,不再维护请求登记与计数。
* <p>
* 提示信息通过 {@link #setSuccess(String)} 走基类的一次性事件通道,ViewModel 内不弹 Toast。
*/
public class UsageViewModel extends BaseViewModel {
private static final String TAG = "UsageViewModel";
// 一轮完整刷新中可能出现的请求标识。
// 不能硬编码总数:限制场景会额外发出 controlStatus / remainingTime / appControlDetail 三个请求,
// 所以按实际登记情况动态统计。
private static final String REQ_SETTING = "setting";
private static final String REQ_USE_TIME = "useTime";
private static final String REQ_CONTROL_STATUS = "controlStatus";
private static final String REQ_REMAINING_TIME = "remainingTime";
private static final String REQ_APP_CONTROL_DETAIL = "appControlDetail";
private final StatisticsRepository mRepository = StatisticsRepository.getInstance();
private final MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);
// 本轮刷新中尚未返回的请求,以及成功计数,用于判断整页是否全部成功
private final Set<String> mPendingRequests = new HashSet<>();
private int mTotalRequests = 0;
private int mSuccessCount = 0;
// ===== UI 状态(对外暴露 LiveData,类型与 Repository 返回类型一致)=====
public final MutableLiveData<BaseResponse<SystemSettingsSet>> settingData = new MutableLiveData<>();
@@ -43,39 +65,114 @@ public class UsageViewModel extends BaseViewModel {
public final MutableLiveData<BaseResponse<AppUseTimeData>> appUseTime = new MutableLiveData<>();
public final MutableLiveData<List<AppControlDetail>> mAppInfosLiveData = new MutableLiveData<>();
public final MutableLiveData<Boolean> loading = new MutableLiveData<>();
public final MutableLiveData<Throwable> error = new MutableLiveData<>();
/** 请求异常(一次性事件,避免页面重建后重复提示) */
public final SingleLiveEvent<Throwable> error = new SingleLiveEvent<>();
/** 最近一次整页同步成功的时间戳,0 表示暂无记录 */
public final MutableLiveData<Long> lastSyncTime = new MutableLiveData<>();
/**
* 整页刷新。
*
* @param queryType 应用使用时长查询类型:1 今天、2 本周、3 本月
* @param isAll 0 只取使用时长最高的 6 条,1 取全部
*/
public void loadAll(int queryType, int isAll) {
beginSyncCycle();
refreshLastSyncTime();
loadSettingData();
loadAppUseTime(queryType, isAll);
}
/** 开启新一轮同步:登记一定会发出的两个请求 */
private void beginSyncCycle() {
mPendingRequests.clear();
mSuccessCount = 0;
mPendingRequests.add(REQ_SETTING);
mPendingRequests.add(REQ_USE_TIME);
mTotalRequests = mPendingRequests.size();
}
/**
* 登记一个本轮刷新中的请求;重复登记不会重复计数。
*/
private void registerRequest(String tag) {
if (mPendingRequests.add(tag)) {
mTotalRequests++;
}
}
/**
* 统计本轮刷新内各请求的完成情况。
*
* <p>只有全部已登记的请求都返回且全部成功时,才把当前时间戳写入 MMKV 作为同步时间。
* 未登记的请求(Tab 切换、fetchData 单独触发)不参与统计。
*/
private void onRequestFinished(String tag, boolean success) {
if (!mPendingRequests.remove(tag)) {
return;
}
if (success) {
mSuccessCount++;
}
if (!mPendingRequests.isEmpty()) {
return;
}
if (mSuccessCount >= mTotalRequests) {
mMMKV.encode(CommonConfig.LAST_SYNC_TIME_KEY, System.currentTimeMillis());
refreshLastSyncTime();
}
mSuccessCount = 0;
}
/** 读取本地缓存的同步时间戳(0 表示暂无),供视图层格式化展示 */
public void refreshLastSyncTime() {
lastSyncTime.setValue(mMMKV.decodeLong(CommonConfig.LAST_SYNC_TIME_KEY, 0));
}
public void loadSettingData() {
Disposable disposable = mRepository.getSetting()
.subscribe(new Consumer<BaseResponse<SystemSettingsSet>>() {
@Override
public void accept(BaseResponse<SystemSettingsSet> resp) throws Throwable {
Log.e("UsageViewModel", "loadSettingData: " + resp);
Log.e(TAG, "loadSettingData: " + resp);
settingData.setValue(resp);
loading.setValue(false);
if (resp.code == 200 && resp.data != null) {
Toaster.show("刷新成功");
boolean success = resp.code == 200 && resp.data != null && resp.data.getUser() != null;
onRequestFinished(REQ_SETTING, success);
if (!success) {
return;
}
setSuccess("刷新成功");
// 管控场景下额外拉取三项数据,登记后一并计入本轮同步统计
if (resp.data.getUser().getIs_control() == 1) {
registerRequest(REQ_CONTROL_STATUS);
registerRequest(REQ_REMAINING_TIME);
registerRequest(REQ_APP_CONTROL_DETAIL);
loadControlCombined();
loadAppControlDetail();
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable err) throws Throwable {
Log.e(TAG, "loadSettingData 失败: " + err.getMessage());
onRequestFinished(REQ_SETTING, false);
error.setValue(err);
loading.setValue(false);
Toaster.show("网络错误");
}
});
mDisposables.add(disposable);
}
public void loadControlStatus() {
loading.setValue(true);
Disposable disposable = mRepository.getControlStatus()
.subscribe(
resp -> {
Log.e("UsageViewModel", "loadControlStatus: " + resp);
Log.e(TAG, "loadControlStatus: " + resp);
controlStatus.setValue(resp);
loading.setValue(false);
},
@@ -91,7 +188,7 @@ public class UsageViewModel extends BaseViewModel {
Disposable disposable = mRepository.getRemainingTime()
.subscribe(
resp -> {
Log.e("UsageViewModel", "loadRemainingTime: " + resp);
Log.e(TAG, "loadRemainingTime: " + resp);
remainingTime.setValue(resp);
loading.setValue(false);
},
@@ -106,23 +203,27 @@ public class UsageViewModel extends BaseViewModel {
/**
* 同时请求管控状态与剩余时长,两路每各发出一条结果时组合回调。
* 两路均有磁盘缓存时,可先回调缓存组合,再回调网络组合。
* Fragment 只需观察 controlCombined,即可根据两个值联动判断。
*/
public void loadControlCombined() {
loading.setValue(true);
Disposable disposable = mRepository.getControlStatusCombined()
.subscribe(
combined -> {
Log.e("UsageViewModel", "loadControlCombined: " + combined);
Log.e(TAG, "loadControlCombined: " + combined);
// 保留原有独立 LiveData,兼容仍单独观察的地方
controlStatus.setValue(combined.controlStatus);
remainingTime.setValue(combined.remainingTime);
controlCombined.setValue(combined);
loading.setValue(false);
onRequestFinished(REQ_CONTROL_STATUS, combined.controlStatus != null);
onRequestFinished(REQ_REMAINING_TIME, combined.remainingTime != null);
},
err -> {
Log.e(TAG, "loadControlCombined 失败: " + err.getMessage());
error.setValue(err);
loading.setValue(false);
onRequestFinished(REQ_CONTROL_STATUS, false);
onRequestFinished(REQ_REMAINING_TIME, false);
}
);
mDisposables.add(disposable);
@@ -142,10 +243,14 @@ public class UsageViewModel extends BaseViewModel {
resp -> {
appUseTime.setValue(resp);
loading.setValue(false);
boolean success = resp.code == 200 && resp.data != null
&& !resp.data.getApp_list().isEmpty();
onRequestFinished(REQ_USE_TIME, success);
},
err -> {
error.setValue(err);
loading.setValue(false);
onRequestFinished(REQ_USE_TIME, false);
}
);
mDisposables.add(disposable);
@@ -156,6 +261,7 @@ public class UsageViewModel extends BaseViewModel {
.subscribe(
resp -> {
mAppInfosLiveData.setValue(resp);
onRequestFinished(REQ_APP_CONTROL_DETAIL, resp != null);
// loading.setValue(false);
},
err -> {
@@ -164,6 +270,7 @@ public class UsageViewModel extends BaseViewModel {
} else {
error.setValue(err);
}
onRequestFinished(REQ_APP_CONTROL_DETAIL, false);
}
);
mDisposables.add(disposable);
@@ -53,6 +53,11 @@ public class UsageDetailActivity extends BaseMvvmActivity<UsageDetailViewModel,
return R.layout.activity_usage_detail;
}
@Override
protected Class<UsageDetailViewModel> getViewModelClass() {
return UsageDetailViewModel.class;
}
@Override
protected void initDataBinding() {
mContext = this;