10.9 WallpaperManager(壁纸管理器)
梳理 Android WallpaperManager 壁纸设置/查询/清除 API、推荐壁纸尺寸与居中裁剪逻辑、系统壁纸选择器调用、Activity 壁纸主题配置,以及结合 AlarmManager 定时轮换壁纸的实现与现代后台调度演进。
学完这一章,你能够
- 梳理 Android WallpaperManager 壁纸设置/查询/清除 API、推荐壁纸尺寸与居中裁剪逻辑、系统壁纸选择器调用、Activity 壁纸主题配置,以及结合 AlarmManager 定时轮换壁纸的实现与现代后台调度演进。
WallpaperManager 核心方法、尺寸裁剪与权限
`WallpaperManager`(壁纸管理器)是 Android 用于读写与清除系统桌面/锁屏壁纸的系统服务,通过静态方法 `WallpaperManager.getInstance(context)` 获取实例,修改壁纸前须在 `AndroidManifest.xml` 声明 `<uses-permission android:name="android.permission.SET_WALLPAPER"/>`。设置壁纸提供 `setBitmap(Bitmap)`、`setResource(int resid)` 与 `setStream(InputStream)` 三类接口(Android 7.0 / API 24 起新增带 `visibleCropHint` 裁剪矩形与 `FLAG_SYSTEM`/`FLAG_LOCK` 标志的重载,可分别设置主屏与锁屏壁纸);其余常用方法包括 `clear()`(恢复系统默认壁纸)、`getDesiredMinimumWidth()` 与 `getDesiredMinimumHeight()`(获取桌面视差滚动所需的建议最小壁纸宽高)、`getWallpaperInfo()`(若当前为动态壁纸则返回信息,否则为 `null`),以及用于读取当前壁纸的 `getDrawable()`(未设时回退系统默认壁纸)与 `peekDrawable()`(未设时直接返回 `null`)。本站离线实验验证了 `2160×1920` 视差壁纸与 `1080×1920` 锁屏壁纸的居中裁剪矩形计算。
调用系统壁纸选择器与将 Activity 背景设为壁纸
若无需自建壁纸库,可直接构造 `new Intent(Intent.ACTION_SET_WALLPAPER)` 并通过 `startActivity(Intent.createChooser(chooseIntent, "选择壁纸"))` 唤起系统内置壁纸选择器,由用户挑选图库或动态壁纸应用。
若要将当前 `Activity` 背景透明呈现为系统当前壁纸,有两种等价配置:方法一在 `Activity.onCreate()` 调用 `super.onCreate(savedInstanceState)` **之前**执行 `setTheme(android.R.style.Theme_Wallpaper_NoTitleBar_Fullscreen)`;方法二在 `AndroidManifest.xml` 对应 `<activity>` 节点声明 `android:theme="@android:style/Theme.Wallpaper.NoTitleBar"`(若使用 `AppCompatActivity` 则需继承自 `Theme.AppCompat` 并配置 `windowShowWallpaper=true` 与透明背景以避免主题不兼容崩溃)。
结合 AlarmManager 实现定时换壁纸与现代调度注意
定时换壁纸示例将 `WallpaperManager` 与 10.5 节的 `AlarmManager` 结合:`WallPaperService` 在 `onCreate()` 中获取 `WallpaperManager` 实例,维护 4 张资源下标 `current`,每次 `onStartCommand()` 触发时循环调用 `wManager.setResource(papers[current++])`(到达 4 时归零)并返回 `START_STICKY`;`MainActivity` 布局提供“开启自动换壁纸”“关闭自动换壁纸”“清除壁纸”三个按钮,通过 `PendingIntent.getService()` 绑定 `WallPaperService`,点击开启后调用 `aManager.setRepeating(AlarmManager.RTC_WAKEUP, 0, 3000, pi)` 并切换按钮可用态,点击关闭时 `aManager.cancel(pi)`,点击清除时调用 `clear()`;最后在清单注册 `SET_WALLPAPER` 权限与 `<service android:name=".WallPaperService"/>`。需提示现代兼容性:Android 5.1+ 对短周期重复闹钟设有最小间隔限制(通常 60 秒),Android 8.0+ 限制后台 `startService`,Android 12+ 构造 `PendingIntent` 须显式指定 `FLAG_IMMUTABLE` 或 `FLAG_MUTABLE`,生产环境定时换壁纸宜改用 Jetpack `WorkManager`。来源附带的 `WallpaperManagerDemo.zip` 因继承停采策略未联网下载,已登记留痕。
运行离线 WallpaperManager 推荐尺寸裁剪、壁纸选择器配置与定时轮播状态核验
"""Offline Android system-service verifier for Ch 144: WallpaperManager."""
from dataclasses import dataclass
import json
import xml.etree.ElementTree as ET
VERSION = (
"CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
"(Android SDK/emulator absent)"
)
@dataclass
class WallpaperManagerModel:
desired_min_width: int
desired_min_height: int
default_wallpaper: str = "system_default_wallpaper"
current_wallpaper: str | None = None
live_wallpaper_info: dict | None = None
def set_resource(self, res_name: str) -> None:
self.current_wallpaper = res_name
self.live_wallpaper_info = None
def clear(self) -> None:
self.current_wallpaper = None
self.live_wallpaper_info = None
def get_drawable(self) -> str:
return self.current_wallpaper or self.default_wallpaper
def peek_drawable(self) -> str | None:
return self.current_wallpaper
def compute_center_crop_rect(src_w: int, src_h: int, dst_w: int, dst_h: int) -> dict[str, int]:
"""Compute centered source crop rectangle matching target wallpaper aspect ratio."""
src_ratio = src_w / src_h
dst_ratio = dst_w / dst_h
if src_ratio > dst_ratio:
crop_h = src_h
crop_w = round(src_h * dst_ratio)
else:
crop_w = src_w
crop_h = round(src_w / dst_ratio)
left = (src_w - crop_w) // 2
top = (src_h - crop_h) // 2
return {"left": left, "top": top, "right": left + crop_w, "bottom": top + crop_h}
def main() -> None:
# Case 1: WallpaperManager desired dimensions, center-crop hint, getDrawable vs peekDrawable
wm = WallpaperManagerModel(desired_min_width=2160, desired_min_height=1920)
before_set = {"getDrawable": wm.get_drawable(), "peekDrawable": wm.peek_drawable()}
wm.set_resource("R.mipmap.gui_1")
after_set = {"getDrawable": wm.get_drawable(), "peekDrawable": wm.peek_drawable()}
wm.clear()
after_clear = {"getDrawable": wm.get_drawable(), "peekDrawable": wm.peek_drawable()}
# 3840x2160 (16:9) source image cropped to 2160x1920 (9:8 parallax wallpaper)
crop_parallax = compute_center_crop_rect(3840, 2160, wm.desired_min_width, wm.desired_min_height)
# 1080x2400 tall image cropped to 1080x1920 (9:16 lockscreen)
crop_lockscreen = compute_center_crop_rect(1080, 2400, 1080, 1920)
c1_actual = {
"desired_dimensions": [wm.desired_min_width, wm.desired_min_height],
"before_set": before_set,
"after_set": after_set,
"after_clear": after_clear,
"crop_parallax_3840x2160": crop_parallax,
"crop_lockscreen_1080x2400": crop_lockscreen,
}
c1_expected = {
"desired_dimensions": [2160, 1920],
"before_set": {"getDrawable": "system_default_wallpaper", "peekDrawable": None},
"after_set": {"getDrawable": "R.mipmap.gui_1", "peekDrawable": "R.mipmap.gui_1"},
"after_clear": {"getDrawable": "system_default_wallpaper", "peekDrawable": None},
"crop_parallax_3840x2160": {"left": 705, "top": 0, "right": 3135, "bottom": 2160},
"crop_lockscreen_1080x2400": {"left": 0, "top": 240, "right": 1080, "bottom": 2160},
}
# Case 2: System wallpaper chooser Intent & Activity wallpaper theme configuration
manifest = """<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<application>
<activity android:name=".MainActivity" android:theme="@android:style/Theme.Wallpaper.NoTitleBar" />
<service android:name=".WallPaperService" />
</application>
</manifest>"""
root = ET.fromstring(manifest)
ns = "{http://schemas.android.com/apk/res/android}"
chooser_intent = {
"action": "android.intent.action.SET_WALLPAPER",
"chooser_title": "选择壁纸",
}
activity_theme = root.find("./application/activity").attrib[f"{ns}theme"]
perm = root.find("uses-permission").attrib[f"{ns}name"]
service_name = root.find("./application/service").attrib[f"{ns}name"]
c2_actual = {
"chooser_intent": chooser_intent,
"manifest_theme": activity_theme,
"permission": perm,
"service": service_name,
}
c2_expected = {
"chooser_intent": {
"action": "android.intent.action.SET_WALLPAPER",
"chooser_title": "选择壁纸",
},
"manifest_theme": "@android:style/Theme.Wallpaper.NoTitleBar",
"permission": "android.permission.SET_WALLPAPER",
"service": ".WallPaperService",
}
# Case 3: Scheduled wallpaper rotation service cycle & button enabled state
papers = ["R.mipmap.gui_1", "R.mipmap.gui_2", "R.mipmap.gui_3", "R.mipmap.gui_4"]
current = 0
applied_sequence = []
for _ in range(6):
if current >= len(papers):
current = 0
wm.set_resource(papers[current])
applied_sequence.append(wm.get_drawable())
current += 1
btn_on_enabled, btn_off_enabled = True, False
# Click btn_on
btn_on_enabled, btn_off_enabled = False, True
after_start = [btn_on_enabled, btn_off_enabled]
# Click btn_off
btn_on_enabled, btn_off_enabled = True, False
after_stop = [btn_on_enabled, btn_off_enabled]
c3_actual = {
"rotation_sequence_6_ticks": applied_sequence,
"buttons_after_start": after_start,
"buttons_after_stop": after_stop,
}
c3_expected = {
"rotation_sequence_6_ticks": [
"R.mipmap.gui_1",
"R.mipmap.gui_2",
"R.mipmap.gui_3",
"R.mipmap.gui_4",
"R.mipmap.gui_1",
"R.mipmap.gui_2",
],
"buttons_after_start": [False, True],
"buttons_after_stop": [True, False],
}
cases = [
{
"name": "wallpapermanager_dimensions_crop_and_drawables",
"summary": "验证 WallpaperManager 最小推荐尺寸、居中裁剪矩阵及 getDrawable/peekDrawable/clear 状态差异",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "wallpaper_chooser_theme_and_manifest",
"summary": "验证 ACTION_SET_WALLPAPER 选择器 Intent、Theme.Wallpaper 主题配置与 SET_WALLPAPER 清单声明",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "scheduled_wallpaper_service_rotation",
"summary": "验证 AlarmManager + WallPaperService 轮播索引循环及启停按钮状态切换",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证 getDesiredMinimumWidth/Height 居中裁剪、getDrawable 与 peekDrawable 返回差异、清单声明及 4 图循环轮播。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:9ca3a8f1ff1fd9f4536945042ae74157594f592a1ef728ae827029e8d7b5d55a
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:4a9638406e9e8764141a28a58d588850864bbaaf9ce59fa50448ad7958e6ea07
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`WallpaperManager` 中 `getDrawable()` 与 `peekDrawable()` 在设备未自定义壁纸时有何区别?
展开参考解答
`getDrawable()` 在用户未设置自定义壁纸时会返回系统默认壁纸 `Drawable`,而 `peekDrawable()` 仅在已设置壁纸时返回对象、未设置时直接返回 `null`。