diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 65e3354..a756e31 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -144,6 +144,10 @@ android:launchMode="singleInstance" android:showOnLockScreen="true" android:turnScreenOn="true" /> + + + android:screenOrientation="portrait" + android:theme="@style/MaterialTheme" /> { + 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{ + List 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;} + } +} diff --git a/app/src/main/java/com/ttstd/dialer/activity/album/FamilyAlbumViewModel.java b/app/src/main/java/com/ttstd/dialer/activity/album/FamilyAlbumViewModel.java new file mode 100644 index 0000000..9d150b3 --- /dev/null +++ b/app/src/main/java/com/ttstd/dialer/activity/album/FamilyAlbumViewModel.java @@ -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> photos=new MutableLiveData<>(new ArrayList<>()); + private final MutableLiveData busy=new MutableLiveData<>(false); + private List all=new ArrayList<>(); + private boolean favoritesOnly; + public FamilyAlbumViewModel(Application app){super(app);repository=SnRepository.getInstance(app);} + public LiveData> photos(){return photos;} + public LiveData busy(){return busy;} + public void filter(boolean favorites){favoritesOnly=favorites;publish();} + private void publish(){List 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;ifailed()));} + 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("操作失败,请检查网络后重试");} +} diff --git a/app/src/main/java/com/ttstd/dialer/activity/settings/home/SettingsActivity.java b/app/src/main/java/com/ttstd/dialer/activity/settings/home/SettingsActivity.java index 2348803..cf87081 100644 --- a/app/src/main/java/com/ttstd/dialer/activity/settings/home/SettingsActivity.java +++ b/app/src/main/java/com/ttstd/dialer/activity/settings/home/SettingsActivity.java @@ -50,6 +50,7 @@ public class SettingsActivity extends BaseMvvmActivity> getFamilyPictures() { + return ApiResponseMapper.unwrap(mApi.getFamilyPictures()); + } + + public Observable setPictureFavorite(String url, boolean favorite) { + return ApiResponseMapper.unwrapAsSuccess(mApi.setPictureFavorite(url, favorite ? 1 : 0)); + } + + public Observable deleteFamilyPicture(String url) { + return ApiResponseMapper.unwrapAsSuccess(mApi.deleteFamilyPicture(url)); + } } diff --git a/app/src/main/java/com/ttstd/dialer/data/repository/SnRepository.java b/app/src/main/java/com/ttstd/dialer/data/repository/SnRepository.java index 1f5c62e..6dc2a6a 100644 --- a/app/src/main/java/com/ttstd/dialer/data/repository/SnRepository.java +++ b/app/src/main/java/com/ttstd/dialer/data/repository/SnRepository.java @@ -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> getFamilyPictures() { + return mRemoteDataSource.getFamilyPictures().subscribeOn(Schedulers.io()); + } + + public Observable setPictureFavorite(String url, boolean favorite) { + return mRemoteDataSource.setPictureFavorite(url, favorite).subscribeOn(Schedulers.io()); + } + + public Observable deleteFamilyPicture(String url) { + return mRemoteDataSource.deleteFamilyPicture(url).subscribeOn(Schedulers.io()); + } } diff --git a/app/src/main/java/com/ttstd/dialer/manager/MqttManager.java b/app/src/main/java/com/ttstd/dialer/manager/MqttManager.java index f807000..15e4dcf 100644 --- a/app/src/main/java/com/ttstd/dialer/manager/MqttManager.java +++ b/app/src/main/java/com/ttstd/dialer/manager/MqttManager.java @@ -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 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 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 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; } diff --git a/app/src/main/java/com/ttstd/dialer/manager/MqttReconnectPolicy.java b/app/src/main/java/com/ttstd/dialer/manager/MqttReconnectPolicy.java new file mode 100644 index 0000000..7296459 --- /dev/null +++ b/app/src/main/java/com/ttstd/dialer/manager/MqttReconnectPolicy.java @@ -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; + } +} diff --git a/app/src/main/java/com/ttstd/dialer/network/api/SnApi.java b/app/src/main/java/com/ttstd/dialer/network/api/SnApi.java index 99c57e0..e3f88ea 100644 --- a/app/src/main/java/com/ttstd/dialer/network/api/SnApi.java +++ b/app/src/main/java/com/ttstd/dialer/network/api/SnApi.java @@ -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>> getFamilyPictures(); + + @POST("pictures/favorite") + Observable> setPictureFavorite( + @Query("url") String url, @Query("favorite") int favorite); + + @DELETE("pictures") + Observable> deleteFamilyPicture(@Query("url") String url); } diff --git a/app/src/main/java/com/ttstd/dialer/wallpager/WallpaperTextView.java b/app/src/main/java/com/ttstd/dialer/wallpager/WallpaperTextView.java new file mode 100644 index 0000000..0aacb90 --- /dev/null +++ b/app/src/main/java/com/ttstd/dialer/wallpager/WallpaperTextView.java @@ -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 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()); + } +} diff --git a/app/src/main/java/com/ttstd/dialer/wallpager/WallpaperThemeManager.java b/app/src/main/java/com/ttstd/dialer/wallpager/WallpaperThemeManager.java new file mode 100644 index 0000000..0959d25 --- /dev/null +++ b/app/src/main/java/com/ttstd/dialer/wallpager/WallpaperThemeManager.java @@ -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 { + 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(); + } + } +} diff --git a/app/src/main/res/layout/activity_family_album.xml b/app/src/main/res/layout/activity_family_album.xml new file mode 100644 index 0000000..dc99643 --- /dev/null +++ b/app/src/main/res/layout/activity_family_album.xml @@ -0,0 +1,90 @@ + + + + + + + + + +