feat(album): 新增家人相册功能
- 新增 FamilyAlbumActivity 及 ViewModel,支持照片浏览、收藏筛选与删除操作 - 重构 MQTT 重连策略,使用自定义指数退避替代 HiveMQ 内置自动重连,避免重复连接 - 新增 WallpaperThemeManager 与 WallpaperTextView,根据壁纸明暗自动适配文字颜色 - 添加 SnApi 家人相册相关接口(获取列表、设置收藏、删除照片) - 在设置页添加家人相册入口按钮 - 新增 MqttReconnectPolicy 单元测试覆盖退避与重置
This commit is contained in:
1 parent
251bc15fd2
commit
9b427e1149
16 files changed
+638
-64
No files matched your search
@@ -144,6 +144,10 @@
|
||||
android:launchMode="singleInstance"
|
||||
android:showOnLockScreen="true"
|
||||
android:turnScreenOn="true" />
|
||||
<activity
|
||||
android:name=".activity.album.FamilyAlbumActivity"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- 设备未绑定提示(对话框样式 Activity) -->
|
||||
<activity
|
||||
android:name=".activity.bind.BindRequiredActivity"
|
||||
@@ -159,8 +163,8 @@
|
||||
<activity
|
||||
android:name=".activity.alarm.add.AlarmAddActivity"
|
||||
android:launchMode="singleTask"
|
||||
android:theme="@style/MaterialTheme"
|
||||
android:screenOrientation="portrait" />
|
||||
android:screenOrientation="portrait"
|
||||
android:theme="@style/MaterialTheme" />
|
||||
<activity
|
||||
android:name=".activity.alarm.edit.AlarmEditActivity"
|
||||
android:launchMode="singleTask"
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.ttstd.dialer.activity.album;
|
||||
import android.app.Dialog;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.*;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.recyclerview.widget.GridLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import com.bumptech.glide.Glide;
|
||||
import com.ttstd.dialer.R;
|
||||
import com.ttstd.dialer.base.mvvm.BaseMvvmActivity;
|
||||
import com.ttstd.dialer.bean.FamilyPicture;
|
||||
import com.ttstd.dialer.databinding.ActivityFamilyAlbumBinding;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
public class FamilyAlbumActivity extends BaseMvvmActivity<FamilyAlbumViewModel,ActivityFamilyAlbumBinding>{
|
||||
private final PhotosAdapter adapter=new PhotosAdapter();
|
||||
private boolean busy;
|
||||
public boolean setfitWindow(){return true;}
|
||||
public boolean setNightMode(){return true;}
|
||||
protected int getLayoutId(){return R.layout.activity_family_album;}
|
||||
protected void initDataBinding(){}
|
||||
protected void initView(){
|
||||
mViewDataBinding.photos.setLayoutManager(new GridLayoutManager(this,2));mViewDataBinding.photos.setAdapter(adapter);
|
||||
mViewDataBinding.back.setOnClickListener(v->finish());mViewDataBinding.refresh.setOnClickListener(v->mViewModel.load());
|
||||
mViewDataBinding.filter.setOnCheckedChangeListener((group,id)->mViewModel.filter(id==R.id.favorites));
|
||||
}
|
||||
protected void observeViewModel(){
|
||||
mViewModel.photos().observe(this,items->{adapter.items=items;adapter.notifyDataSetChanged();mViewDataBinding.empty.setVisibility(items.isEmpty()?View.VISIBLE:View.GONE);});
|
||||
mViewModel.busy().observe(this,value->{busy=Boolean.TRUE.equals(value);mViewDataBinding.progress.setVisibility(busy?View.VISIBLE:View.GONE);mViewDataBinding.refresh.setEnabled(!busy);adapter.notifyDataSetChanged();});
|
||||
}
|
||||
protected void onResume(){super.onResume();mViewModel.load();}
|
||||
private void preview(FamilyPicture picture){
|
||||
Dialog dialog=new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
|
||||
LinearLayout panel=new LinearLayout(this);panel.setOrientation(LinearLayout.VERTICAL);
|
||||
ImageView image=new ImageView(this);image.setScaleType(ImageView.ScaleType.FIT_CENTER);panel.addView(image,new LinearLayout.LayoutParams(-1,0,1));
|
||||
Button close=new Button(this);close.setText("关闭");close.setOnClickListener(v->dialog.dismiss());panel.addView(close,new LinearLayout.LayoutParams(-1,-2));
|
||||
dialog.setContentView(panel);Glide.with(this).load(picture.getDisplayUrl()).error(android.R.drawable.ic_menu_report_image).into(image);dialog.setOnDismissListener(d->Glide.with(getApplicationContext()).clear(image));dialog.show();
|
||||
}
|
||||
private class PhotosAdapter extends RecyclerView.Adapter<PhotoHolder>{
|
||||
List<FamilyPicture> items=new ArrayList<>();
|
||||
public PhotoHolder onCreateViewHolder(ViewGroup parent,int type){
|
||||
LinearLayout card=new LinearLayout(parent.getContext());card.setOrientation(LinearLayout.VERTICAL);int pad=(int)(8*getResources().getDisplayMetrics().density);card.setPadding(pad,pad,pad,pad);card.setBackgroundColor(ContextCompat.getColor(FamilyAlbumActivity.this,R.color.card_background_color));
|
||||
card.setLayoutParams(new RecyclerView.LayoutParams(-1,-2));ImageView image=new ImageView(parent.getContext());image.setContentDescription("相册照片,点击查看大图");card.addView(image,new LinearLayout.LayoutParams(-1,(int)(180*getResources().getDisplayMetrics().density)));
|
||||
Button favorite=new Button(parent.getContext());card.addView(favorite,new LinearLayout.LayoutParams(-1,-2));Button delete=new Button(parent.getContext());delete.setText("删除");card.addView(delete,new LinearLayout.LayoutParams(-1,-2));return new PhotoHolder(card,image,favorite,delete);
|
||||
}
|
||||
public void onBindViewHolder(PhotoHolder h,int pos){FamilyPicture p=items.get(pos);Glide.with(h.image).load(p.getDisplayUrl()).placeholder(android.R.drawable.ic_menu_gallery).error(android.R.drawable.ic_menu_report_image).centerCrop().into(h.image);
|
||||
h.favorite.setText(p.isFavorite()?"★ 已收藏":"☆ 收藏");h.favorite.setEnabled(!busy);h.delete.setEnabled(!busy);
|
||||
h.favorite.setOnClickListener(v->mViewModel.favorite(p));h.image.setOnClickListener(v->preview(p));
|
||||
h.delete.setOnClickListener(v->new AlertDialog.Builder(FamilyAlbumActivity.this).setTitle("删除照片?").setMessage("删除后家属端相册也将不再显示这张照片。").setNegativeButton("取消",null).setPositiveButton("删除",(d,w)->mViewModel.delete(p)).show());
|
||||
}
|
||||
public int getItemCount(){return items.size();}
|
||||
public void onViewRecycled(PhotoHolder h){Glide.with(h.image).clear(h.image);super.onViewRecycled(h);}
|
||||
}
|
||||
private static class PhotoHolder extends RecyclerView.ViewHolder{
|
||||
final ImageView image;final Button favorite,delete;
|
||||
PhotoHolder(View root,ImageView image,Button favorite,Button delete){super(root);this.image=image;this.favorite=favorite;this.delete=delete;}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.ttstd.dialer.activity.album;
|
||||
import android.app.Application;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import com.ttstd.dialer.base.mvvm.BaseAndroidViewModel;
|
||||
import com.ttstd.dialer.bean.FamilyPicture;
|
||||
import com.ttstd.dialer.data.repository.SnRepository;
|
||||
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
public class FamilyAlbumViewModel extends BaseAndroidViewModel {
|
||||
private final SnRepository repository;
|
||||
private final MutableLiveData<List<FamilyPicture>> photos=new MutableLiveData<>(new ArrayList<>());
|
||||
private final MutableLiveData<Boolean> busy=new MutableLiveData<>(false);
|
||||
private List<FamilyPicture> all=new ArrayList<>();
|
||||
private boolean favoritesOnly;
|
||||
public FamilyAlbumViewModel(Application app){super(app);repository=SnRepository.getInstance(app);}
|
||||
public LiveData<List<FamilyPicture>> photos(){return photos;}
|
||||
public LiveData<Boolean> busy(){return busy;}
|
||||
public void filter(boolean favorites){favoritesOnly=favorites;publish();}
|
||||
private void publish(){List<FamilyPicture> result=new ArrayList<>();for(FamilyPicture p:all)if(!favoritesOnly||p.isFavorite())result.add(p);photos.setValue(result);}
|
||||
public void load(){if(Boolean.TRUE.equals(busy.getValue()))return;busy.setValue(true);
|
||||
addDisposable(repository.getFamilyPictures().observeOn(AndroidSchedulers.mainThread()).subscribe(items->{all=new ArrayList<>(items);publish();busy.setValue(false);},e->failed()));}
|
||||
public void favorite(FamilyPicture picture){if(Boolean.TRUE.equals(busy.getValue()))return;busy.setValue(true);
|
||||
addDisposable(repository.setPictureFavorite(picture.getUrl(),!picture.isFavorite()).observeOn(AndroidSchedulers.mainThread()).subscribe(ok->{
|
||||
for(int i=0;i<all.size();i++)if(all.get(i).getUrl().equals(picture.getUrl()))all.set(i,picture.withFavorite(!picture.isFavorite()));publish();busy.setValue(false);
|
||||
},e->failed()));}
|
||||
public void delete(FamilyPicture picture){if(Boolean.TRUE.equals(busy.getValue()))return;busy.setValue(true);
|
||||
addDisposable(repository.deleteFamilyPicture(picture.getUrl()).observeOn(AndroidSchedulers.mainThread()).subscribe(ok->{all.removeIf(p->p.getUrl().equals(picture.getUrl()));publish();busy.setValue(false);},e->failed()));}
|
||||
private void failed(){busy.setValue(false);setError("操作失败,请检查网络后重试");}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ public class SettingsActivity extends BaseMvvmActivity<SettingsViewModel, Activi
|
||||
}
|
||||
|
||||
public class BtnClick {
|
||||
public void openFamilyAlbum(View view) { startActivity(new Intent(SettingsActivity.this, com.ttstd.dialer.activity.album.FamilyAlbumActivity.class)); }
|
||||
public void exit(View view) {
|
||||
finish();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.ttstd.dialer.bean;
|
||||
|
||||
import com.ttstd.dialer.network.UrlConstants;
|
||||
import java.net.URI;
|
||||
|
||||
public class FamilyPicture {
|
||||
private String url;
|
||||
private int favorite;
|
||||
private long fileSize;
|
||||
|
||||
public String getUrl() { return url; }
|
||||
public boolean isFavorite() { return favorite == 1; }
|
||||
public long getFileSize() { return fileSize; }
|
||||
|
||||
public String getDisplayUrl() {
|
||||
try {
|
||||
return URI.create(UrlConstants.SERVER_ORIGIN).resolve(url).toString();
|
||||
} catch (IllegalArgumentException | NullPointerException error) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public FamilyPicture withFavorite(boolean selected) {
|
||||
FamilyPicture result = new FamilyPicture();
|
||||
result.url = url;
|
||||
result.favorite = selected ? 1 : 0;
|
||||
result.fileSize = fileSize;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import androidx.annotation.NonNull;
|
||||
import com.ttstd.dialer.bean.BaseResponse;
|
||||
import com.ttstd.dialer.bean.DeveloperOptions;
|
||||
import com.ttstd.dialer.bean.WallpaperInfo;
|
||||
import com.ttstd.dialer.bean.FamilyPicture;
|
||||
import com.ttstd.dialer.bean.req.SnHardwareInfoReq;
|
||||
import com.ttstd.dialer.db.alarm.AlarmInfo;
|
||||
import com.ttstd.dialer.bean.req.SnLocationReq;
|
||||
@@ -161,4 +162,16 @@ public class SnRemoteDataSource {
|
||||
OkHttpManager.convertToRequestBody(appName == null ? "" : appName),
|
||||
part);
|
||||
}
|
||||
|
||||
public Observable<List<FamilyPicture>> getFamilyPictures() {
|
||||
return ApiResponseMapper.unwrap(mApi.getFamilyPictures());
|
||||
}
|
||||
|
||||
public Observable<Boolean> setPictureFavorite(String url, boolean favorite) {
|
||||
return ApiResponseMapper.unwrapAsSuccess(mApi.setPictureFavorite(url, favorite ? 1 : 0));
|
||||
}
|
||||
|
||||
public Observable<Boolean> deleteFamilyPicture(String url) {
|
||||
return ApiResponseMapper.unwrapAsSuccess(mApi.deleteFamilyPicture(url));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import androidx.annotation.NonNull;
|
||||
import com.ttstd.dialer.bean.BaseResponse;
|
||||
import com.ttstd.dialer.bean.DeveloperOptions;
|
||||
import com.ttstd.dialer.bean.WallpaperInfo;
|
||||
import com.ttstd.dialer.bean.FamilyPicture;
|
||||
import com.ttstd.dialer.bean.req.SnHardwareInfoReq;
|
||||
import com.ttstd.dialer.db.alarm.AlarmInfo;
|
||||
import com.ttstd.dialer.network.OkHttpManager;
|
||||
@@ -245,4 +246,16 @@ public class SnRepository {
|
||||
return mRemoteDataSource.uploadAppIcon(packageName, appName, part)
|
||||
.subscribeOn(Schedulers.io());
|
||||
}
|
||||
|
||||
public Observable<List<FamilyPicture>> getFamilyPictures() {
|
||||
return mRemoteDataSource.getFamilyPictures().subscribeOn(Schedulers.io());
|
||||
}
|
||||
|
||||
public Observable<Boolean> setPictureFavorite(String url, boolean favorite) {
|
||||
return mRemoteDataSource.setPictureFavorite(url, favorite).subscribeOn(Schedulers.io());
|
||||
}
|
||||
|
||||
public Observable<Boolean> deleteFamilyPicture(String url) {
|
||||
return mRemoteDataSource.deleteFamilyPicture(url).subscribeOn(Schedulers.io());
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
|
||||
@@ -13,6 +14,8 @@ import com.hivemq.client.mqtt.lifecycle.MqttClientConnectedContext;
|
||||
import com.hivemq.client.mqtt.lifecycle.MqttClientDisconnectedContext;
|
||||
import com.hivemq.client.mqtt.lifecycle.MqttDisconnectSource;
|
||||
import com.hivemq.client.mqtt.mqtt5.lifecycle.Mqtt5ClientConnectedContext;
|
||||
import com.hivemq.client.mqtt.mqtt5.exceptions.Mqtt5DisconnectException;
|
||||
import com.hivemq.client.mqtt.mqtt5.message.disconnect.Mqtt5Disconnect;
|
||||
import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAck;
|
||||
import com.jeremyliao.liveeventbus.LiveEventBus;
|
||||
import com.ttstd.dialer.bean.DeviceStatus;
|
||||
@@ -30,8 +33,11 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* MQTT 消息管理
|
||||
@@ -87,6 +93,12 @@ public class MqttManager {
|
||||
*/
|
||||
private volatile boolean mManualDisconnect;
|
||||
|
||||
private volatile long mClientGeneration;
|
||||
private final MqttReconnectPolicy mReconnectPolicy = new MqttReconnectPolicy();
|
||||
private final Handler mReconnectHandler = new Handler(Looper.getMainLooper());
|
||||
private Runnable mReconnectTask;
|
||||
private CompletableFuture<Boolean> mReconnectGate;
|
||||
|
||||
/**
|
||||
* 心跳定时器(主线程 Handler)
|
||||
*/
|
||||
@@ -146,7 +158,8 @@ public class MqttManager {
|
||||
/**
|
||||
* 建立 MQTT 连接(异步,断线后自动重连)
|
||||
*/
|
||||
public void connect() {
|
||||
public synchronized void connect() {
|
||||
final long generation;
|
||||
try {
|
||||
if (mMqttClient != null && mConnected) {
|
||||
return;
|
||||
@@ -159,13 +172,9 @@ public class MqttManager {
|
||||
// 主动发起连接,清除主动断开标记,允许后续自动重连
|
||||
mManualDisconnect = false;
|
||||
mConnecting = true;
|
||||
if (mMqttClient != null) {
|
||||
try {
|
||||
mMqttClient.disconnect();
|
||||
} catch (Throwable ignore) {
|
||||
}
|
||||
mMqttClient = null;
|
||||
}
|
||||
generation = ++mClientGeneration;
|
||||
// 每个生命周期只构建一个客户端;等待重连时 connect() 不得绕过退避。
|
||||
final AtomicReference<Mqtt5AsyncClient> clientRef = new AtomicReference<>();
|
||||
|
||||
URI uri = URI.create(MQTT_URL);
|
||||
String host = uri.getHost();
|
||||
@@ -175,10 +184,9 @@ public class MqttManager {
|
||||
.identifier(SystemUtils.getSerial())
|
||||
.serverHost(host)
|
||||
.serverPort(port)
|
||||
// HiveMQ 自带断线自动重连(内置指数退避),避免与自定义重连叠加导致重复连接
|
||||
.automaticReconnectWithDefaultConfig()
|
||||
.addDisconnectedListener(this::onDisconnected)
|
||||
.addConnectedListener(this::onConnected);
|
||||
// 使用一个可取消的等待门控制 HiveMQ 重连,保留跨短连接的退避状态。
|
||||
.addDisconnectedListener(context -> onDisconnected(context, generation))
|
||||
.addConnectedListener(context -> onConnected(context, generation, clientRef.get()));
|
||||
|
||||
builder.simpleAuth()
|
||||
.username(MQTT_USERNAME)
|
||||
@@ -186,7 +194,7 @@ public class MqttManager {
|
||||
.applySimpleAuth();
|
||||
|
||||
mMqttClient = builder.buildAsync();
|
||||
|
||||
clientRef.set(mMqttClient);
|
||||
mMqttClient.connectWith()
|
||||
.keepAlive(30)
|
||||
.cleanStart(false) // 复用历史会话
|
||||
@@ -199,35 +207,44 @@ public class MqttManager {
|
||||
.applyWillPublish()
|
||||
.send()
|
||||
.whenComplete((connAck, throwable) -> {
|
||||
// 首次 connect 异步结果返回,复位连接中标记
|
||||
mConnecting = false;
|
||||
if (throwable != null) {
|
||||
String msg = throwable.getMessage();
|
||||
Logger.e(TAG, "connect: 首次连接失败 " + msg
|
||||
+ ",HiveMQ 将自动重连 " + host + ":" + port);
|
||||
setConnected(false);
|
||||
} else {
|
||||
// 首次连接成功(后续重连成功会走 onConnected 回调)
|
||||
onConnected();
|
||||
synchronized (MqttManager.this) {
|
||||
if (generation != mClientGeneration || mManualDisconnect) {
|
||||
return;
|
||||
}
|
||||
if (throwable != null) {
|
||||
// 断线监听统一安排重试,此处不能清除 mConnecting 或重复发起连接。
|
||||
Logger.e(TAG, "connect: 首次连接失败 " + throwable.getMessage()
|
||||
+ ",等待退避重连 " + host + ":" + port);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (Throwable e) {
|
||||
mConnecting = false;
|
||||
mManualDisconnect = true;
|
||||
++mClientGeneration;
|
||||
cancelPendingReconnect();
|
||||
if (mMqttClient != null) {
|
||||
mMqttClient.disconnect();
|
||||
mMqttClient = null;
|
||||
}
|
||||
setConnected(false);
|
||||
Logger.e(TAG, "connect: 异常 " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接成功回调(首次 connect 异步结果返回时调用,无 context 信息)
|
||||
*/
|
||||
private void onConnected() {
|
||||
onConnected(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接成功回调(首次连接与 HiveMQ 自动重连成功都会触发)
|
||||
*/
|
||||
private void onConnected(MqttClientConnectedContext context) {
|
||||
/** 首次连接与重连成功只通过生命周期监听处理一次。 */
|
||||
private synchronized void onConnected(MqttClientConnectedContext context, long generation,
|
||||
Mqtt5AsyncClient client) {
|
||||
if (generation != mClientGeneration || mManualDisconnect) {
|
||||
// 已取消的旧客户端即使刚好连上,也不能恢复订阅、上报或覆盖新连接状态。
|
||||
if (client != null) {
|
||||
client.disconnect();
|
||||
}
|
||||
return;
|
||||
}
|
||||
mConnecting = false;
|
||||
mReconnectPolicy.onConnected(SystemClock.elapsedRealtime());
|
||||
boolean sessionPresent = false;
|
||||
if (context instanceof Mqtt5ClientConnectedContext) {
|
||||
Mqtt5ConnAck connAck = ((Mqtt5ClientConnectedContext) context).getConnAck();
|
||||
@@ -243,39 +260,71 @@ public class MqttManager {
|
||||
reportScreenStateOnConnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 断线回调:仅做状态清理与心跳停止,重连交由 HiveMQ 自动重连处理,
|
||||
* 不再自行调用 connect(),避免与 HiveMQ 的重连叠加导致重复连接。
|
||||
* 同时打印 Broker 返回的断开原因,便于定位反复断开的根因。
|
||||
*/
|
||||
private void onDisconnected(MqttClientDisconnectedContext context) {
|
||||
if (mManualDisconnect) {
|
||||
Logger.e(TAG, "onDisconnected: 主动断开,不重连");
|
||||
/** 在 HiveMQ 生命周期回调中注册重连,定时等待可被主动断开取消。 */
|
||||
private synchronized void onDisconnected(MqttClientDisconnectedContext context, long generation) {
|
||||
if (generation != mClientGeneration || mManualDisconnect
|
||||
|| context.getSource() == MqttDisconnectSource.USER) {
|
||||
context.getReconnector().reconnect(false);
|
||||
return;
|
||||
}
|
||||
// 解析断开来源与原因,区分"服务端踢"与"网络/客户端问题"
|
||||
String source = context.getSource() != null ? context.getSource().name() : "UNKNOWN";
|
||||
String cause = context.getCause() != null ? context.getCause().toString() : "null";
|
||||
if (context.getSource() == MqttDisconnectSource.SERVER) {
|
||||
// 服务端主动断开(如 clientId 冲突、鉴权失败、协议违规),reason code 有价值
|
||||
Logger.e(TAG, "onDisconnected: 服务端主动断开 source=" + source
|
||||
+ " cause=" + cause
|
||||
+ ",等待 HiveMQ 自动重连");
|
||||
} else {
|
||||
Logger.e(TAG, "onDisconnected: 连接断开 source=" + source
|
||||
+ " cause=" + cause
|
||||
+ ",等待 HiveMQ 自动重连");
|
||||
}
|
||||
setConnected(false);
|
||||
stopHeartbeat();
|
||||
mConnecting = true;
|
||||
cancelPendingReconnect();
|
||||
|
||||
long baseDelay = mReconnectPolicy.nextDelayMillis(SystemClock.elapsedRealtime(),
|
||||
context.getSource() == MqttDisconnectSource.SERVER);
|
||||
long delay = Math.min(MqttReconnectPolicy.MAX_DELAY_MS,
|
||||
baseDelay + ThreadLocalRandom.current().nextLong(baseDelay / 5 + 1));
|
||||
CompletableFuture<Boolean> gate = new CompletableFuture<>();
|
||||
mReconnectGate = gate;
|
||||
context.getReconnector().delay(0, TimeUnit.MILLISECONDS)
|
||||
.reconnectWhen(gate, (allowed, error) -> context.getReconnector().reconnect(
|
||||
Boolean.TRUE.equals(allowed) && !mManualDisconnect
|
||||
&& generation == mClientGeneration));
|
||||
mReconnectTask = () -> {
|
||||
synchronized (MqttManager.this) {
|
||||
gate.complete(!mManualDisconnect && generation == mClientGeneration);
|
||||
if (mReconnectGate == gate) {
|
||||
mReconnectGate = null;
|
||||
mReconnectTask = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
mReconnectHandler.postDelayed(mReconnectTask, delay);
|
||||
|
||||
Throwable cause = context.getCause();
|
||||
String reason = "";
|
||||
if (cause instanceof Mqtt5DisconnectException) {
|
||||
Mqtt5Disconnect message = ((Mqtt5DisconnectException) cause).getMqttMessage();
|
||||
reason = " reasonCode=" + message.getReasonCode()
|
||||
+ " reasonString=" + message.getReasonString().map(Object::toString).orElse("");
|
||||
}
|
||||
Logger.e(TAG, "onDisconnected: source=" + context.getSource() + reason
|
||||
+ " cause=" + cause + "," + delay + "ms 后重连");
|
||||
}
|
||||
|
||||
private void cancelPendingReconnect() {
|
||||
if (mReconnectTask != null) {
|
||||
mReconnectHandler.removeCallbacks(mReconnectTask);
|
||||
mReconnectTask = null;
|
||||
}
|
||||
if (mReconnectGate != null) {
|
||||
mReconnectGate.complete(false);
|
||||
mReconnectGate = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开 MQTT 连接(主动断开,先发离线消息再断连,不会触发遗言)
|
||||
*/
|
||||
public void disconnect() {
|
||||
public synchronized void disconnect() {
|
||||
// 标记主动断开,断线监听据此跳过重连
|
||||
mManualDisconnect = true;
|
||||
++mClientGeneration;
|
||||
mConnecting = false;
|
||||
cancelPendingReconnect();
|
||||
mReconnectPolicy.reset();
|
||||
stopHeartbeat();
|
||||
try {
|
||||
if (mMqttClient != null && mConnected) {
|
||||
@@ -285,6 +334,8 @@ public class MqttManager {
|
||||
String offlinePayload = GsonUtils.toJSONString(new DeviceStatus(sn, false, getLocalIpAddress(), SystemUtils.getCurrentNetworkRssi(mContext), false));
|
||||
publish(MQTT_TOPIC_STATUS, offlinePayload);
|
||||
}
|
||||
}
|
||||
if (mMqttClient != null) {
|
||||
mMqttClient.disconnect();
|
||||
mMqttClient = null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ttstd.dialer.manager;
|
||||
|
||||
/** 跨短连接保留退避状态;只在连接稳定后或主动断开时重置。由 MqttManager 锁保护。 */
|
||||
final class MqttReconnectPolicy {
|
||||
static final long MAX_DELAY_MS = 300_000L;
|
||||
static final long STABLE_CONNECTION_MS = 120_000L;
|
||||
private long connectedAt = -1L;
|
||||
private long previousDelay;
|
||||
|
||||
void onConnected(long now) {
|
||||
connectedAt = now;
|
||||
}
|
||||
|
||||
long nextDelayMillis(long now, boolean serverDisconnect) {
|
||||
if (connectedAt >= 0 && now - connectedAt >= STABLE_CONNECTION_MS) {
|
||||
previousDelay = 0;
|
||||
}
|
||||
connectedAt = -1L;
|
||||
long initialDelay = serverDisconnect ? 10_000L : 2_000L;
|
||||
previousDelay = Math.min(MAX_DELAY_MS, Math.max(initialDelay, previousDelay * 2));
|
||||
return previousDelay;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
connectedAt = -1L;
|
||||
previousDelay = 0;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.ttstd.dialer.network.api;
|
||||
import com.ttstd.dialer.bean.BaseResponse;
|
||||
import com.ttstd.dialer.bean.DeveloperOptions;
|
||||
import com.ttstd.dialer.bean.WallpaperInfo;
|
||||
import com.ttstd.dialer.bean.FamilyPicture;
|
||||
import com.ttstd.dialer.db.alarm.AlarmInfo;
|
||||
import com.ttstd.dialer.network.UrlConstants;
|
||||
|
||||
@@ -16,6 +17,8 @@ import retrofit2.http.Body;
|
||||
import retrofit2.http.Field;
|
||||
import retrofit2.http.FormUrlEncoded;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.DELETE;
|
||||
import retrofit2.http.Query;
|
||||
import retrofit2.http.Multipart;
|
||||
import retrofit2.http.POST;
|
||||
import retrofit2.http.Part;
|
||||
@@ -137,4 +140,14 @@ public interface SnApi {
|
||||
@Body RequestBody body
|
||||
);
|
||||
|
||||
|
||||
@GET("pictures")
|
||||
Observable<BaseResponse<List<FamilyPicture>>> getFamilyPictures();
|
||||
|
||||
@POST("pictures/favorite")
|
||||
Observable<BaseResponse<Void>> setPictureFavorite(
|
||||
@Query("url") String url, @Query("favorite") int favorite);
|
||||
|
||||
@DELETE("pictures")
|
||||
Observable<BaseResponse<Void>> deleteFamilyPicture(@Query("url") String url);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ttstd.dialer.wallpager;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.ContextWrapper;
|
||||
import android.app.Activity;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.WindowManager;
|
||||
|
||||
import androidx.appcompat.widget.AppCompatTextView;
|
||||
import androidx.lifecycle.Observer;
|
||||
|
||||
/** 用于直接覆盖在壁纸上的文字;附着/分离时自动订阅/取消,不影响卡片内的普通 TextView。 */
|
||||
public class WallpaperTextView extends AppCompatTextView {
|
||||
private final Observer<Boolean> observer = light -> applyWallpaperColor();
|
||||
private WallpaperThemeManager manager;
|
||||
|
||||
public WallpaperTextView(Context context) { this(context, null); }
|
||||
|
||||
public WallpaperTextView(Context context, AttributeSet attrs) {
|
||||
this(context, attrs, android.R.attr.textViewStyle);
|
||||
}
|
||||
|
||||
public WallpaperTextView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
@Override protected void onAttachedToWindow() {
|
||||
super.onAttachedToWindow();
|
||||
// 共享应用条目也用于普通列表页;仅在显示系统壁纸的窗口中启用。
|
||||
Context current = getContext();
|
||||
while (current instanceof ContextWrapper && !(current instanceof Activity)) {
|
||||
Context base = ((ContextWrapper) current).getBaseContext();
|
||||
if (base == current) break;
|
||||
current = base;
|
||||
}
|
||||
if (!(current instanceof Activity)
|
||||
|| ((((Activity) current).getWindow().getAttributes().flags
|
||||
& WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER) == 0)) return;
|
||||
manager = WallpaperThemeManager.getInstance(getContext());
|
||||
manager.observeForever(observer);
|
||||
}
|
||||
|
||||
@Override protected void onDetachedFromWindow() {
|
||||
if (manager != null) manager.removeObserver(observer);
|
||||
manager = null;
|
||||
super.onDetachedFromWindow();
|
||||
}
|
||||
|
||||
private void applyWallpaperColor() {
|
||||
if (manager != null) setTextColor(manager.getTextColor());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.ttstd.dialer.wallpager;
|
||||
|
||||
import android.app.WallpaperColors;
|
||||
import android.app.WallpaperManager;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.core.graphics.ColorUtils;
|
||||
import androidx.lifecycle.LiveData;
|
||||
|
||||
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
|
||||
import io.reactivex.rxjava3.core.Single;
|
||||
import io.reactivex.rxjava3.disposables.Disposable;
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers;
|
||||
|
||||
/** 全局壁纸明暗状态。仅持有 Application Context,有观察者时监听,最后一个观察者移除后释放。 */
|
||||
public final class WallpaperThemeManager extends LiveData<Boolean> {
|
||||
private static volatile WallpaperThemeManager instance;
|
||||
private final Context context;
|
||||
private final WallpaperManager wallpaperManager;
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
private Disposable pending;
|
||||
private Runnable removeColorsListener;
|
||||
private int generation;
|
||||
private final BroadcastReceiver receiver = new BroadcastReceiver() {
|
||||
@Override public void onReceive(Context context, Intent intent) { refresh(); }
|
||||
};
|
||||
|
||||
private WallpaperThemeManager(Context context) {
|
||||
super(false); // 无法读取时默认深色壁纸、白字。
|
||||
this.context = context.getApplicationContext();
|
||||
wallpaperManager = WallpaperManager.getInstance(this.context);
|
||||
}
|
||||
|
||||
public static WallpaperThemeManager getInstance(Context context) {
|
||||
if (instance == null) {
|
||||
synchronized (WallpaperThemeManager.class) {
|
||||
if (instance == null) instance = new WallpaperThemeManager(context);
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/** true 表示浅色壁纸;可直接使用 LifecycleOwner 观察。 */
|
||||
public boolean isLightWallpaper() { return Boolean.TRUE.equals(getValue()); }
|
||||
|
||||
public int getTextColor() { return isLightWallpaper() ? Color.BLACK : Color.WHITE; }
|
||||
|
||||
@Override protected void onActive() {
|
||||
ContextCompat.registerReceiver(context, receiver,
|
||||
new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED), ContextCompat.RECEIVER_EXPORTED);
|
||||
if (Build.VERSION.SDK_INT >= 27) {
|
||||
WallpaperManager.OnColorsChangedListener listener = (colors, which) -> {
|
||||
if ((which & WallpaperManager.FLAG_SYSTEM) != 0) refresh();
|
||||
};
|
||||
wallpaperManager.addOnColorsChangedListener(listener, handler);
|
||||
removeColorsListener = () -> wallpaperManager.removeOnColorsChangedListener(listener);
|
||||
}
|
||||
refresh();
|
||||
}
|
||||
|
||||
@Override protected void onInactive() {
|
||||
context.unregisterReceiver(receiver);
|
||||
if (removeColorsListener != null) {
|
||||
removeColorsListener.run();
|
||||
removeColorsListener = null;
|
||||
}
|
||||
generation++;
|
||||
if (pending != null) pending.dispose();
|
||||
}
|
||||
|
||||
/** 主线程调用;读取与采样在后台执行,快速连续切换只采用最后一次结果。 */
|
||||
public void refresh() {
|
||||
if (Looper.myLooper() != Looper.getMainLooper()) {
|
||||
handler.post(this::refresh);
|
||||
return;
|
||||
}
|
||||
if (!hasActiveObservers()) return;
|
||||
final int request = ++generation;
|
||||
if (pending != null) pending.dispose();
|
||||
pending = Single.fromCallable(this::readLightWallpaper)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(light -> {
|
||||
if (request == generation && !light.equals(getValue())) setValue(light);
|
||||
}, error -> Log.w("WallpaperThemeManager", "无法读取壁纸明暗,保留当前文字颜色", error));
|
||||
}
|
||||
|
||||
private boolean readLightWallpaper() {
|
||||
if (Build.VERSION.SDK_INT >= 27) {
|
||||
WallpaperColors colors = wallpaperManager.getWallpaperColors(WallpaperManager.FLAG_SYSTEM);
|
||||
if (colors == null) return isLightWallpaper();
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
return (colors.getColorHints() & WallpaperColors.HINT_SUPPORTS_DARK_TEXT) != 0;
|
||||
}
|
||||
return ColorUtils.calculateLuminance(colors.getPrimaryColor().toArgb()) > 0.179;
|
||||
}
|
||||
// 老系统只绘制 32×32 缩略图,不创建壁纸尺寸的额外位图。
|
||||
wallpaperManager.forgetLoadedWallpaper();
|
||||
Drawable drawable = wallpaperManager.getDrawable();
|
||||
if (drawable == null) return isLightWallpaper();
|
||||
Bitmap sample = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888);
|
||||
try {
|
||||
drawable.setBounds(0, 0, 32, 32);
|
||||
drawable.draw(new Canvas(sample));
|
||||
double luminance = 0;
|
||||
for (int y = 0; y < 32; y++) {
|
||||
for (int x = 0; x < 32; x++) {
|
||||
luminance += ColorUtils.calculateLuminance(sample.getPixel(x, y));
|
||||
}
|
||||
}
|
||||
// 黑白文字对比度的交点约为 0.179。
|
||||
return luminance / 1024 > 0.179;
|
||||
} finally {
|
||||
sample.recycle();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layout xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<data />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/default_background_color"
|
||||
android:orientation="vertical"
|
||||
android:padding="12dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical">
|
||||
|
||||
<Button
|
||||
android:id="@+id/back"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="返回" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:gravity="center"
|
||||
android:text="家人相册"
|
||||
android:textColor="@color/theme_text_primary"
|
||||
android:textSize="24sp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/refresh"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="刷新" />
|
||||
</LinearLayout>
|
||||
|
||||
<RadioGroup
|
||||
android:id="@+id/filter"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:checkedButton="@id/all"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<RadioButton
|
||||
android:id="@+id/all"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="56dp"
|
||||
android:layout_weight="1"
|
||||
android:text="全部照片"
|
||||
android:textColor="@color/theme_text_primary"
|
||||
android:textSize="20sp" />
|
||||
|
||||
<RadioButton
|
||||
android:id="@+id/favorites"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="56dp"
|
||||
android:layout_weight="1"
|
||||
android:text="收藏"
|
||||
android:textColor="@color/theme_text_primary"
|
||||
android:textSize="20sp" />
|
||||
</RadioGroup>
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/progress"
|
||||
style="?android:attr/progressBarStyleHorizontal"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="4dp"
|
||||
android:indeterminate="true"
|
||||
android:visibility="gone" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/empty"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center"
|
||||
android:padding="24dp"
|
||||
android:text="暂无照片,可让家人在家属端上传后刷新"
|
||||
android:textColor="@color/theme_text_secondary"
|
||||
android:textSize="20sp" />
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/photos"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1" />
|
||||
</LinearLayout>
|
||||
</layout>
|
||||
@@ -78,6 +78,13 @@
|
||||
android:background="@drawable/settings_card_bg"
|
||||
android:orientation="vertical">
|
||||
|
||||
<Button
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="64dp"
|
||||
android:onClick="@{click::openFamilyAlbum}"
|
||||
android:text="家人相册"
|
||||
android:textSize="22sp" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
@@ -221,8 +228,8 @@
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/theme_text_primary"
|
||||
android:text="辅助设置"
|
||||
android:textColor="@color/theme_text_primary"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintEnd_toEndOf="parent"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
@@ -264,11 +271,11 @@
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:text="关于"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center"
|
||||
android:onClick="@{click::aboutUs}"
|
||||
android:textColor="@color/theme_text_primary"
|
||||
android:layout_height="wrap_content" />
|
||||
android:text="关于"
|
||||
android:textColor="@color/theme_text_primary" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toTopOf="parent" />
|
||||
|
||||
<TextView
|
||||
<com.ttstd.dialer.wallpager.WallpaperTextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="@dimen/dp_8"
|
||||
@@ -113,7 +113,7 @@
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toTopOf="parent" />
|
||||
|
||||
<TextView
|
||||
<com.ttstd.dialer.wallpager.WallpaperTextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="@dimen/dp_8"
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ttstd.dialer.manager;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MqttReconnectPolicyTest {
|
||||
@Test
|
||||
public void repeatedServerKicksKeepBackoffAcrossSuccessfulShortConnections() {
|
||||
MqttReconnectPolicy policy = new MqttReconnectPolicy();
|
||||
long now = 0;
|
||||
for (long expected : new long[]{10_000, 20_000, 40_000, 80_000, 160_000, 300_000, 300_000}) {
|
||||
policy.onConnected(now);
|
||||
assertEquals(expected, policy.nextDelayMillis(now + 1_000, true));
|
||||
now += expected + 1_000;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unsuccessfulRetriesDoNotResetBackoff() {
|
||||
MqttReconnectPolicy policy = new MqttReconnectPolicy();
|
||||
assertEquals(2_000, policy.nextDelayMillis(0, false));
|
||||
assertEquals(4_000, policy.nextDelayMillis(2_000, false));
|
||||
assertEquals(8_000, policy.nextDelayMillis(6_000, false));
|
||||
assertEquals(16_000, policy.nextDelayMillis(14_000, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stableConnectionRestoresFastRecovery() {
|
||||
MqttReconnectPolicy policy = new MqttReconnectPolicy();
|
||||
policy.nextDelayMillis(0, true);
|
||||
policy.nextDelayMillis(10_000, true);
|
||||
policy.onConnected(30_000);
|
||||
assertEquals(2_000, policy.nextDelayMillis(150_000, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void waitingWithoutConnectionDoesNotCountAsStable() {
|
||||
MqttReconnectPolicy policy = new MqttReconnectPolicy();
|
||||
policy.onConnected(0);
|
||||
assertEquals(10_000, policy.nextDelayMillis(1_000, true));
|
||||
assertEquals(20_000, policy.nextDelayMillis(1_000_000, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void manualResetStartsANewLifecycle() {
|
||||
MqttReconnectPolicy policy = new MqttReconnectPolicy();
|
||||
policy.nextDelayMillis(0, true);
|
||||
policy.nextDelayMillis(1, true);
|
||||
policy.reset();
|
||||
assertEquals(10_000, policy.nextDelayMillis(2, true));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user