I'm trying to add a class in my application by which I can download different type of files instead of pdf on API 23 and lower.
I have tested my codes on API 24 and upper and I can easily download pdf files but I don't know why it's not working on API <= 23.
public class FileDownloader {
private static final int MEGA_BYTE = 1024 * 1024;
public interface OnDownloadListener{
void onStarted();
void onProgressUpdate(int upd);
void onFinished(String result);
void onError(Exception e);
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
public static class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private OnDownloadListener onDownloadListener;
public DownloadTask(Context context, OnDownloadListener onDownloadListener) {
this.context = context;
this.onDownloadListener = onDownloadListener;
}
#Override
protected String doInBackground(String... str) {
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
wl.acquire();
try {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(str[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(str[1]); // /sdcard/file_name.extension
byte data[] = new byte[MEGA_BYTE];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled())
return null;
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
if(onDownloadListener != null){
onDownloadListener.onError(e);
}
return e.toString();
}finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
}catch (IOException ignored) { }
if (connection != null)
connection.disconnect();
}
} finally {
wl.release();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if(onDownloadListener != null){
onDownloadListener.onStarted();
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to fals
if(onDownloadListener != null){
onDownloadListener.onProgressUpdate(progress[0]);
}
}
#Override
protected void onPostExecute(String result) {
if(onDownloadListener != null){
onDownloadListener.onFinished(result);
}
}
}
}
When "HttpURLConnection" tries to connect it returns error code 404 which means "HTTP 404 Not Found" but on API >= 24 it works fine and also I can download these files via web browsers too.
I also tried to use "DownloadManager" class but it returns "Failed" when I start downloading pdf files on API <= 23.
How can I fix this problem on API <= 23?!!
Thanks in advance.
Set your minSdkVersion to maybe 15. This will make your app compatible with devices API 15 and above
Related
I'm working on an Android app that is going to call the DarkSky weather API (I have redacted my API key here for obvious reasons). My problem comes when I parse the JSON data and push it to a stack I named dataStack. At the time of pushing the stack I log its size and it shows correctly. However when my code reaches the buildGraph() method, the stack is now empty and all my data has disappeared. What causes the stack to empty?
EDIT: As of 30 minutes after posting I found a workaround. I am now returning the String and parsing it in my MainActivity Android class. However, I still do not know why the stack was being deleted. I would love to know :)
public class MainActivity extends AppCompatActivity {
Button button;
TextView progressLabel;
GraphView graph;
JSONObject jsonObject;
static Stack<DataPoint> dataStack = new Stack<>(); // stack for graph data points
static final String API_URL = "https://api.darksky.net/forecast/API_KEY/42.3611,-71.0570,"; // #TODO: delete API key before comitting to GitHub
static final String URL_TAIL = "?exclude=currently,flags,hourly"; // end of URL
static final long currTime = System.currentTimeMillis() / 1000L; // current UNIX time
static long unixTime = currTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
progressLabel = findViewById(R.id.progressLabel);
graph = findViewById(R.id.graph);
}
public void loadResults(View view) {
for (int x = 0; x < 2; x++) { // 7 API calls for each of 7 days
new APICall().execute();
unixTime -= 86400; // subtract 24 hours in UNIX time
dataStack.size();
}
buildGraph(); // after all data is gathered, build a graph using it
}
private void buildGraph() {
// #TODO: Method to build graph
Log.i("STACK pop", String.valueOf(dataStack.size()));
}
class APICall extends AsyncTask<Void, Void, String> { // Extend AsyncTask so we don't hijack the main UI thread
protected void onPreExecute() {
// Do stuff before executing the AsyncTask
progressLabel.setText("Fetching Data");
}
protected String doInBackground(Void... urls) {
// Execute background task here
try {
final String FULL_URL = API_URL + unixTime + URL_TAIL; // build the full URL with latest time
URL url = new URL(FULL_URL); // URL for the API call
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // connection to URL
try {
// tools for reading API results
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
// accumulate results
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close(); // always close buffered reader
return stringBuilder.toString(); // return results
}
finally {
// inside a finally block so that no matter what we always end a connection that has been started
urlConnection.disconnect(); // end the connection
}
}
catch(Exception ex) {
Log.e("ERROR", ex.getMessage(), ex);
return null;
}
}
protected void onPostExecute(String response) {
// Do stuff after we're finished executing
if (response == null) {
response = "AN ERROR HAS OCCURRED";
}
else {
try {
jsonObject = new JSONObject(response); // create object from our response
JSONArray arr = jsonObject.getJSONObject("daily").getJSONArray("data"); // get data Array
String arrString = arr.getString(0); // full String
String[] splitString = arrString.split(","); // split String into array by comma
String time = splitString[0].substring(8); // time is the first index of the array, use substring to cutout unecessary info
String temp = splitString[11].substring(18);
dataStack.push(new DataPoint(Integer.valueOf(time), Float.valueOf(temp))); // push our data onto the stack as a DataPoint
Log.i("STACK push", String.valueOf(dataStack.toString()));
response = "Data received"; // display this to user
}
catch(Exception ex) {
response = "ERROR DURING JSON PARSING";
}
}
progressLabel.setText(response);
// parse data here
Log.i("INFO", response);
}
}
}
The stack is empty because result isn't in yet. The issue is with your loadResults().
public void loadResults(View view) {
for (int x = 0; x < 2; x++) { // 7 API calls for each of 7 days
new APICall().execute();
unixTime -= 86400; // subtract 24 hours in UNIX time
dataStack.size();
}
buildGraph(); // after all data is gathered, build a graph using it
}
You issued the new APICall().execute(); to request data and update the dataStack and you expect to get the dataStack results 'immediately' inside the same function loadResults()? It's not possible.
One solution is to remove the buildGraph() in loadResults() to inside onPostExecute().
I referenced a question here about how one might approach (outside of Google Play) having an app essentially update itself. For testing, I simply wanted to try to see if I could get it to download and install. Unfortunately, I get a parse error.
I would greatly appreciate any help:
A snippet from the class that calls the AsyncTask class:
public class downloadReceiver extends BroadcastReceiver {
private Context context;
private long localUpdate;
private long remoteUpdate = 20;
#Override
public void onReceive(final Context c, Intent i) {
new Thread(new Runnable() {
#Override
public void run() {
SharedPreferences preferences = c.getSharedPreferences("config", c.MODE_PRIVATE);
final String store = preferences.getString("store", "");
final String id = preferences.getString("id", "");
final long lastUpdated = preferences.getLong("updated", 0);
// autoUpdate app
appUpdater updater = new appUpdater(c);
try {
updater.execute(new URL("http://midamcorp.com/myApp.php"));
} catch (Exception e) {Log.e(this.getClass().toString(), " " + e.getMessage()); }
and the appUpdater class:
public class appUpdater extends AsyncTask<URL, String, String> {
private Context c;
public appUpdater(Context context) {
this.c = context;
}
protected String doInBackground(URL... appUrl) {
String location = c.getFilesDir() + "/app.apk";
try {
URL url = appUrl[0];
URLConnection con = url.openConnection();
con.connect();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(location);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.close();
input.close();
} catch(Exception e){
Log.e(this.getClass().toString(), " " + e.getMessage());
}
return location;
}
#Override
protected void onPostExecute(String saveLocation) {
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
Log.i("Location of app is: ", " " + saveLocation);
i.setDataAndType(Uri.fromFile(new File(saveLocation)), "application/vnd.android.package-archive");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
c.startActivity(i);
}
}
Please note, the URL is linked to a PHP file that forces a download because the server I have it on has trouble with .apk files.
Your primary problem is that the installer does not have access to your portion of internal storage (getFilesDir()). Use external storage.
I also recommend that you call flush(), getFD().sync(), and close() in succession on your FileOutputStream, before trying to install the app.
My Delphi XE7 project needs to communicate with the FTDI FT311 Android Accessory Chip. They helpfully provide an Android demo that includes their JAVA driver FT311I2CInterface.java(shown later in this post). Presuming that I needed to convert this file to OP I followed the instructions for using the Java2OP.exe command line tool making the necessary path addition to point to the JDK (which seems to get installed by XE7) SET PATH=%PATH%;C:\Program Files\Java\jdk1.7.0_25\bin
With everything in the same folder I ran the tool with:
java2op.exe -unit FT311I2CInterface.java
received no errors and obtained an output file FT311I2CInterface.java.pas. However this output file has an empty class in it as follows:
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FT311I2CInterface.java;
interface
uses
Androidapi.JNIBridge;
type
// ===== Forward declarations =====
// ===== Interface declarations =====
implementation
procedure RegisterTypes;
begin
end;
initialization
RegisterTypes;
end.
Can anyone suggest what I am doing wrong please?
The original JAVA file as supplied is as follows:
//User must modify the below package with their package name
package com.I2CDemo;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Toast;
/******************************FT311 GPIO interface class******************************************/
public class FT311I2CInterface extends Activity
{
private static final String ACTION_USB_PERMISSION = "com.I2CDemo.USB_PERMISSION";
public UsbManager usbmanager;
public UsbAccessory usbaccessory;
public PendingIntent mPermissionIntent;
public ParcelFileDescriptor filedescriptor;
public FileInputStream inputstream;
public FileOutputStream outputstream;
public boolean mPermissionRequestPending = false;
public boolean READ_ENABLE = true;
public boolean accessory_attached = false;
public handler_thread handlerThread;
private byte [] usbdata;
private byte [] writeusbdata;
private int readcount;
private byte status;
private byte maxnumbytes = 60;
public boolean datareceived = false;
public Context global_context;
public static String ManufacturerString = "mManufacturer=FTDI";
public static String ModelString = "mModel=FTDII2CDemo";
public static String VersionString = "mVersion=1.0";
/*constructor*/
public FT311I2CInterface(Context context){
super();
global_context = context;
/*shall we start a thread here or what*/
usbdata = new byte[64];
writeusbdata = new byte[64];
/***********************USB handling******************************************/
usbmanager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
// Log.d("LED", "usbmanager" +usbmanager);
mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
context.registerReceiver(mUsbReceiver, filter);
inputstream = null;
outputstream = null;
}
/*reset method*/
public void Reset()
{
/*create the packet*/
writeusbdata[0] = 0x34;
writeusbdata[1] = 0x00;
writeusbdata[2] = 0x00;
writeusbdata[3] = 0x00;
writeusbdata[4] = 0x00;
/*send the packet over the USB*/
SendPacket(5);
}
/*SetFrequency*/
public void SetFrequency(byte freq)
{
/*check for maximum and minimum freq*/
if(freq > 92)
freq = 92;
if (freq < 23)
freq = 23;
/*create the packet*/
writeusbdata[0] = 0x31;
switch(freq)
{
case 23:
writeusbdata[1] = 10;
break;
case 44:
writeusbdata[1] = 21;
break;
case 60:
writeusbdata[1] = 30;
break;
default:
writeusbdata[1] = 56;
break;
}
writeusbdata[2] = 0x00;
writeusbdata[3] = 0x00;
writeusbdata[4] = 0x00;
/*send the packet over the USB*/
SendPacket(5);
}
/*write data*/
public byte WriteData(byte i2cDeviceAddress,byte transferOptions,
byte numBytes, byte[] buffer,
byte [] actualNumBytes)
{
status = 0x01; /*error by default*/
/*
* if num bytes are more than maximum limit
*/
if(numBytes < 1){
actualNumBytes[0] = (byte)0x00;
/*return the status with the error in the command*/
return status;
}
/*check for maximum limit*/
if(numBytes > maxnumbytes){
numBytes = maxnumbytes;
}
/*prepare the packet to be sent*/
for(int count = 0;count<numBytes;count++)
{
writeusbdata[4+count] = (byte)buffer[count];
}
/*prepare the usbpacket*/
writeusbdata[0] = 0x32;
writeusbdata[1] = i2cDeviceAddress;
writeusbdata[2] = transferOptions;
writeusbdata[3] = numBytes;
SendPacket((int)(numBytes+4));
datareceived = false;
/*wait while the data is received*/
/*FIXME, may be create a thread to wait on , but any
* way has to wait in while loop
*/
while(true){
if(datareceived == true){
break;
}
}
/*by default it error*/
status = 0x01;
/*check for the received data*/
if(usbdata[0] == 0x32)
{
/*check for return error status*/
status = usbdata[1];
/*updated the written bytes*/
actualNumBytes[0] = usbdata[3];
}
datareceived = false;
return status;
}
/*read data*/
public byte ReadData(byte i2cDeviceAddress,byte transferOptions,
byte numBytes, byte[] readBuffer,
byte [] actualNumBytes)
{
status = 0x01; /*error by default*/
/*should be at least one byte to read*/
if(numBytes < 1){
return status;
}
/*check for max limit*/
if(numBytes > maxnumbytes){
numBytes = maxnumbytes;
}
/*prepare the packet to send this command*/
writeusbdata[0] = 0x33; /*read data command*/
writeusbdata[1] = i2cDeviceAddress; /*device address*/
writeusbdata[2] = transferOptions; /*transfer options*/
writeusbdata[3] = numBytes; /*number of bytes*/
/*send the data on USB bus*/
SendPacket(4);
datareceived = false;
/*wait for data to arrive*/
while(true)
{
if(datareceived == true){
break;
}
}
/*check the received data*/
if(usbdata[0] == 0x33)
{
/*check the return status*/
status = usbdata[1];
/*check the received data length*/
numBytes = usbdata[3];
if(numBytes > maxnumbytes){
numBytes = maxnumbytes;
}
for(int count = 0; count<numBytes;count++)
{
readBuffer[count] = usbdata[4+count];
}
/*update the actual number of bytes*/
actualNumBytes[0] = numBytes;
datareceived = false;
}
return status;
}
/*method to send on USB*/
private void SendPacket(int numBytes)
{
try {
if(outputstream != null){
outputstream.write(writeusbdata, 0,numBytes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*resume accessory*/
public void ResumeAccessory()
{
// Intent intent = getIntent();
if (inputstream != null && outputstream != null) {
return;
}
UsbAccessory[] accessories = usbmanager.getAccessoryList();
if(accessories != null)
{
Toast.makeText(global_context, "Accessory Attached", Toast.LENGTH_SHORT).show();
}
else
{
accessory_attached = false;
return;
}
UsbAccessory accessory = (accessories == null ? null : accessories[0]);
if (accessory != null) {
if( -1 == accessory.toString().indexOf(ManufacturerString))
{
Toast.makeText(global_context, "Manufacturer is not matched!", Toast.LENGTH_SHORT).show();
return;
}
if( -1 == accessory.toString().indexOf(ModelString))
{
Toast.makeText(global_context, "Model is not matched!", Toast.LENGTH_SHORT).show();
return;
}
if( -1 == accessory.toString().indexOf(VersionString))
{
Toast.makeText(global_context, "Version is not matched!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(global_context, "Manufacturer, Model & Version are matched!", Toast.LENGTH_SHORT).show();
accessory_attached = true;
if (usbmanager.hasPermission(accessory)) {
OpenAccessory(accessory);
}
else
{
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
Toast.makeText(global_context, "Request USB Permission", Toast.LENGTH_SHORT).show();
usbmanager.requestPermission(accessory,
mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {}
}
/*destroy accessory*/
public void DestroyAccessory(){
global_context.unregisterReceiver(mUsbReceiver);
if(accessory_attached == true)
{
READ_ENABLE = false;
byte i2cDeviceAddress = 1;
byte transferOptions = bOption.START_BIT;
byte numBytes = 2;
byte [] actualNumBytes = new byte[1];
byte [] readBuffer = new byte[60];
//byte deviceAddress = 1;
readBuffer[0] = 1;
ReadData(i2cDeviceAddress,transferOptions,
numBytes, readBuffer,
actualNumBytes);
try{Thread.sleep(10);}
catch(Exception e){}
}
CloseAccessory();
}
/*********************helper routines*************************************************/
public void OpenAccessory(UsbAccessory accessory)
{
filedescriptor = usbmanager.openAccessory(accessory);
if(filedescriptor != null){
usbaccessory = accessory;
FileDescriptor fd = filedescriptor.getFileDescriptor();
inputstream = new FileInputStream(fd);
outputstream = new FileOutputStream(fd);
/*check if any of them are null*/
if(inputstream == null || outputstream==null){
return;
}
}
handlerThread = new handler_thread(inputstream);
handlerThread.start();
}
private void CloseAccessory()
{
try{
if(filedescriptor != null)
filedescriptor.close();
}catch (IOException e){}
try {
if(inputstream != null)
inputstream.close();
} catch(IOException e){}
try {
if(outputstream != null)
outputstream.close();
}catch(IOException e){}
/*FIXME, add the notfication also to close the application*/
filedescriptor = null;
inputstream = null;
outputstream = null;
System.exit(0);
}
/***********USB broadcast receiver*******************************************/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
Toast.makeText(global_context, "Allow USB Permission", Toast.LENGTH_SHORT).show();
OpenAccessory(accessory);
}
else
{
Toast.makeText(global_context, "Deny USB Permission", Toast.LENGTH_SHORT).show();
Log.d("LED", "permission denied for accessory "+ accessory);
}
mPermissionRequestPending = false;
}
}
else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action))
{
CloseAccessory();
}else
{
Log.d("LED", "....");
}
}
};
/*usb input data handler*/
private class handler_thread extends Thread {
FileInputStream instream;
handler_thread(FileInputStream stream ){
instream = stream;
}
public void run()
{
while(READ_ENABLE == true)
{
try
{
/*dont overwrite the previous buffer*/
if((instream != null) && (datareceived==false))
{
readcount = instream.read(usbdata,0,64);
if(readcount > 0)
{
datareceived = true;
/*send only when you find something*/
}
}
}catch (IOException e){}
}
}
}
}
I am a beginner with Android and I am also trying to interface the FT311.
I will share my experience with Java2OP but I am not yet able to get the usbAccessory in Delphi XE7
UsbManager := TJUsbManager.Wrap(SharedActivityContext.getSystemService(TJContext.JavaClass.USB_SERVICE));
AccessoryList := UsbManager.getAccessoryList();
if ( AccessoryList <> nil ) then begin
if ( AccessoryList.Length > 0 ) then begin
Accessory := AccessoryList.Items[0]; <<<<<<< raise an illegal instruction , access violation..
end;
end;
I had many troubles to use java2op but Here are the steps I follow After googling (sorry I don't remember the urls)
create a .jar file with eclipse ADT containing the class you need (I use FT311GPIOInterface.java from the FT31 demo project supplyed by FTDI). It is not as easy because you have to split the demo app into a "android project library" (the one which will produce the .jar) and an "android project" the UI of the demo app. The .jar is build when you build and run the demo app (not when you build the android project library).
If you want to test your .jar with the UI app, you have to copy the .jar into the UI app in the directory Libs and then deploy it on the android device
I am new to eclipse, there is probably a better way to do it but ...
I saw other way to produce the .jar file
See brian long web site for another way to
Java2op : It works on a clean XP windows : I use a virtual machine, no delphi XE installed, with java jdk1.7.0_25, java2op installed, no android SDK.
my jar is ft311lib.jar
java2op -jar ft311lib.jar -unit com.poco.ft311lib
this produce com.poco.ft311lib.pas
Hope this help
According the linked documentation about this command line tool, I would do the following:
create a src/ folder and put FT311I2CInterface.java in it.
run java2op.exe with those args:
java2op.exe -source src/ -unit Android.JNI.FT311I2C
Expected output :
Android.JNI.FT311I2C.pas
The -unit arg specify the output.
The -source arg specify the input (in your case you need a java source file)
Java2OP.exe ... is a command-line tool that you
can use to generate Delphi native bridge files from Java libraries
(JAR or class files).
I suggest to check if you used the tool correctly:
java2op.exe -unit FT311I2CInterface.java
According to the documentation, -unit specifies File name of the output unit, not the input file. It also says
You must specify at least one input option that indicates what
content you want to include in the output Delphi native bridge file.
Try instead:
java2op.exe -source .
My app seems to work on most of the machines, but some just don't want to cooperate... The files on the server are fine, server itself isn't down or anything. The problem is that the app downloads all required files (up to 600KB) correctly except one (12MB). I can't figure out what is wrong. My guess is that there's something running in background that blocks the downloading thread of my app, or maybe the router blocks some of the packets? All I can see is that progress bar goes up to 4% (sometimes even up to 8!) and then stops with no errors or exceptions, while all the other downloads go up to 100% without problems. Any ideas?
Here's the class I use to download files (I've downloaded the whole 'download manager' script from http://www.java-tips.org/java-se-tips/javax.swing/how-to-create-a-download-manager-in-java.html):
class Download extends Observable implements Runnable {
private static final int MAX_BUFFER_SIZE = 1024;
public static final String STATUSES[] = { "Pobieranie", "Pauza", "OK", "Anulowany",
"Błąd" };
public static final int DOWNLOADING = 0;
public static final int PAUSED = 1;
public static final int COMPLETE = 2;
public static final int CANCELLED = 3;
public static final int ERROR = 4;
private URL url; // download URL
private int size; // size of download in bytes
private int downloaded; // number of bytes downloaded
private int status; // current status of download
// Constructor for Download.
public Download(URL url) {
this.url = url;
size = -1;
downloaded = 0;
status = DOWNLOADING;
System.err.println("==========Pobieram plik: " + url.toString());
// Begin the download.
download();
}
// Get this download's URL.
public String getUrl() {
//return url.toString();
return getFileName(url);
}
// Get this download's size.
public int getSize() {
return size;
}
// Get this download's progress.
public float getProgress() {
return ((float) downloaded / size) * 100;
}
public int getStatus() {
return status;
}
public void pause() {
status = PAUSED;
stateChanged();
}
public void resume() {
status = DOWNLOADING;
stateChanged();
download();
}
public void cancel() {
status = CANCELLED;
stateChanged();
}
private void error() {
status = ERROR;
stateChanged();
}
private void download() {
Thread thread = new Thread(this);
thread.start();
}
// Get file name portion of URL.
private String getFileName(URL url) {
String fileName = url.getFile();
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
// Download file.
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
// Open connection to URL.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
// Connect to server.
connection.connect();
// Make sure response code is in the 200 range.
if (connection.getResponseCode() / 100 != 2) {
error();
}
// Check for valid content length.
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
/*
* Set the size for this download if it hasn't been already set.
*/
if (size == -1) {
size = contentLength;
stateChanged();
}
File f = new File(Files.download_dir + Files.SEPARATOR + getFileName(url));
if (f.exists()) f.delete();
// Open file and seek to the end of it.
file = new RandomAccessFile(Files.download_dir + Files.SEPARATOR + getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
/*
* Size buffer according to how much of the file is left to download.
*/
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;
// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;
//System.out.println("Pobralem juz: " + String.valueOf(downloaded));
stateChanged();
}
/*
* Change status to complete if this point was reached because downloading
* has finished.
*/
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {
}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
}
}
}
}
private void stateChanged() {
setChanged();
notifyObservers();
}
}
(If you need more code, just let me know and I'll upload everything somewhere.)
How can I use the library to download a file and print out bytes saved? I tried using
import static org.apache.commons.io.FileUtils.copyURLToFile;
public static void Download() {
URL dl = null;
File fl = null;
try {
fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip");
copyURLToFile(dl, fl);
} catch (Exception e) {
System.out.println(e);
}
}
but I cannot display bytes or a progress bar. Which method should I use?
public class download {
public static void Download() {
URL dl = null;
File fl = null;
String x = null;
try {
fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip");
OutputStream os = new FileOutputStream(fl);
InputStream is = dl.openStream();
CountingOutputStream count = new CountingOutputStream(os);
dl.openConnection().getHeaderField("Content-Length");
IOUtils.copy(is, os);//begin transfer
os.close();//close streams
is.close();//^
} catch (Exception e) {
System.out.println(e);
}
}
If you are looking for a way to get the total number of bytes before downloading, you can obtain this value from the Content-Length header in http response.
If you just want the final number of bytes after the download, it is easiest to check the file size you just write to.
However if you want to display the current progress of how many bytes have been downloaded, you might want to extend apache CountingOutputStream to wrap the FileOutputStream so that everytime the write methods are called it counts the number of bytes passing through and update the progress bar.
Update
Here is a simple implementation of DownloadCountingOutputStream. I am not sure if you are familiar with using ActionListener or not but it is a useful class for implementing GUI.
public class DownloadCountingOutputStream extends CountingOutputStream {
private ActionListener listener = null;
public DownloadCountingOutputStream(OutputStream out) {
super(out);
}
public void setListener(ActionListener listener) {
this.listener = listener;
}
#Override
protected void afterWrite(int n) throws IOException {
super.afterWrite(n);
if (listener != null) {
listener.actionPerformed(new ActionEvent(this, 0, null));
}
}
}
This is the usage sample :
public class Downloader {
private static class ProgressListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// e.getSource() gives you the object of DownloadCountingOutputStream
// because you set it in the overriden method, afterWrite().
System.out.println("Downloaded bytes : " + ((DownloadCountingOutputStream) e.getSource()).getByteCount());
}
}
public static void main(String[] args) {
URL dl = null;
File fl = null;
String x = null;
OutputStream os = null;
InputStream is = null;
ProgressListener progressListener = new ProgressListener();
try {
fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip");
os = new FileOutputStream(fl);
is = dl.openStream();
DownloadCountingOutputStream dcount = new DownloadCountingOutputStream(os);
dcount.setListener(progressListener);
// this line give you the total length of source stream as a String.
// you may want to convert to integer and store this value to
// calculate percentage of the progression.
dl.openConnection().getHeaderField("Content-Length");
// begin transfer by writing to dcount, not os.
IOUtils.copy(is, dcount);
} catch (Exception e) {
System.out.println(e);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
}
}
commons-io has IOUtils.copy(inputStream, outputStream). So:
OutputStream os = new FileOutputStream(fl);
InputStream is = dl.openStream();
IOUtils.copy(is, os);
And IOUtils.toByteArray(is) can be used to get the bytes.
Getting the total number of bytes is a different story. Streams don't give you any total - they can only give you what is currently available in the stream. But since it's a stream, it can have more coming.
That's why http has its special way of specifying the total number of bytes. It is in the response header Content-Length. So you'd have to call url.openConnection() and then call getHeaderField("Content-Length") on the URLConnection object. It will return the number of bytes as string. Then use Integer.parseInt(bytesString) and you'll get your total.