I want to install the update automatically as my APK is not on the Play store. So I tried the following:
I followed all the steps given in
http://www.wepstech.com/download-and-install-app-programmatically/
Below is the Async Task: (URL given is correct)
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
String PATH = Objects.requireNonNull(mContext.getExternalFilesDir(null)).getAbsolutePath();
File file = new File(PATH);
boolean isCreate = file.mkdirs();
File outputFile = new File(file, "my_apk.apk");
if (outputFile.exists()) {
boolean isDelete = outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1;
long total = 0;
while ((len1 = is.read(buffer)) != -1) {
total += len1;
fos.write(buffer, 0, len1);
publishProgress((int) ((total * 100) / lenghtOfFile));
}
fos.close();
is.close();
if (mPDialog != null)
mPDialog.dismiss()
;
I have an API checking the version and if the version is old I have given a button to download and install, So when I do that the apk is getting downloaded only (but not a full-size file) I see only 189bytes. The Async just closes thinking the file has downloaded it starts to install and when it does it gives "There was a problem parsing the package".
It is because the APK file not downloaded fully.
I am not sure why the file is not getting downloaded fully. It is an 8MB file. And I am running Android 11.
you can use the lib fetch, it's a best file downloader library for android
https://github.com/tonyofrancis/Fetch
Related
i m making an android app to download pdf files from android and then saving them in a folder in internal or external memory.but sometime due to bad internet connection download stops without finshing .like file size is 1.1mb and its only downloaded upto 750kb. now the problem is whether file fully download or not my app showing it as download but in real it is not.so i want to know the exact size of file befor and after download so that i can found whether file is completely download or not.and want to restart the download.
can anybody help me........
my code
String DownloadUrl = "http://www.example.com/books/"+book_name;
String fileName = book_name;
URL url = new URL(DownloadUrl);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
// File SDCardRoot = new File("/storage/emulated/0/documents/docx/stuff/");
File SDCardRoot = new File(Environment.getExternalStorageDirectory()+File.separator+"MybookStore/paper/paperStuff/documents/docx/other/stuff/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,fileName);
String file_size = Long.toString(file.length()/1024);
int size_file=Integer.parseInt(file_size);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
my code
Any reasonable server response header will include a Content-Length key, which will hopefully denote the full length of the resource you’re trying to download.
With that in mind, here's a quick example:
HttpURLConnection connection = null;
InputStream input = null;
OutputStream output = null;
try {
final URL url = new URL(resourceUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
final int length = connection.getContentLength();
int downloaded = 0;
input = url.openStream();
output = new FileOutputStream(targetFile);
final byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
downloaded += read;
}
if (downloaded == length) {
// The file was successfully downloaded.
} else {
// The file was not fully downloaded.
}
} catch (IOException e) {
// Handle exception.
} finally {
// Close resources.
}
my code works fine, it downloads image to sd card, however , i get this warning where i defined my sd card path "Do not hardcode "/sdcard/"; use Environment.getExternalStorageDirectory().getPath() instead"
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/.temp");//.temp is the image file name
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
}
the problem is, if i use the suggested solution, then i won't be able to give my downloaded file a new name (".temp")
When working with files and directories, it's better to work with File objects rather than with strings. Here's how you can address the warning:
File dir = Environment.getExternalStorageDirectory();
File tmpFile = new File(dir, ".temp");
OutputStream output = new FileOutputStream(tmpFile);
That creates a File object that points to a file named ".temp" in the environment's external storage directory. It then opens it for writing using a different constructor of the FileOutputStream class.
If you need the file path as a string instead (say, for printing), you can do that too:
String tmpFileString = tmpFile.getPath();
Or if you decide to use the java.nio API in the future and need a Path object:
Path tmpFilePath = tmpFile.toPath();
I am trying to create an app that can download music files.
How to download mp3 file in android from a URL and save it in SD card??
I use this code but lenghtOfFile always <=350:
String fileUrl = (String) params[0];
path = (String) params[1];
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
int count;
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection .connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = connection .getContentLength();
// downlod the file
input = new BufferedInputStream(url.openStream());
output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
url files :
http://snd1.tebyan.net/1391/12/08_Khaneh_D_117323.mp3
http://snd1.tebyan.net/1393/12/100_Pedar_Va_Madar_D_148797.mp3
and .....
update :
int code= connection.getResponseCode();\\302
String _result= connection.getResponseMessage();\\ found
note :
Files do download in Samsung Galaxy S3, but files do not download in Samsung tablet N8000
You could implement HMTL5 and do it from there, might need some JS...
for 302 response ,you need connection.setInstanceFollowRedirects(true) to follow it. before connection.connect()
I use below code to download file:
URL u = new URL(one.getSrcPath());
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.setReadTimeout(10000);
c.connect();
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + SavePath, FileName);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int finishbyte = 0;
long total = 0;
while((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
f.write(buffer, 0, len1);
finishbyte++;
}
f.close();
I have two problems:
First, why my download task download fail very high frequency?
Second, if I want my download task resume from break point.
I have get the finishbyte.
How can I modify?
finishbyte both does not represent any information (except the number of calls to the read method, but certainly not the size of the downloaded file), and is not relevant, since you have written to a file and can use the File.length() method to know how much you got so far.
To resume a download:
Open your file, check the size, request a range using the http header that is:
Range: <file.length()>-
(example, if you have downloaded 234 bytes:
Range: 234-
If the response code from the server is 206 Partial Content, you can append to your file, if it is 200, you have to overwrite your file (content have changed or Range is not supported)
To start downloading a file starting with finishbyte position, you will have to use the Range HTTP header. As for the failed downloads problem, it's probably a network issue or phone sleep issue, in which case you should check out the wifi lock
I am working on an API which returns me a zip file containing multiple XML files, which i have to parse individually after extracting the zip file.
Here is the link for that(will download the zip-file) :
http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=studyxml=true
Here is my current code to save the zip-file in sdcard:
File root = Environment.getExternalStorageDirectory();
String url= "http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=xml=true";
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000); // timeout 10 secs
conn.connect();
InputStream input = conn.getInputStream();
FileOutputStream fOut = new FileOutputStream(new File(root, "new.zip"));
int byteCount = 0;
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = input.read(buffer)) != -1) {
fOut.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
Problem :
New.zip File is getting created in sdcard but it seems nothing is downloading also the file size is 0kb.
Is my code proper or I have to use something else to handel zipfiles.
Edit Solved :
I am extremely sorry the api link is invalid ... it should be
http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=&studyxml=true
& is required before studtxml..
Thnx every 1 for quick response ..
There is something wrong either in your .zip file URL or in .zip file size(0 byte size) because if we download this .zip file (From URL given by you) from web browser then also its downloaded with 0 byte size.
Downloaded .zip file URL.
Your Url in the code String url=... is not giving me a zip file.
http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=xml=true
The link you provided is different
http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=studyxml=true
Looks like there's an error: lup_e=xml=true should be lup_e=studyxml=true