Search code examples
javaandroidgiflive-wallpaper

Custom WallpaperService shows only the first frame of the GIF


I'm working on a small project where I'm making my own custom live wallpaper app where I'm supposed to be able to select a gif and automatically make a live wallpaper of it. Because of this I need to write my own wallpaper service and so far it works but it only seems to be drawing the first frame.

Here's the code:

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);

        }
    }
}
}

As I stated, the code does draw the first frame and therefore there is not problem opening or accessing the file and if I open the gif in the android file manager it works just fine.

Thanks for all kinds of help!


Solution

  • Found the issue!

    movie.setTime((int) System.currentTimeMillis() % movie.duration());
    

    needs to be:

    movie.setTime((int) (System.currentTimeMillis() % movie.duration()));