我正在做一个小项目,正在制作自己的自定义动态壁纸应用程序,该应用程序应该能够选择gif并自动为其制作动态壁纸。因此,我需要编写自己的墙纸服务,到目前为止,它仍然有效,但似乎只绘制了第一帧。
代码如下:
package com.example.r.c;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.os.Environment;
import android.service.wallpaper.WallpaperService;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.SurfaceHolder;
import android.graphics.Movie;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import android.os.Handler;
public class CustomWallpaperService extends WallpaperService {
@Override
public Engine onCreateEngine() {
try{
File f = new File("/storage/emulated/0/testgif.gif");
Movie m = Movie.decodeStream(new FileInputStream(f));
return new wEngine(m);
} catch (Exception e){
return null;
}
}
public class wEngine extends Engine{
private Movie movie;
private SurfaceHolder holder;
private Handler handler;
private boolean visible = true;
public wEngine(Movie m){
this.movie = m;
handler = new Handler();
}
@Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
this.holder = surfaceHolder;
}
private Runnable drawRunnable = new Runnable() {
@Override
public void run() {
draw();
}
};
private void draw(){
Canvas canvas = holder.lockCanvas();
canvas.save();
canvas.scale(2f,2f);
movie.draw(canvas, 0, 0);
canvas.restore();
holder.unlockCanvasAndPost(canvas);
movie.setTime((int) System.currentTimeMillis() % movie.duration());
handler.removeCallbacks(drawRunnable);
handler.postDelayed(drawRunnable, 20);
}
@Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
this.visible = visible;
if (visible) {
handler.post(drawRunnable);
} else {
handler.removeCallbacks(drawRunnable);
}
}
}
}
正如我所说,代码确实绘制了第一帧,因此打开或访问文件没有问题,如果我在android文件管理器中打开gif,就可以正常工作。
感谢各种帮助!
答案 0 :(得分:0)
发现了问题!
movie.setTime((int) System.currentTimeMillis() % movie.duration());
需要是:
movie.setTime((int) (System.currentTimeMillis() % movie.duration()));