diff --git a/app/src/main/java/com/fuying/sn/core/base/BaseDialogFragment.java b/app/src/main/java/com/fuying/sn/core/base/BaseDialogFragment.java
index 59cf8a6..244f25d 100644
--- a/app/src/main/java/com/fuying/sn/core/base/BaseDialogFragment.java
+++ b/app/src/main/java/com/fuying/sn/core/base/BaseDialogFragment.java
@@ -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} 一致的懒加载入口。
+ *
+ *
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;
}
-
}
diff --git a/app/src/main/java/com/fuying/sn/core/base/BaseFragment.java b/app/src/main/java/com/fuying/sn/core/base/BaseFragment.java
index a47c5d0..bd815d8 100644
--- a/app/src/main/java/com/fuying/sn/core/base/BaseFragment.java
+++ b/app/src/main/java/com/fuying/sn/core/base/BaseFragment.java
@@ -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 基类,提供标准的懒加载框架
- *
- * 兼容两种宿主场景:
- * 1. ViewPager(v1) + FragmentPagerAdapter:通过 {@link #setUserVisibleHint} 判断可见性(老接口,deprecated)
- * 2. ViewPager2 / FragmentTransaction.setMaxLifecycle:通过 onResume/onPause 判断可见性
- *
- * 懒加载核心思路:
- * 1. 视图创建完成({@code isViewInitiated}) + 当前页可见({@code isVisibleToUser}) 两个条件同时满足时,
- * 才触发首次加载({@link #onLazyLoad()}),之后切回该页不再重复触发。
+ *
+ *
可见性由两个条件共同决定:
+ * 1. 宿主告知"当前是否为选中页"({@link #setPageSelected(boolean)});
+ * 2. 自身生命周期已进入 onResume。
+ *
+ *
这样既覆盖 ViewPager 场景,又不再依赖已废弃的
+ * {@code setUserVisibleHint()}(该方法在 ViewPager 之外根本不会被调用,
+ * 且与 setMaxLifecycle 等新机制冲突)。
+ *
+ *
懒加载核心思路:
+ * 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 场景下,通过此回调精确判断当前页是否可见
+ * 宿主页面切换时通知本页是否被选中。
+ *
+ *
替代已废弃的 {@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) {
}
/**
diff --git a/app/src/main/java/com/fuying/sn/core/base/mvvm/BaseAndroidViewModel.java b/app/src/main/java/com/fuying/sn/core/base/mvvm/BaseAndroidViewModel.java
index a173cec..1342d41 100644
--- a/app/src/main/java/com/fuying/sn/core/base/mvvm/BaseAndroidViewModel.java
+++ b/app/src/main/java/com/fuying/sn/core/base/mvvm/BaseAndroidViewModel.java
@@ -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 mLoadingLiveData = new MutableLiveData<>(false);
-
- /** 全局错误提示 */
- private final MutableLiveData mErrorLiveData = new MutableLiveData<>();
-
- /** 全局成功提示 */
- private final MutableLiveData 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 getLoadingLiveData() {
- return mLoadingLiveData;
+ return mUiState.getLoadingLiveData();
}
+ @Override
public LiveData getErrorLiveData() {
- return mErrorLiveData;
+ return mUiState.getErrorLiveData();
}
+ @Override
public LiveData 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();
}
}
diff --git a/app/src/main/java/com/fuying/sn/core/base/mvvm/BaseMvvmActivity.java b/app/src/main/java/com/fuying/sn/core/base/mvvm/BaseMvvmActivity.java
index 729b6f1..da97b9c 100644
--- a/app/src/main/java/com/fuying/sn/core/base/mvvm/BaseMvvmActivity.java
+++ b/app/src/main/java/com/fuying/sn/core/base/mvvm/BaseMvvmActivity.java
@@ -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 extends BaseTransparentActivity {
- private static final String TAG = BaseMvvmActivity.class.getSimpleName();
-
protected VM mViewModel;
protected VDB mViewDataBinding;
- protected Class vmClass;
// ============================================================
// 生命周期
@@ -84,15 +77,17 @@ public abstract class BaseMvvmActivity历史上这里通过解析泛型参数反射创建 ViewModel,反射失败时只能得到 null 且难以排查;
+ * 改为子类显式返回具体 Class,编译期即可发现遗漏。
+ */
+ protected abstract Class getViewModelClass();
+
+ /** 创建 ViewModel 实例(默认按 {@link #getViewModelClass()} 创建,子类可按需重写) */
protected VM createViewModel() {
- vmClass = (Class) ((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 mLoadingLiveData = new MutableLiveData<>(false);
-
- /** 全局错误提示 */
- private final MutableLiveData mErrorLiveData = new MutableLiveData<>();
-
- /** 全局成功提示 */
- private final MutableLiveData 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 getLoadingLiveData() {
- return mLoadingLiveData;
+ return mUiState.getLoadingLiveData();
}
+ @Override
public LiveData getErrorLiveData() {
- return mErrorLiveData;
+ return mUiState.getErrorLiveData();
}
+ @Override
public LiveData 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();
}
}
diff --git a/app/src/main/java/com/fuying/sn/core/base/mvvm/IMvvmUiState.java b/app/src/main/java/com/fuying/sn/core/base/mvvm/IMvvmUiState.java
index a3adc7c..ad01389 100644
--- a/app/src/main/java/com/fuying/sn/core/base/mvvm/IMvvmUiState.java
+++ b/app/src/main/java/com/fuying/sn/core/base/mvvm/IMvvmUiState.java
@@ -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 getLoadingLiveData();
- /** 全局错误提示(只读) */
+ /** 全局错误提示(只读,一次性事件) */
LiveData getErrorLiveData();
- /** 全局成功提示(只读) */
+ /** 全局成功提示(只读,一次性事件) */
LiveData getSuccessLiveData();
}
diff --git a/app/src/main/java/com/fuying/sn/core/base/mvvm/MvvmUiStateDelegate.java b/app/src/main/java/com/fuying/sn/core/base/mvvm/MvvmUiStateDelegate.java
new file mode 100644
index 0000000..ade5af5
--- /dev/null
+++ b/app/src/main/java/com/fuying/sn/core/base/mvvm/MvvmUiStateDelegate.java
@@ -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 通用状态的共享实现。
+ *
+ * {@link BaseViewModel} 与 {@link BaseAndroidViewModel} 只差一个父类(ViewModel /
+ * AndroidViewModel),Java 单继承无法再抽公共父类,因此把 loading / error / success 状态
+ * 与 RxJava 订阅管理抽到本类,两个基类通过组合复用,避免两份完全相同的实现各自维护。
+ *
+ *
error / success 使用 {@link SingleLiveEvent}:它们表达的是"提示一次"的动作,
+ * 不能因为页面重建而被重复消费。
+ */
+final class MvvmUiStateDelegate implements IMvvmUiState {
+
+ /** 全局加载状态(状态型,重建后需要恢复,所以用普通 LiveData) */
+ private final MutableLiveData mLoadingLiveData = new MutableLiveData<>(false);
+
+ /** 全局错误提示(一次性事件) */
+ private final SingleLiveEvent mErrorLiveData = new SingleLiveEvent<>();
+
+ /** 全局成功提示(一次性事件) */
+ private final SingleLiveEvent mSuccessLiveData = new SingleLiveEvent<>();
+
+ private final CompositeDisposable mDisposables = new CompositeDisposable();
+
+ @Override
+ public LiveData getLoadingLiveData() {
+ return mLoadingLiveData;
+ }
+
+ @Override
+ public LiveData getErrorLiveData() {
+ return mErrorLiveData;
+ }
+
+ @Override
+ public LiveData 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();
+ }
+ }
+}
diff --git a/app/src/main/java/com/fuying/sn/core/base/mvvm/SingleLiveEvent.java b/app/src/main/java/com/fuying/sn/core/base/mvvm/SingleLiveEvent.java
new file mode 100644
index 0000000..6157a27
--- /dev/null
+++ b/app/src/main/java/com/fuying/sn/core/base/mvvm/SingleLiveEvent.java
@@ -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。
+ *
+ * 普通 LiveData 是"状态",新订阅者(如屏幕旋转后重建的页面)会立刻再收到最后一次值,
+ * 导致 Toast、跳转、弹窗这类"动作"被重复执行。本类只把值投递给第一个消费它的观察者,
+ * 之后的重新订阅不会再收到旧事件。
+ *
+ *
注意:仅适用于单观察者场景(本项目的 Activity / Fragment 各自持有自己的 ViewModel),
+ * 多观察者同时订阅时只有一个能收到事件。
+ *
+ * @param 事件数据类型
+ */
+public class SingleLiveEvent extends MutableLiveData {
+
+ /** 是否有未消费的事件 */
+ 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);
+ }
+}
diff --git a/app/src/main/java/com/fuying/sn/core/base/mvvm/fragment/BaseMvvmDialogFragment.java b/app/src/main/java/com/fuying/sn/core/base/mvvm/fragment/BaseMvvmDialogFragment.java
deleted file mode 100644
index 10db1a2..0000000
--- a/app/src/main/java/com/fuying/sn/core/base/mvvm/fragment/BaseMvvmDialogFragment.java
+++ /dev/null
@@ -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 ViewModel 类型,必须继承 {@link BaseViewModel} 或 {@link BaseAndroidViewModel}
- * @param ViewDataBinding 类型
- */
-public abstract class BaseMvvmDialogFragment extends BaseDialogFragment {
-
- protected final String mTag = this.getClass().getSimpleName();
-
- protected boolean mIsVisible;
- protected boolean mHasPrepare;
-
- protected VM mViewModel;
- protected VDB mViewDataBinding;
-
- private WeakReference 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 vmClass = (Class) ((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();
- }
-}
diff --git a/app/src/main/java/com/fuying/sn/core/base/mvvm/fragment/BaseMvvmFragment.java b/app/src/main/java/com/fuying/sn/core/base/mvvm/fragment/BaseMvvmFragment.java
index 8bb974e..5c7d1fb 100644
--- a/app/src/main/java/com/fuying/sn/core/base/mvvm/fragment/BaseMvvmFragment.java
+++ b/app/src/main/java/com/fuying/sn/core/base/mvvm/fragment/BaseMvvmFragment.java
@@ -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 基类
*
* 职责:
* - 绑定 DataBinding
- * - 初始化 ViewModel(默认通过反射自动创建)
+ * - 初始化 ViewModel(子类通过 {@link #getViewModelClass()} 显式声明,不使用反射)
* - 订阅 ViewModel 中的 LiveData({@link #observeViewModel()})
* - 订阅全局通用状态({@link #observeCommonState()})
* - 页面创建完成后加载数据({@link #onLoadData()})
* - 支持懒加载({@link #onEnter()} / {@link #onExit()})
* - 将用户操作转发给 ViewModel
*
+ * 可见性由 {@link BaseFragment} 统一计算(宿主选中 + 已 resume),
+ * 本类只把可见性变化转成 {@link #onEnter()} / {@link #onExit()} 回调。
+ *
* 禁止:
* - 在 Fragment 中直接进行网络请求或数据库操作(必须通过 ViewModel → Repository)
* - 持有可变 LiveData 的引用(应通过 LiveData 回调观察)
* - 在 Fragment 中写业务逻辑
* - 使用 getActivity() 强转后直接操作 Activity(应通过 ViewModel 通信)
*
- * @param ViewModel 类型,必须继承 {@link BaseViewModel} 或 {@link BaseAndroidViewModel}
+ * @param ViewModel 类型,必须继承 {@link com.fuying.sn.core.base.mvvm.BaseViewModel}
+ * 或 {@link com.fuying.sn.core.base.mvvm.BaseAndroidViewModel}
* @param ViewDataBinding 类型
*/
public abstract class BaseMvvmFragment 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改为显式声明后不再解析泛型反射创建,编译期即可发现遗漏。
+ */
+ protected abstract Class getViewModelClass();
+
+ /**
+ * 创建 ViewModel 实例(默认按 {@link #getViewModelClass()} 创建,子类可按需重写)
*/
protected VM createViewModel() {
- Class vmClass = (Class) ((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 getViewModelClass() {
+ return DeviceViewModel.class;
+ }
+
@Override
protected int getLayoutId() {
return R.layout.fragment_device;
@@ -121,19 +125,19 @@ public class DeviceFragment extends BaseMvvmFragment() {
+ @Override
+ public void onChanged(AppInfo appInfo) {
+ Intent intent = new Intent(mContext, UpdateActivity.class);
+ intent.putExtra("appInfo", appInfo);
+ startActivity(intent);
+ }
+ });
mViewModel.checkUpdate(false);
}
diff --git a/app/src/main/java/com/fuying/sn/feature/device/DeviceViewModel.java b/app/src/main/java/com/fuying/sn/feature/device/DeviceViewModel.java
index 742f896..6b6d727 100644
--- a/app/src/main/java/com/fuying/sn/feature/device/DeviceViewModel.java
+++ b/app/src/main/java/com/fuying/sn/feature/device/DeviceViewModel.java
@@ -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。
+ *
+ * 升级判断(本地版本与服务端版本比较)属于业务逻辑,放在这里完成;
+ * 视图层只负责展示版本号与跳转,不再自行比较版本。
+ * 需要 PackageManager 比较版本号,因此继承 {@link BaseAndroidViewModel} 获取 Application Context。
+ */
+public class DeviceViewModel extends BaseAndroidViewModel {
+
+ private static final String TAG = "DeviceViewModel";
+
private final DeviceRepository mRepository = DeviceRepository.getInstance();
- public MutableLiveData mSnInfoMutableLiveData = new MutableLiveData<>();
+ public DeviceViewModel(Application application) {
+ super(application);
+ }
+
+ public final MutableLiveData mSnInfoMutableLiveData = new MutableLiveData<>();
+
+ /** 检测到可升级版本(一次性事件,视图层收到后跳转更新页) */
+ public final SingleLiveEvent updateAvailable = new SingleLiveEvent<>();
+
+ public final MutableLiveData mDeviceInfoMutableLiveData = new MutableLiveData<>();
+
+ public final MutableLiveData mAppInfoMutableLiveData = new MutableLiveData<>();
public void getSnInfo() {
Disposable disposable = mRepository.getSnInfoControl()
.subscribeWith(new DisposableObserver>() {
@Override
public void onNext(@NonNull BaseResponse 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 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 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>() {
@Override
public void onNext(@NonNull BaseResponse 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);
diff --git a/app/src/main/java/com/fuying/sn/feature/home/HomeActivity.java b/app/src/main/java/com/fuying/sn/feature/home/HomeActivity.java
index 866e0e5..e3633c4 100644
--- a/app/src/main/java/com/fuying/sn/feature/home/HomeActivity.java
+++ b/app/src/main/java/com/fuying/sn/feature/home/HomeActivity.java
@@ -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 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 getViewModelClass() {
+ return HomeViewModel.class;
+ }
+
@Override
protected void initDataBinding() {
mViewDataBinding.setClick(new BtnClick());
@@ -82,9 +87,34 @@ public class HomeActivity extends BaseMvvmActivity原先各 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
diff --git a/app/src/main/java/com/fuying/sn/feature/main/MainActivity.java b/app/src/main/java/com/fuying/sn/feature/main/MainActivity.java
index c415621..57d409b 100644
--- a/app/src/main/java/com/fuying/sn/feature/main/MainActivity.java
+++ b/app/src/main/java/com/fuying/sn/feature/main/MainActivity.java
@@ -88,6 +88,11 @@ public class MainActivity extends BaseMvvmActivity getViewModelClass() {
+ return MainViewModel.class;
+ }
+
@Override
protected void initDataBinding() {
mViewDataBinding.setClick(new BtnClick());
diff --git a/app/src/main/java/com/fuying/sn/feature/update/UpdateActivity.java b/app/src/main/java/com/fuying/sn/feature/update/UpdateActivity.java
index c134837..f2f7e79 100644
--- a/app/src/main/java/com/fuying/sn/feature/update/UpdateActivity.java
+++ b/app/src/main/java/com/fuying/sn/feature/update/UpdateActivity.java
@@ -25,6 +25,11 @@ public class UpdateActivity extends BaseMvvmActivity getViewModelClass() {
+ return UpdateViewModel.class;
+ }
+
@Override
protected void initDataBinding() {
mViewDataBinding.setClick(new BtnClick());
diff --git a/app/src/main/java/com/fuying/sn/feature/usage/UsageFragment.java b/app/src/main/java/com/fuying/sn/feature/usage/UsageFragment.java
index 4c68356..66a08ec 100644
--- a/app/src/main/java/com/fuying/sn/feature/usage/UsageFragment.java
+++ b/app/src/main/java/com/fuying/sn/feature/usage/UsageFragment.java
@@ -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 {
private static final String TAG = "UsageFragment";
@@ -75,20 +73,10 @@ public class UsageFragment extends BaseMvvmFragment mPendingRequests = new HashSet<>();
- // 本次 loadData 周期登记的总请求数(含根据 onSettingData 动态补充的请求),
- // 用于判断整体是否全部成功
- private int mTotalRequests = 0;
- private int mSuccessCount = 0;
+ @Override
+ protected Class getViewModelClass() {
+ return UsageViewModel.class;
+ }
@Override
protected int getLayoutId() {
@@ -115,7 +103,6 @@ public class UsageFragment extends BaseMvvmFragment= 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 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 details) {
- onRequestFinished(REQ_APP_CONTROL_DETAIL, details != null);
mAppControlDetailAdapter.setAppTimeControlInfos(details);
}
@@ -438,7 +372,6 @@ public class UsageFragment extends BaseMvvmFragment 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();
diff --git a/app/src/main/java/com/fuying/sn/feature/usage/UsageViewModel.java b/app/src/main/java/com/fuying/sn/feature/usage/UsageViewModel.java
index 2d566f5..ea13ac4 100644
--- a/app/src/main/java/com/fuying/sn/feature/usage/UsageViewModel.java
+++ b/app/src/main/java/com/fuying/sn/feature/usage/UsageViewModel.java
@@ -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。
*
- * 职责:持有 UI 状态(LiveData)、调用 StatisticsRepository 获取数据,
- * 网络与 IO 由 Repository 负责。
- * 由基类使用 CompositeDisposable 管理订阅,在 onCleared 时释放。
+ * 职责:持有 UI 状态(LiveData)、编排整页请求、统计本轮同步是否全部成功并落盘同步时间。
+ * 视图层只负责把数据渲染到控件,不再维护请求登记与计数。
+ *
+ * 提示信息通过 {@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 mPendingRequests = new HashSet<>();
+ private int mTotalRequests = 0;
+ private int mSuccessCount = 0;
// ===== UI 状态(对外暴露 LiveData,类型与 Repository 返回类型一致)=====
public final MutableLiveData> settingData = new MutableLiveData<>();
@@ -43,39 +65,114 @@ public class UsageViewModel extends BaseViewModel {
public final MutableLiveData> appUseTime = new MutableLiveData<>();
public final MutableLiveData> mAppInfosLiveData = new MutableLiveData<>();
public final MutableLiveData loading = new MutableLiveData<>();
- public final MutableLiveData error = new MutableLiveData<>();
+
+ /** 请求异常(一次性事件,避免页面重建后重复提示) */
+ public final SingleLiveEvent error = new SingleLiveEvent<>();
+
+ /** 最近一次整页同步成功的时间戳,0 表示暂无记录 */
+ public final MutableLiveData 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++;
+ }
+ }
+
+ /**
+ * 统计本轮刷新内各请求的完成情况。
+ *
+ * 只有全部已登记的请求都返回且全部成功时,才把当前时间戳写入 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>() {
@Override
public void accept(BaseResponse 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() {
@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);
diff --git a/app/src/main/java/com/fuying/sn/feature/usage/detail/UsageDetailActivity.java b/app/src/main/java/com/fuying/sn/feature/usage/detail/UsageDetailActivity.java
index d555584..7106514 100644
--- a/app/src/main/java/com/fuying/sn/feature/usage/detail/UsageDetailActivity.java
+++ b/app/src/main/java/com/fuying/sn/feature/usage/detail/UsageDetailActivity.java
@@ -53,6 +53,11 @@ public class UsageDetailActivity extends BaseMvvmActivity getViewModelClass() {
+ return UsageDetailViewModel.class;
+ }
+
@Override
protected void initDataBinding() {
mContext = this;