Tagdalvik

Tutorial: How to play animated GIFs in Android – Part 3

Animated GIFs in Android is a difficult topic. It is an issue that has been discussed heavily and still, it is very difficult for developers to bring GIFs to life. There are three ways to animate GIFs on Android, each of them has its pros and cons. Each part of this series will cover one of these approaches.

Getting started

For this example, we will use an image I found on gifs.net, it’s this one:

I will store it in our project’s asset folder and name it ‘piggy.gif’. We will also use an Activity to set the views we define as content views. If you want to know everything about playing GIFs, please start at part one.

Approach 3: Using a WebView

This is the by far easyest way. As you might know, a WebView is able to do what a browser does. And since the browser of Android devices using Android 2.2 + supports the animation of GIFs (at least on most devices), we can just use that.

So, at first, we extend our own class by a WebView:

public class GifWebView extends WebView

We create a constructor that takes both a context to call the constructor of the mother-class and a path to the file. We use loadUrl() to load that file into our WebView:

   public GifWebView(Context context, String path) {
      super(context);
      loadUrl(path);
   }

Now, let’s go back to our Activity which we created in the first tutorial. Here, we create our view and pass it a context and path to our GIF-file:

   GifWebView view = new GifWebView(this, "file:///android_asset/piggy.gif");
   setContentView(view);

And now, believe it or not, we are done.

Movie, GifDecoder or WebView?

Which way you take depends on your needs. When your app is targeting users mainly using devices with Android 2.2+, the way described above is probably your way to go. If you want to support as many devices as possible and don’t care much about memory footprint, you can also use the GifDecoder-method. When you want to support many users but don’t want to recycle tons of Bitmaps, and are sure the format of your GIFs can be played using the Movie-class, then this approach is for you.

Personally, I prefer the WebView-way. Because WebKit is already implemented native, it’s memory footprint is really low, especially when compared to the GifDecoder. Operations on images like scaling can be performed simply by using HTML and the overall code is really short and pretty.

 

You can checkout the code of the three parts of this series at http://code.google.com/p/animated-gifs-in-android/.

 

Which method do you like best? As always, please feel free to leave your thoughts in the comments.

Tutorial: How to play animated GIFs in Android – Part 2

Animated GIFs in Android is a difficult topic. It is an issue that has been discussed heavily and still, it is very difficult for developers to bring GIFs to life. There are three ways to animate GIFs on Android, each of them has its pros and cons. Each part of this series will cover one of these approaches.

Getting started

For this example, we will use an image I found on gifs.net, it’s this one:

I will store it in our project’s asset folder and name it ‘piggy.gif’. We will also use an Activity to set the views we define as content views. If you want to know everything about playing GIFs, please start at part one.

Approach 2: Extracting the Bitmaps

For this approach, we will use the GifDecoder class published here on googlecode. It’s Apache licensed, so don’t worry. What this class esentially does is, it extracts the different bitmaps from the given stream so you can use it the way you want.

To get started, download this class first. Place it somewhere in your project, maybe in a util package.
Now, we create a new class which inherits from ImageView:

   public class GifDecoderView extends ImageView

We create a constructor with a Context and an InputStream, just like in the first part of this series. This time, we call a method playGif(InputStream) and pass it our InputStream:

   public GifDecoderView(Context context, InputStream stream) {
      super(context);
      playGif(stream);

We give our class five member variables: A boolean which will state whether the thread we will use to play our animation is runningor not, an instance of the GifDecoder-class you just downloaded, a Bitmap which stores the different frames of the animation, a Handler to post our updates to the UI-thread and a Runnable that will arrange that the Bitmap we just defined will be drawn using the Handler:

   private boolean mIsPlayingGif = false;

   private GifDecoder mGifDecoder;

   private Bitmap mTmpBitmap;

   final Handler mHandler = new Handler();

   final Runnable mUpdateResults = new Runnable() {
      public void run() {
         if (mTmpBitmap != null && !mTmpBitmap.isRecycled()) {
            GifDecoderView.this.setImageBitmap(mTmpBitmap);
         }
      }
   };

Let’s take a look at playGif(InputStream). First, we need to initialise mGifDecoder. After that, we let it read our stream and set mIsPlayingGif to true, so that our thread can run:

   private void playGif(InputStream stream) {
      mGifDecoder = new GifDecoder();
      mGifDecoder.read(stream);
      mIsPlayingGif = true;

Now we need to define our thread. We retreive the frame count of our GIF’s frames and the number of repetitions. When GifDecoder.getLoopCount() returns 0, this means the GIF should be played infinitely. Now for every frame, we receive the according Bitmap by calling getFrame() on the GifDecoder. We post our new Bitmap using the Handler and Runnable members we defined and send our thread to sleep until the next Bitmap needs to be drawn.

new Thread(new Runnable() {
         public void run() {
            final int n = mGifDecoder.getFrameCount();
            final int ntimes = mGifDecoder.getLoopCount();
            int repetitionCounter = 0;
            do {
              for (int i = 0; i < n; i++) {
                 mTmpBitmap = mGifDecoder.getFrame(i);
                 final int t = mGifDecoder.getDelay(i);
                 mHandler.post(mUpdateResults);
                 try {
                    Thread.sleep(t);
                 } catch (InterruptedException e) {
                    e.printStackTrace();
                 }
              }
              if(ntimes != 0) {
                 repetitionCounter ++;
              }
           } while (mIsPlayingGif && (repetitionCounter <= ntimes))
        }
     }).start();

That’s it. All we have to do now is use our GifDecoderView in an Activity, just like we did in the last part of this tutorial:

   // ...
   InputStream stream = null;
   try {
      stream = getAssets().open("piggy.gif");
   } catch (IOException e) {
      e.printStackTrace();
   }

// GifMovieView view = new GifMovieView(this, stream);
   GifDecoderView view = new GifDecoderView(this, stream);

   setContentView(view);
   // ...

 

Now, what’ the bad thing about this? It’s the memory footprint. Bitmaps on pre-Honeycomb-devices are stored in an native heap, not in the heap the Dalvik VM uses. Still, this heap counts to the maximum of memory your app can use. So when you have a lot of Bitmaps, the garbage collector might not notice that you are running out of memory because it only controls the heap of the Dalvik VM. To avoid this, make sure you call recycle() on every Bitmap you don’t need anymore. If you want to see how much space your native heap allocated, call Debug.getNativeHeapAllocatedSize().

If you want to know another, maybe better way of playing animated GIFs, stay tuned: The next part of this series will come soon.

 

You can checkout the code of the three parts of this series at http://code.google.com/p/animated-gifs-in-android/.

 

As always, please feel free to leave your thoughts in the comments.

© 2024 Droid-Blog

Theme by Anders NorenUp ↑