Android设置桌面主要用到了WallPaperService这个类。首先创建自己的类继承WallPaperService并重写onCreateEngine()方法,创建自己的Engine。
1、创建自己的Engine类GifEngine 继承Engine,重写里面的onSurfaceCreated方法,onVisibilityChanged方法,onSurfaceDestroy方法。在onSurfaceCreate方法中加载gif动画,这里涉及到gif动画的加载与播放,涉及到Movie类,用movie解码gif文件然后画在canvas上,并重复一帧一帧的绘制。这样就能将gif动画渲染到surfaceView上呈现到屏幕。
onVisibilityChanged方法在桌面可见不可见的时候进行回调,当屏幕可见的时候进行播放,屏幕不可见取消gif绘制。onSurfaceDestroy销毁的时候销毁操作。类如下:
public class GIfWallPaperService extends WallpaperService {private Movie movie; private Handler handler; private boolean isVisible; private int height; private int width; private int gifWidth; private int gifHeigth; @Override public Engine onCreateEngine() {return new GifEngine(); }class GifEngine extends Engine {@Override public void onSurfaceCreated(SurfaceHolder holder) {super.onSurfaceCreated(holder); handler = new Handler(); try {InputStream inputStream = getContentResolver().openInputStream(Config.filePath); movie = Movie.decodeStream(inputStream); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); height = displayMetrics.heightPixels; width = displayMetrics.widthPixels; gifWidth = movie.width(); gifHeigth = movie.height(); } catch (FileNotFoundException e) {e.printStackTrace(); }}@Override public void onVisibilityChanged(boolean visible) {if (visible) {isVisible = true; handler.post(runnable); } else {isVisible = false; handler.removeCallbacks(runnable); }}@Override public void onSurfaceDestroyed(SurfaceHolder holder) {super.onSurfaceDestroyed(holder); handler.removeCallbacks(runnable); } private Runnable runnable = new Runnable() {@Override public void run() {if (isVisible) { Canvas canvas = getSurfaceHolder().lockCanvas(); canvas.save(); canvas.scale(2 , 2 ); movie.draw(canvas, 0, 0); movie.setTime((int) (System.currentTimeMillis() % movie.duration())); canvas.restore(); getSurfaceHolder().unlockCanvasAndPost(canvas); handler.postDelayed(runnable, 50); //50ms表示每50m绘制一次 }}}; } }
2、配置AndroidMainfest.xml
<service android:name=".service.GIfWallPaperService" android:label="@string/gif_wallpaper" 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/gif_wallpaper" />
</service>
3、配置gif_wallpaper.xml
<?xml version="1.0" encoding="utf-8"?> <wallpaper xmlns:android="http://schemas.android.com/apk/res/android" android:thumbnail="@mipmap/ic_launcher" android:description="@string/gif_description" />
4、配置strings.xml
<string name="gif_description">gif动态壁纸</string>
5、配置权限
<uses-permission android:name="android.permission.SET_WALLPAPER" />
6、启动GifService
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER); intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,new ComponentName(context, GIfWallPaperService.class)); startActivity(intent);这样就可以实现gif动画加载了