Monday, March 19, 2012

Using assets from any apk

Android allows a nice feature of adding your own files in the final apk package. These files are called “assets”. For adding assets to your project you simply add your files to the “prj_name/assets” directory.

The files you add in the assets directory will be zipped in the final “apk” project, along with the executable-files and the other resources.

One has two methods to access the asset files:

  1. use android.content.res.AssetManager
    • Note that this will limit your asset files to 1Mb, at least for Android 1.5 release.
  2. use java.util.zip 
    1. This has no limitations to size, but will access all resources in the zip, so one has to filter the results.
    2. The implementations at a glance:
      1. android.content.res.AssetManager
        AssetManager am = getResources().getAssets(); // get the local asset manager
        InputStream is = am.open( asset ); // open the input stream for reading
        while ( true ) // do the reading
        {
        int count = is.read(buf, 0, MAX_BUF);
        // .. use the data as you wish
        }
      2. java.util.zip
        1. Your apk file is installed in /data/app/com.name.of.package.apk
        2. Given this location of your apk file, the unzip method is straight-forward:
          ZipFile zipFile = new ZipFile(m_sZipFilename); // create the zip file
          Enumeration entries = zipFile.entries(); // get the enumeration of the entries in the zip
          while (entries.hasMoreElements()) // while the zip still has elements
          {
          ZipEntry entry = (ZipEntry)entries.nextElement(); // get each entry at a time
          String filename = entry.getName(); // get entry name
          zipFile.getInputStream(entry); // get the input stream for the given entry – you can use this to unzip the asset
          // process the entry as you like (copy it in the
          }
        3. Some other useful methods of the ZipEntry class are: 
          • - getSize(): Gets the uncompressed size of this ZipEntry.
          • - isDirectory(): Gets the uncompressed size of this ZipEntry.
          • - getCompressedSize(): Gets the compressed size of this ZipEntry

http://www.itwizard.ro/android-phone-installing-assets-how-to-60.html 

No comments:

Post a Comment