package uk.co.baroquedub.downloadfile;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
public class DownloadToPhone extends Activity {
private static final String TAG = "DownloadToPhone";
protected static final String IMAGE_FILENAME = "news-thumb.png";
protected static final String IMAGE_SOURCE = "http://developerlife.com/theblog/wp-content/uploads/2007/11/"+IMAGE_FILENAME;
private static final String PACKAGE_NAME = "uk.co.baroquedub.downloadfile";
private static final String URI_PREFIX = "file:///data/data/"+PACKAGE_NAME+"/files/";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
// download an image from the web... in the background
{
Runnable getImage = new Runnable() {
public void run() {
try {
Log.i(TAG, "MainDriver: trying to download and save PNG file to user.dir");
URL u = new URL(IMAGE_SOURCE);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = openFileOutput(IMAGE_FILENAME, Activity.MODE_WORLD_WRITEABLE);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
Log.i(TAG, "successfully downloaded IMAGE file to user.dir");
WebView web = (WebView) findViewById(R.id.webview);
initWebkit(web);
}
catch (Exception e) {
Log.e(TAG, "could not download and save IMAGE file", e);
}
}
};
new Thread(getImage).start();
}
}
catch (Exception e) {
Log.e(TAG, "ui creation problem", e);
}
}
private static void initWebkit(WebView web) {
String html = new String();
html = ("<html><body><header><h1>Title</h1></header><section><img src=\""+URI_PREFIX+IMAGE_FILENAME+"\" align=left><p>Content</p></section></body></html>" );
web.loadDataWithBaseURL(URI_PREFIX,
html,
"text/html",
"utf-8",
"");
}
}