Mobile atlas installer for Android

We want to ship OSM tiles in our APK and install them on the SD card for offline use.

First create the offline map for several zoom levels in Mobile Atlas Creator. Be sure to set the atlas format to osmdroid ZIP. Add the result to the assets folder of your Android project.

In general, use AssetManager to retrieve assets and use Java IO to move them to some place in the filesystem. For our case we could write a simple installer class:

package de.nitri.reichswald;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import android.content.res.AssetManager;
import android.util.Log;
 
public class AtlasInstaller {
 
	private AssetManager assetManager;
 
	public AtlasInstaller(AssetManager assetManager) {
		this.assetManager = assetManager;
	}
 
	public void install() {
		String filename = "reichswald.zip";
		String dir = "/sdcard/osmdroid/";
		File atlasDirectory = new File(dir);
		atlasDirectory.mkdirs();
		InputStream in = null;
		OutputStream out = null;
		try {
			in = assetManager.open(filename);
			out = new FileOutputStream(dir + filename);
			copyFile(in, out);
			in.close();
			in = null;
			out.flush();
			out.close();
			out = null;
		} catch (Exception e) {
			Log.e("tag", e.getMessage());
		}
 
	}
 
	private void copyFile(InputStream in, OutputStream out) throws 
           IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
	}
}

We can call it from our main activity when the app starts for the first time, when the user requests it or whenever appropriate.

AtlasInstaller installer = new AtlasInstaller(getAssets());
installer.install();

Add the needed permission to the manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />;

Leave a Reply