How to download and automatic install apk from url in android - android

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!!

Related

video download from google+/picasa android

We have a requirement to download video from google+/picasa and store it into sdcard.
Can you please any one help me to solve this issue?
google+/picasa
Converting from URI to byte[], then byte[] is stored to file:
InputStream videoStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(videoStream );
videoFile = new File("abcd.mp4");
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
Can you try that one :
public String DownloadFromUrl(String DownloadUrl, String fileName) {
File SDCardRoot = null;
try {
SDCardRoot = Environment.getExternalStorageDirectory();
File files = new File(SDCardRoot+fileName);
int sizeoffile;
if(!files.exists())
{
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath());
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl);
File file = new File(dir, fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
sizeoffile = ucon.getContentLength();
Log.d("SIZEOFFILE: ", sizeoffile+" BYTE");
/*
* 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(5000);
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.flush();
fos.close();
}
}
catch (IOException e) {
e.getMessage();
}
return SDCardRoot+fileName; }
Finally i found the solution.
Uri videoUri = data.getData();
File videoFile = null;
final InputStream imageStream;
try {
imageStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(imageStream);//IStoByteArray(imageStream);
videoFile = new File(Environment.getExternalStorageDirectory()+ "/"+System.currentTimeMillis()+".mp4");
videoFile.createNewFile();
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}
I have recently encountered this.
I first discovered that what I'm receiving is a picture rather than a video.
But I didn't understand why Facebook is successfully playing the online video I shared via (Google+'s) Photo.
I then occasionally discovered that the file they're currently giving is a GIF with the original extension in the MediaStore.Images.Media.DISPLAY_NAME section of the contentUri.
Eeek!

android file download from Internet gives an exception

I am trying to download file form Internet. I have given all permission.But my apps gives some Exception. Here is my source code ..........
private void write()
{
try {
URL url = new URL("http://wordpress.org/plugins/about/readme.txt");
// URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
// c.setReadTimeout(10000); // millis
// c.setConnectTimeout(15000); // millis
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
String fileName = "Sap.txt";
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();
// }
} catch (IOException e) {
MessageBox(e.getMessage());
}
}
//permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
c.connect(); // this connect() function gives an exception. I can't identify the problem.
Please somebody help me....
add this in main function
new AsyncTaskRunner().execute("");
add below after main function
private class AsyncTaskRunner extends AsyncTask<String, String, String>
{
#Override
protected void onPostExecute(String result) {
try
{
MessageBox(result);
/*
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
String fileName = "Sap.txt";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c;
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
*/
}
catch(Exception ex)
{
MessageBox(ex.getMessage()+"error ");
}
}
#Override
protected String doInBackground(String... params) {
try
{
URL url = new URL("http://wordpress.org/plugins/about/readme.txt");
// URL url = new
// URL("http://androidsaveitem.appspot.com/downloadjpg");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
// c.setReadTimeout(10000); // millis
// c.setConnectTimeout(15000); // millis
//c.setDoOutput(true);
c.connect();
InputStream is = c.getInputStream();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
String fileName = "Sap.txt";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
//InputStream is = c;
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Log.v("esty", "Successfully");
return "Successfully";
}
catch(Exception ex)
{
Log.v("esty", ex.getMessage());
return "failed"+ex.getMessage();
}
}
i hope it solves your problem! :)

Android download even if does not exist

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
}

Android: downloaded file size less than its actual size

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()

Downloading a PDF file

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

Categories

Resources