首先是定义我们自己的Renderer类,FireWallpaperRenderer实现了GLWallpaperService.Renderer接口(GLWallpaperService的代码在《android利用OpenGLES开发动态壁纸用到的GLWallpaperService类》的那篇博客里):
import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; public class FireWallpaperRenderer implements GLWallpaperService.Renderer { @Override public void onDrawFrame(GL10 gl) { //绘制你的对象 } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { //屏幕尺寸发生变化时调用 } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { //初始化OpenGLES设置 } }
然后定义我们的WallpaperService,FireWallpaperService继承自GLWallpaperService:
public class FireWallpaperService extends GLWallpaperService { private FireWallpaperRenderer mRenderer; public Engine onCreateEngine() { if (mRenderer == null) { mRenderer = new FireWallpaperRenderer(); } return new FireWallpaperEngine(); } class FireWallpaperEngine extends GLWallpaperService.GLEngine { public FireWallpaperEngine() { setRenderer(mRenderer); setRenderMode(RENDERMODE_CONTINUOUSLY); } } }
完成后编辑Manifest.xml文件,如下:
<application android:icon="@drawable/icon" android:label="@string/app_name"> <service android:name=".FireWallpaperService" android:label="@string/firewallpaper" android:permission="android.permission.BIND_WALLPAPER"> <intent-filter> <action android:name="android.service.wallpaper.WallpaperService" /> </intent-filter> <meta-data android:name="android.service.wallpaper" android:resource="@xml/wallpaper" /> </service> </application>
Manifest.xml文件中,FireWallpaperService使用到的wallpaper文件
(<meta-dataandroid:name="android.service.wallpaper"android:resource="@xml/wallpaper" />)在res/xml目录下定义,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/description" android:thumbnail="@drawable/fire" />
这样基于OpenGLES的动态壁纸框架就搭建好了,你只需在FireWallpaperRenderer类的对应方法中添加适当的代码就可以实现动态壁纸了。