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"));
Related
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
the code is downloading file from url and save that in external storage
work on android 4 - 4.4 but not work on android 5.1
why?
this is my code:
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#SuppressWarnings("deprecation")
#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 lengthOfFile = 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(zippath);
// /sdcard/downloadedfile.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)/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 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
* **/
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String src) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
try {
Toast.makeText(getApplicationContext(), "download finished", Toast.LENGTH_LONG).show();
Intent ii=new Intent(Download.this,Setpic.class);
startActivity(ii);
//
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), ""+e, 5000).show();
}
}
}
and
new DownloadFileFromURL().execute(src);
more details
more details
more details
more details
more details
The code you are referencing ("URLConnection") is deprecated, which means it is no longer available in the latest versions of Android. You shouldn't just supress the warning and ignore the message.
The answer has been given here already: HttpEntity is deprecated on Android now, what's the alternative?
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));
}
}
}
In my android app i need to download a file into my SD card and view it through intents, I'm using volley library for all network calls in my application.
Ideas.
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();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.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;
}
/**
* 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);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
}
}
}
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.