Skip to content

Instantly share code, notes, and snippets.

@nutiteq
Created October 29, 2012 21:04
Show Gist options
  • Save nutiteq/3976531 to your computer and use it in GitHub Desktop.
Save nutiteq/3976531 to your computer and use it in GitHub Desktop.
NetFetchTileTask.java
package com.nutiteq.tasks;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.nutiteq.components.Components;
import com.nutiteq.components.TileQuadTreeNode;
import com.nutiteq.log.Log;
public class NetFetchTileTask extends FetchTileTask {
private static final int CONNECTION_TIMEOUT = 5 * 1000;
private static final int READ_TIMEOUT = 5 * 1000;
protected String url;
private HttpURLConnection urlConnection;
private Map<String, String> httpHeaders;
public NetFetchTileTask(TileQuadTreeNode tile, Components components, long tileIdOffset,
String url) {
this(tile, components, tileIdOffset,url, null);
}
public NetFetchTileTask(TileQuadTreeNode tile, Components components, long tileIdOffset,
String url, Map<String, String> httpHeaders) {
super(tile, components, tileIdOffset);
this.httpHeaders = httpHeaders;
this.url = url;
}
@Override
public void run() {
super.run();
try {
urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(READ_TIMEOUT);
if(this.httpHeaders != null){
for (Map.Entry<String, String> entry : this.httpHeaders.entrySet()) {
urlConnection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
BufferedInputStream inputStream = new BufferedInputStream(urlConnection.getInputStream(), BUFFER_SIZE);
readStream(inputStream);
} catch (IOException e) {
Log.error(getClass().getName() + ": Failed to fetch tile. " + e.getMessage());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
cleanUp();
}
protected void finished(byte[] data) {
if (data == null) {
Log.error(getClass().getName() + " : No data.");
} else {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
if (bitmap == null) {
// If the compressed image is corrupt, delete it
Log.error(getClass().getName() + " : Failed to decode the image.");
} else {
// Add the compressed image to persistentCache
components.persistentCache.add(rasterTileId, data);
// Add the compressed image to compressedMemoryCache
components.compressedMemoryCache.add(rasterTileId, data);
// If not corrupt, add to the textureMemoryCache
components.textureMemoryCache.add(rasterTileId, bitmap);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment