Android download apk file and save to INTERNAL STORAGE - android

I have been stuck for days when developing a function that allow user to check for new app update (I use local server as my distribution point).
The problem is the downloading progress seems working perfectly but I could not find the downloaded file anywhere in my phone (i have no sd card / external memory).
Below is what i have came so far.
class DownloadFileFromURL extends AsyncTask<String, String, String> {
ProgressDialog pd;
String path = getFilesDir() + "/myapp.apk";
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(DashboardActivity.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(true);
//pd.setIndeterminate(true);
pd.show();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return path;
}
protected void onProgressUpdate(String... progress) {
pd.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
if (pd!=null) {
pd.dismiss();
}
// i am going to run the file after download finished
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(new File(file_url)), "application/vnd.android.package-archive" );
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d("Lofting", "About to install new .apk");
getApplicationContext().startActivity(i);
}
}
After the progress dialog reach 100% and dismissed, I could not find the file. I assume that's the reason application cannot continue install downloaded apk.
Did I miss some code ?

I can not believe i solved this.
What I do is replacing:
getFilesDir()
to
Environment.getExternalStorageDirectory()
below I post my final code
class DownloadFileFromURL extends AsyncTask<String, String, String> {
ProgressDialog pd;
String pathFolder = "";
String pathFile = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(DashboardActivity.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(true);
pd.show();
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
pathFolder = Environment.getExternalStorageDirectory() + "/YourAppDataFolder";
pathFile = pathFolder + "/yourappname.apk";
File futureStudioIconFile = new File(pathFolder);
if(!futureStudioIconFile.exists()){
futureStudioIconFile.mkdirs();
}
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lengthOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
FileOutputStream output = new FileOutputStream(pathFile);
byte data[] = new byte[1024]; //anybody know what 1024 means ?
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return pathFile;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pd.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
if (pd!=null) {
pd.dismiss();
}
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(new File(file_url)), "application/vnd.android.package-archive" );
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(i);
}
}
Simply put this code to use this class
new DownloadFileFromURL().execute("http://www.yourwebsite.com/download/yourfile.apk");
This code can perform file download to your internal phone storage with a progress bar and continue asking your permission for application install.
Enjoy it.

as we know getFilesDir() returns the absolute path to the directory on the filesystem where files created, which will give you path /data/data/your package/files
so you can find the file(if downloaded completely) there
i suggest you to read this article:
How to get the each directory path

Related

How to hide the browser when downloading files from online

I am trying to download a file from an online source of mine. The issue I am having is that the browser window keeps appearing as it load into the download server. Is there some way that I may be able to hide this? I already have this code below in the doInBackground portion of an AsyncTask, but cant seem to get it to hide the browser bar. Here is my code at this point:
private class getErDone extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setTitle("Downloading Software");
progressDialog.setMessage("Now Updating, DO NOT TURN OFF DEVICE");
progressDialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try{
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("http://mydownloadlink.com/myfile?dl=1"));
//**Note** As convincing as it seems, this is not the real download link
startActivity(goToMarket);
}catch (UnknownError e){
e.printStackTrace();
}
/*catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException t){
t.printStackTrace();
}*/
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
Thanks everyone!
here is sample from my code, download without browser:
private TextView mFileDownloadProgressBarPercent;
private ProgressBar mFileDownloadProgressBar;
private Runnable mFileExecutionTaskAfterDownload;
public String fileDownloadedResultPath;
and asynctask:
class DownloadFileFromURL extends AsyncTask<String, String, String> {
// Before starting background thread
// Show Progress Bar Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.VISIBLE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.VISIBLE);
}
// Downloading file in background thread
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf"); // for example we are downloading pdf's so store in pdf dir.
folder.mkdir();
File subFolder = new File(extStorageDirectory+"/pdf", "fileId"); // here you can place files by id of category etc..
subFolder.mkdir();
String fileName = url.toString().substring(url.toString().lastIndexOf("/")+1);
fileDownloadedResultPath = subFolder + "/" + fileName;
// Output stream to write file
OutputStream output = new FileOutputStream(subFolder + "/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setProgress(Integer.parseInt(progress[0]));
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setText(mContext.getString(R.string.downloading_file) + " " + String.format("%s%%",Integer.parseInt(progress[0])+""));
}
#Override
protected void onPostExecute(String file_url) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.GONE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.GONE);
if(mFileExecutionTaskAfterDownload != null)
mFileExecutionTaskAfterDownload.run();
}
}

How to upload and download images into server from android using phpmyadmin and json?

I mean, to my local host database.
Please help me.
Find this link.It contain both code of Android and Php for image uploading.
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
Image Downloading:
call this method in onCreate and mImageUrl is your url to download image
new DownloadImage().execute(mImageUrl);
class DownloadImage extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... mImageUrl) {
int count;
try {
URL url = new URL(mImageUrl[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedImage.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String mImageUrl) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedImage.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}

Android , Check if the file transfer has been successful

I have an android app which downloads a video by clicking a button and saves it on user's device. when users click on the button the app checks if the video is in users' device, and if it is not it downloads the video and if it has been downloaded the app just plays the video without the need to download.
However when the download crashes the file is there , but the app can't plays it and gets tricked that the file has been downloaded already.
I wanted to ask if there are any ways to check if the download process has crashed or the file is corrupted.
Thanks
You can use AsyncTask as below to check if the download was interupted or not.
Below code is just for example purpose
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
initialText.setText(getString(R.string.connecting));
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String fileURL = f_url[0];
if (fileURL.contains(" ")) {
fileURL = fileURL.replace(" ", "%20");
}
URL url = new URL(fileURL);
filename = f_url[0].substring(fileURL.lastIndexOf("/") + 1);
URLConnection connection = url.openConnection();
connection.connect();
// getting file length
int lengthOfFile = connection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File file = new File(FilePath);
if (!file.exists()) {
if (!file.isDirectory()) {
file.mkdirs();
}
}
// Output stream to write file
OutputStream output = new FileOutputStream(FilePath + filename);
byte data[] = new byte[1024];
long total = 0;
runOnUiThread(new Runnable() {
#Override
public void run() {
setSubTitle(getString(R.string.downloading));
initialText.setText(ad_tv_initialText.getText().toString() + getString(R.string.connected));
}
});
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
return "SUCCESS";
} catch (Exception e) {
return "FAILED";
}
}
protected void onProgressUpdate(String... progress) {
progress.setProgress(Integer.parseInt(progress[0]));
progressText.setText(progress[0] + " %");
}
#Override
protected void onPostExecute(String result) {
if (result.equals("SUCCESS")) {
takeDecisionToPlay();
} else if (result.equals("FAILED")) {
setSubTitle(getString(R.string.failed_));
finalText.setText(getString(R.string.failed));
}
}
}

Android : Download and Share html file issue

In my application I want to download and share one html file. so I tried the following code:
Button download = (Button) findViewById(R.id.downloadbtn);
download.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String file_url= "/* http url*/";
new DownloadFileFromURL().execute(file_url);
}
});
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
String filePath = Environment.getExternalStorageDirectory().toString() + "/sridhar.html";
// Output stream to write file
OutputStream output = new FileOutputStream(filePath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
goShare();
}
}
public void goShare(){
String filePath = Environment.getExternalStorageDirectory().toString() + "/sridhar.html";
// setting downloaded into image view
Log.e("Downloaded path","Path is "+filePath);
Uri fileuri = Uri.fromFile(getFileStreamPath(filePath));
// MimeTypeMap myMime = MimeTypeMap.getSingleton();
//String mimeType = myMime.getMimeTypeFromExtension("html");
//File file = new File(imagePath);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
// shareIntent.setDataAndType(Uri.fromFile(file),mimeType);
// shareIntent.setFlags(shareIntent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, fileuri);
shareIntent.setType("text/html");
startActivity(Intent.createChooser(shareIntent,"Share"));
}
The problem is , I can able to download my html file but i cant share that ...
i.e I can able to bring the share context menu and selecting gmail, the file is not accepted by gmail app and it forces the gmail app close.
And also the progress bar is not working...
Please provide me the best way to share the downloaded file..
I have found the solution :
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filePath)));
shareIntent.setType("text/html");
startActivity(Intent.createChooser(shareIntent,"Share"));

onDownload complete notification - inapp purchase in Android

In my Android application I am downloading a video through an application purchase from Urban Airship.
When I click a particular button in my application the downloading gets started. In such a case, after the download completes fully I want to get a notification or alert so that the button becomes invisible. How can I know that the video has been downloaded completely?
Is there any piece of code I could write to be notified when a download finishes in Android?
private void startDownload() {
String url = PUT HERE YOUR URL;
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
// mProgressDialog.setIcon(R.drawable.icon);
mProgressDialog.setIcon(R.drawable.tab_icon_pitchforkfm);
mProgressDialog.setTitle("Downloading file... "
+ GlobalVariable.Getstrpath().toString());
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
/**
* This is used for downloading the file in the background
* process.
*/
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub.
// mp3load();
int len1 = 0;
int count;
try {
URL url = new URL(GlobalVariable.Getstr());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
String PATH = Environment.getExternalStorageDirectory() +
"/download/";
Log.v(LOG_TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
// String fileName = "workTest.mp3";
String fileName = "TEST.mp3";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
long total = 0;
while ((count = is.read(buffer)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// fos.write(buffer, 0, len1);
fos.write(buffer, 0, count);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d(LOG_TAG, "Error: " + e);
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
//refreshList();
Toast.makeText(
FindFilesByType.this,
"Downloading of " + fileName + " complete.",
Toast.LENGTH_LONG).show();
//Put your code here. That is, button visible/invisible code, etc. This indicates
//that the file download has completed..
refreshList();
}
}
}
I think you are implementing a thread to download the video. But I suggest implementing the same with AsyncTask (also known as painless threading).
If you use AsyncTask then you need to take care of thread management. For your case, implement the AsyncTask as below.
Do all the downloading tasks inside the doInBackground() method of AsyncTask and implement alert/notification or whatever you want to show inside the onPostExecute() method of AsyncTask.
You should use AsyncTask for that.

Categories

Resources