play downloaded Gif image in android

I'm downloading GIF image in my app from server and then i'm showing it with ImageView but it was not animated . is there any other way to play downloaded animated GIF image . Thanks in advance .


Solution 1:

I am using the below custom View instead of Image View.

public class SampleView extends View {

    private Movie mMovie;
    private long mMovieStart;

    public SampleView(Context context) {
        super(context);
        setFocusable(true);

        java.io.InputStream is;
        is = context.getResources().openRawResource(R.drawable.girl_dances);
        mMovie = Movie.decodeStream(is); 
    }

    public SampleView(Context context, AttributeSet attrSet) {
        super(context, attrSet);
        setFocusable(true);

        java.io.InputStream is;
        is = context.getResources().openRawResource(R.drawable.girl_dances);
        mMovie = Movie.decodeStream(is);
    }

    public SampleView(Context context, AttributeSet attrSet, int defStyle) {
        super(context, attrSet, defStyle);
        setFocusable(true);

        java.io.InputStream is;
        is = context.getResources().openRawResource(R.drawable.girl_dances);
        mMovie = Movie.decodeStream(is);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(0x00000000);

        Paint p = new Paint();
        p.setAntiAlias(true);

        long now = android.os.SystemClock.uptimeMillis();
        if (mMovieStart == 0) { // first time
            mMovieStart = now;
        }
        if (mMovie != null) {
            int dur = mMovie.duration();
            if (dur == 0) {
                dur = 1000;
            }
            int relTime = (int) ((now - mMovieStart) % dur);
            mMovie.setTime(relTime);
            mMovie.draw(canvas, getWidth() / 2 - mMovie.width() / 2,
                    getHeight() / 2 - mMovie.height() / 2);
            invalidate();
        }
    }
    }

XML Layout :

<com.test.sample.SampleView
android:id="@+id/gif_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Solution 2:

After some research, it seems that the best (or easiest) solution is to use a WebView :

ex :

put myAnimatedGif.gif file into the assets folder.

create an xml web View:

<WebView
    android:id="@+id/myWebView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

then load the gif file into the web view :

    WebView view = (WebView) findViewById(R.id.myWebView);
    view.loadUrl("file:///android_asset/myAnimatedGif.gif");

Enjoy !

An other solution is to use this kind of library: https://github.com/koral--/android-gif-drawable