I want to update my application automatically
This is the code i am using
public void Update(String apkurl){
try {
URL url = new URL(apkurl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "DeliverReceipt.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();//till here, it works fine - .apk is download to my sdcard in download file
/*Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/apk/" + "DeliverReceipt.apk")), "application/vnd.android.package-archive");
startActivity(intent); //installation is not working
*/
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Update error!", Toast.LENGTH_LONG).show();
}
}
The downloaded file is just 20kb size, which is less than the original
how can i solve this problem?
thank you
*noted : if i try this url in browser it's work, an apk can be downloaded
You should probably flush before you close the file, using fos.flush()
Related
I am generating an android application which capable to include over-the-air updation in the android application. So that I am generating a Webservice for getting the versioncode so that I will compare the versioncode of installed application if it is lesser then I will trigger there is an update to install from the server, for this I using below code.
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "yourapp.apk");
downloadFile(file_url, outputFile);
installApk();
//downloadfile function
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("FileNotFoundException",e+"");
return;
} catch (IOException e) {
Log.e("IOException",e+"");
return;
}
}
//install apk file function
private void installApk(){
Intent installer = new Intent();
installer.setAction(android.content.Intent.ACTION_VIEW);
installer.putExtra(Intent.ACTION_PACKAGE_REPLACED, "org.wannatrak.android");
installer.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "yourapp.apk")), "application/vnd.android.package-archive");
installer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(installer);
}
I am generating an android application which capable to include over-the-air updation in the android application. So that I am generating a Webservice for getting the versioncode so that I will compare the versioncode of installed application if it is lesser then I will trigger there is an update to install from the server, for this I using below code.
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "yourapp.apk");
downloadFile(file_url, outputFile);
installApk();
//downloadfile function
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("FileNotFoundException",e+"");
return;
} catch (IOException e) {
Log.e("IOException",e+"");
return;
}
}
//install apk file function
private void installApk(){
Intent installer = new Intent();
installer.setAction(android.content.Intent.ACTION_VIEW);
installer.putExtra(Intent.ACTION_PACKAGE_REPLACED, "org.wannatrak.android");
installer.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "yourapp.apk")), "application/vnd.android.package-archive");
installer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(installer);
}
The above works well upto 4.0 versions.If i try it in the jelly bean I am getting "There is a parse error in a package error" Please help me to solve this issues
Thanks.
You need to give read permission to your apk file. In the install apk file function, add:
File file = new File(Environment.getExternalStorageDirectory() + "/download/" + "yourapp.apk")
file.setReadable(true, false);
installer.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
I'm trying to programmatically download an .apk file from a given URL and then install it, but I am getting a FileNotFoundException. What could be a possible reason for the issue?
try {
URL url = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "VersionUpdate.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
**//Getting error in this line**
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.flush();
fos.close();
is.close();
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file:///sdcard/download/VersionUpdate.apk"),"application/vnd.android.package-archive");
startActivity(intent);
}
You just replaced by InputStream is = c.getInputStream(); to given code.
InputStream is ;
int status = c.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
is = c.getErrorStream();
else
is = c.getInputStream();
Try the following code
File outputFile = new File(file, "VersionUpdate.apk");
if(!outputFile.exists())
{
outputFile.createNewFile();
}
What you are doing is deleting the file, when it already exist, then FileOutputStream will not get file where you want to download the apk .
If the file already exist, FileOutputStream will override the content with new update.
If you have queries, do ask!!
try {
URL url = new URL("http://URL/Dragonfly.db");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String[] path = url.getPath().split("/");
String _file = path[path.length - 1];
int lengthOfFile = c.getContentLength();
if(lengthOfFile > 0){ // Copy file if Length > 0
String PATH = db.DB_PATH; ;//Environment.getExternalStorageDirectory()+
Log.v("", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "Dragonfly.db";
File outputFile = new File(file , fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}else{
TestAdapter mDbHelper = new TestAdapter(getBaseContext());
mDbHelper.createDatabase();
}
} catch (IOException e) {
e.printStackTrace();
}
I use this code to update database, downloading a new one. but if i dont have a file on server, it replace the database i have for a new empty one (0bytes).
How can i download the file just if it exist on server?
Try to do a status response check:
int responseCode = c.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
{
// update database replacing the old one with the new one
} else {
// continue to use old database
}
I having problem with file download,
I am able to download file in emulator but It is not working with the phone.
I have defined the permission for the Internet and write SD card.
I having one doc file on server, and if user click on download. It downloads the file. This works fine in emulator but not working in phone.
Edit
My code for download file
public void downloadFile(String _url, String fileName) {
File PATH = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
PATH.mkdirs();
URL url = new URL(_url); // you can write here any link
File file = new File(PATH, fileName);
long startTime = System.currentTimeMillis();
Log.d("Manager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
try the snippets given bellow...
File PATH = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
_url = _url.replace(" ", "%20");
URL url = new URL(_url);
//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();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(PATH,fileName);
//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();
Log.i("Download", totalSize+"");
//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);
}
//close the output stream when done
fileOutput.close();
return true;
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
make sure you have enters the correct download path(url)
In my application, the user needs to download PDF file from an url and store it on sdcard.
But the catch here is I can only use DefaultHttpClient to access the url.
I found couple of solutions but none used DefaultHttpClient.
After downloading the PDF, I would also likie to view the PDF in my application.
//use this method to download the pdf file
public void downloadPdfContent(String urlToDownload){
try {
String fileName="xyz";
String fileExtension=".pdf";
// download pdf file.
URL url = new URL(urlToDownload);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName+fileExtension);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("--pdf downloaded--ok--"+urlToDownload);
} catch (Exception e) {
e.printStackTrace();
}
}
// for viewing the pdf use this method
private void onPdfClick()
{
// String pdfFile = Environment.getExternalStorageDirectory()+ File.separator + AstroManager.file.getName();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/mydownload/xyz.pdf"), "application/*");
startActivity(intent);
}
If you have to open pdf file, pdf reader must have to be installed in your device.Otherwise it will show blank screen.
Also here is good example to download pdf from server and view its contents.
see http://developer.android.com/reference/org/apache/http/client/methods/HttpGet.html for retreiving data from a url with a DefaultHttpClient