实现方案,使用camera1实现,CameraX怎么实现还没研究出来,废话不多说,直接看步骤
1、添加壁纸权限,相机权限
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
2、注册服务
<service
android:name=".services.CameraLiveWallpaperService"
android:label="@string/app_name"
android:permission="android.permission.BIND_WALLPAPER">
<!-- 为实时壁纸配置intent-filter -->
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<!-- 为实时壁纸配置meta-data -->
<meta-data
android:name="android.service.wallpaper"
android:resource="@xml/livewallpaper" />
</service>
3、livewallpaper布局如下
<wallpaper
xmlns:android="http://schemas.android.com/apk/res/android"
android:thumbnail="@mipmap/logo"/>
4、重点来了,自定义Service继承WallpaperService,代码如下
@Keep
@Suppress("DEPRECATION")
class CameraLiveWallpaperService : WallpaperService() {
override fun onCreateEngine():Engine {
return CameraEngine()
}
internal inner class CameraEngine : Engine(),Camera.PreviewCallback {
private var camera:Camera? =null
override fun onVisibilityChanged(visible:Boolean) {
if (visible) {
startPreview()
}else {
stopPreview()
}
}
/**
* 开始预览
*/
private fun startPreview() {
camera =Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK)
camera?.setDisplayOrientation(90)
try {
camera?.setPreviewDisplay(surfaceHolder)
camera?.startPreview()
}catch (e:Exception) {
e.printStackTrace()
}
}
/**
* 停止预览
*/
private fun stopPreview() {
if (camera !=null) {
try {
camera?.stopPreview()
camera?.setPreviewCallback(null)
camera?.release()
}catch (e:Exception) {
e.printStackTrace()
}
camera =null
}
}
override fun onPreviewFrame(bytes:ByteArray, camera:Camera) {
camera.addCallbackBuffer(bytes)
}
override fun onDestroy() {
stopPreview()
super.onDestroy()
}
}
}