I'm using Retrofit to download a file from the internet, and I want to do a progress bar that show the progress of the download, but I'm having problems
doing that, I was able to do a notification (is not perfect) but is working at some point.....but is like an infinity progress bar that doesn't show the progress of the download.
How can I show the progress on the progress bar?
private boolean writeResponseBodyToDisk(ResponseBody body, String fileName) {
try {
final int progressMax = 463451606;
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, activityIntent, 0);
final NotificationCompat.Builder notification = new NotificationCompat.Builder(this, CHANNEL_2_ID)
.setSmallIcon(R.drawable.ic_cloud_download_black_24dp)
.setContentTitle("Descargando")
.setContentText("Archivo descargando")
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setContentIntent(contentIntent)
.setProgress(progressMax, 0, true);
notificationManager.notify(2, notification.build());
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
final long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.e(TAG, "Archivo " + fileSizeDownloaded + " de " + fileSize);
new Thread(new Runnable() {
#Override
public void run() {
for (int fileSizeDownloaded = 0; fileSize <= progressMax; fileSizeDownloaded++) {
}
notification.setContentText("Completado")
.setProgress(0, 0, false)
.setOngoing(false);
notificationManager.notify(2, notification.build());
}
}).start();
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
The OkHttp recipes on Github have an example of how to do this. https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
Related
I need to show the progress of the file copying process using the notification. I solved the problem but my phone was laging during the process. So how can I get rid of the lags?
I've tried to solve this problem using AsyncTask<...>. And if I tried to move the notification in the notifications panel left or right, it was moving very slowly. As the copying process was finished, the notification started behaving as a usual notification without lags.
To start copy I used
new notification().execute(myFile, null, null);
The copying class:
public class notification extends AsyncTask<File, Integer, Void> {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, "CopyMoveNotification");
int PROGRESS_MAX = 100;
int CUR_PROGRESS = 0;
public void onPreExecute(){
builder.setContentTitle("Files copying")
.setContentText("Copying in progress")
.setSmallIcon(R.drawable.ic_notification_copy)
.setPriority(NotificationCompat.PRIORITY_MAX);
builder.setProgress(PROGRESS_MAX, CUR_PROGRESS, false);
builder.setOngoing(true);
notificationManager.notify(1, builder.build());
}
#Override
protected Void doInBackground(File... files) {
String path = mCurPath;
File file = new File(path+File.separator+files[0].getName());
try (InputStream in = new FileInputStream(files[0])) {
try (OutputStream out = new FileOutputStream(path+File.separator+files[0].getName())) {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
CUR_PROGRESS = Math.round(100 * file.length()/files[0].length());
publishProgress(CUR_PROGRESS);
out.write(buf, 0, len);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress){
builder.setProgress(PROGRESS_MAX, CUR_PROGRESS, false);
notificationManager.notify(1, builder.build());
}
}
public class notification extends AsyncTask<File, Integer, Void> {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
int PROGRESS_MAX = 100;
private String ChannelId = "CopyMoveNotification";
private Notification notification;
public void onPreExecute() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, ChannelId);
builder.setContentTitle("Files copying")
.setContentText("Copying in progress")
.setSmallIcon(R.drawable.ic_notification_copy)
.setPriority(NotificationCompat.PRIORITY_MAX);
builder.setProgress(PROGRESS_MAX, 0, false);
builder.setOngoing(true);
notification = builder.build();
notificationManager.notify(1, notification);
createChannelIfNeeded();
}
void createChannelIfNeeded() {
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(ChannelId,
"Files copying", NotificationManager.IMPORTANCE_LOW);
channel.setDescription("Copying in progress");
channel.enableLights(false);
channel.enableVibration(false);
NotificationManager manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
}
#Override
protected Void doInBackground(File... files) {
String path = mCurPath;
File file = new File(path + File.separator + files[0].getName());
try (InputStream in = new FileInputStream(files[0])) {
try (OutputStream out = new FileOutputStream(path + File.separator + files[0].getName())) {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
int CUR_PROGRESS = Math.round(100f * file.length() / files[0].length());
publishProgress(CUR_PROGRESS);
out.write(buf, 0, len);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
if (Build.VERSION.SDK_INT >= 24){
Notification.Builder build = Notification.Builder.recoverBuilder(mContext, notification);
build.setProgress(100, progress[0],false);
}else{
notification.contentView.setProgressBar(android.R.id.progress,100,progress[0],false);
}
notificationManager.notify(1, notification);
}
}
Please help me to add update code to my app to be update from my server thank you
nothing worked from net , i need complete guide
You can't install your app without users permission and root access but you can download your applications new version from server then ask users for install. Here is an example:
{
PackageManager manager = context.getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
version = info.versionName;
if (newversion.replace(".", "") < version.replace(".", "")) {
new DownloadFileFromURL().execute("http://exampl.com/Content/files/example.apk");
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = onCreateDialog();
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
file.delete();
}
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
pDialog.setMax(lenghtOfFile / 1024);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/example.apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(total / 1024 + "");
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception ignored) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
//finish() or whatever you want
}
}
}
I am downloading a pdf file from my server.Recently I encountered that
when my internet was disconnected while the download was in progress I
couldn't open the pdf file because it was incomplete.How can I delete
a file programmatically if the download was incomplete and a file with
that extension was saved in the process? This is the code I am
currently using to download the pdf from a server.
class DownloadFileAsync extends AsyncTask<String, String, String>
{
final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
final int notify_id = 1;
final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
private String resp;
#Override
protected String doInBackground(String... params) {
int count;
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Download Status...");
builder.setContentText("Download in Progress...");
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.connect();
int lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
Log.d("FILENAME", fileName);
resp = fileName;
if (isSDPresent) {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream("sdcard/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} else {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream(getFilesDir() + "/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return params[0];
}
#Override
protected void onPostExecute(String filename) {
Log.d("PARAM", filename);
String fname = filename.substring(filename.lastIndexOf('/')+1, filename.length());
int position = Arrays.asList(pdf_url).indexOf(filename);
Log.d("Position",String.valueOf(position));
String magazine_id = magazine_names[position];
if (isSDPresent) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_imei = telephonyManager.getDeviceId();
update_info(device_imei,magazine_id);
Uri uri = Uri.parse("/storage/emulated/0/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
} else {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
Uri uri = Uri.parse(getFilesDir() + "/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected void onProgressUpdate(String... values) {
Log.d("ANDRO_ASYNC", values[0]);
progressDialog.setProgress(Integer.parseInt(values[0]));
builder.setProgress(100, Integer.parseInt(values[0]), false);
NM.notify(notify_id, builder.build());
}
}
Any help or suggestion is appreciated.Thank you.
You can just get a pointer to the file and use "delete()" method
String fileName = "my_file"; //your file name
File parentFile; //get your parent file
File myFile = new File(parentFile, fileName);
myFile.delete();
You can handle the network I/O exceptions first instead of catching "Exception".
// Exception thrown when network timeout occurs
catch (InterruptedIOException iioe)
{
System.err.println ("Remote host timed out during read operation");
}
// Exception thrown when general network I/O error occurs
catch (IOException ioe)
{
System.err.println ("Network I/O exception- " + ioe);
}
then
catch(Exception e) {System.err.println ("Exception - " + ioe);
}
When you get the network type of error, you can then check that whether the file has been created/exists and then you can delete it using the following code,
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + uri.getPath());
} else {
System.out.println("file not Deleted :" + uri.getPath());
}
}
Hope that this helps.
Based on Roee answer that I completed a bit up, here should be a working example :
class DownloadFileAsync extends AsyncTask<String, String, String> {
final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
final int notify_id = 1;
final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
private String resp;
#Override
protected String doInBackground(String... params) {
int count;
String stringToReturnToPostExecute = null;
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Download Status...");
builder.setContentText("Download in Progress...");
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.connect();
int lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
Log.d("FILENAME", fileName);
resp = fileName;
if (isSDPresent) {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream("sdcard/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} else {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream(getFilesDir() + "/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
stringToReturnToPostExecute = params[0];
}
} catch (Exception e) {
e.printStackTrace();
}
return stringToReturnToPostExecute ;
}
#Override
protected void onPostExecute(String filename) {
Log.d("PARAM", filename);
if(filename == null) {
//TODO delete your file here and dismissthe Dialog as well
}
String fname = filename.substring(filename.lastIndexOf('/')+1, filename.length());
int position = Arrays.asList(pdf_url).indexOf(filename);
Log.d("Position",String.valueOf(position));
String magazine_id = magazine_names[position];
if (isSDPresent) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_imei = telephonyManager.getDeviceId();
update_info(device_imei,magazine_id);
Uri uri = Uri.parse("/storage/emulated/0/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
} else {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
Uri uri = Uri.parse(getFilesDir() + "/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected void onProgressUpdate(String... values) {
Log.d("ANDRO_ASYNC", values[0]);
progressDialog.setProgress(Integer.parseInt(values[0]));
builder.setProgress(100, Integer.parseInt(values[0]), false);
NM.notify(notify_id, builder.build());
} }
class DownloadFileAsync extends AsyncTask<String, String, String>
{
final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
final int notify_id = 1;
final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
private String resp;
int lengthOfFile;
#Override
protected String doInBackground(String... params) {
int count;
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Download Status...");
builder.setContentText("Download in Progress...");
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.connect();
lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
Log.d("FILENAME", fileName);
resp = fileName;
if (isSDPresent) {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream("sdcard/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} else {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream(getFilesDir() + "/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return params[0];
}
#Override
protected void onPostExecute(String filename) {
Log.d("PARAM", filename);
String fname = filename.substring(filename.lastIndexOf('/')+1, filename.length());
Log.d("LENGTH OF FILE : ",String.valueOf(lengthOfFile));
int position = Arrays.asList(pdf_url).indexOf(filename);
Log.d("Position",String.valueOf(position));
String magazine_id = magazine_names[position];
if (isSDPresent) {
File f = new File("/storage/emulated/0/shatayushi/" +fname);
if (f.length()<lengthOfFile)
{
if (f.delete())
{
progressDialog.setProgress(0);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download was interrupted please try again!");
NM.notify(notify_id, builder.build());
Toast.makeText(MainActivity.this, "Download was interrupted please try again!", Toast.LENGTH_SHORT).show();
Log.d("Del","File deleted");
}else
{
Toast.makeText(MainActivity.this, "File not deleted", Toast.LENGTH_SHORT).show();
Log.d("NOTDel","File not deleted");
}
}else {
progressDialog.setProgress(0);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String device_imei = telephonyManager.getDeviceId();
// update_info(device_imei,magazine_id);
dbHandler.updateDownloadStatus(magazine_id, "YES");
Uri uri = Uri.parse("/storage/emulated/0/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} else {
File f = new File("/storage/emulated/0/shatayushi/" +fname);
if (f.length()<lengthOfFile)
{
if (f.delete())
{
progressDialog.setProgress(0);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download was interrupted please try again!");
NM.notify(notify_id, builder.build());
Toast.makeText(MainActivity.this, "Download was interrupted please try again!", Toast.LENGTH_SHORT).show();
Log.d("Del","File deleted");
}else
{
Toast.makeText(MainActivity.this, "File not deleted", Toast.LENGTH_SHORT).show();
Log.d("NOTDel","File not deleted");
}
}else
{
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
Uri uri = Uri.parse(getFilesDir() + "/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected void onProgressUpdate(String... values) {
Log.d("ANDRO_ASYNC", values[0]);
progressDialog.setProgress(Integer.parseInt(values[0]));
builder.setProgress(100, Integer.parseInt(values[0]), false);
NM.notify(notify_id, builder.build());
}
}
I finally figured it out Sorry #Rotwang and thank you #user3793589.
I simply want to download mp4 or .3gp files from server to android device. I have tried multiple ways to achieve but in some cases it gives IOException and some time give ProtocolException
First Method to download Video using DownloadVideoTask.class
public class DownloadVideoTask extends AsyncTask<String, Integer, Boolean>
{
String nameOfSong;
Context context;
Boolean flage = true;
ProgressDialog progressDialog2;
#SuppressLint("InlinedApi")
public DownloadVideoTask(Context context,String trackTitle)
{
this.context = context;
nameOfSong = trackTitle;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
progressDialog2 = new ProgressDialog(context, AlertDialog.THEME_HOLO_LIGHT);
}
else
{
progressDialog2 = new ProgressDialog(context);
}
progressDialog2.setIndeterminate(false);
progressDialog2.setMax(100);
progressDialog2.setTitle("Please wait...");
try
{
progressDialog2.setMessage("Downloding.. " + nameOfSong.substring(0, 20));
}
catch (Exception e)
{
progressDialog2.setMessage("Downloding Song...." );
}
progressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog2.show();
}
#Override
protected Boolean doInBackground(String... params)
{
/* String trackTitle = params[0];
nameOfSong = trackTitle;
*/
String trackUrl = params[0];
try
{
File root;// = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
root = Environment.getExternalStorageDirectory();
}
else
{
root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
File dir = new File(root.getAbsolutePath() + "/XarDownloder");
if (dir.exists() == false)
{
dir.mkdirs();
}
URL url = new URL(trackUrl);
File file = new File(dir, nameOfSong);
URLConnection urlConnection = url.openConnection();
int fileLength = urlConnection.getContentLength();//ye statement inputStream k bad likhi thi
InputStream inputStream = urlConnection.getInputStream();
OutputStream outputStream = new FileOutputStream(
root.getAbsolutePath() + "/XarDownloder/" + nameOfSong
+ ".mp4");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
try
{
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
else
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))));
}
context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.fromFile(file)));
}
catch (Exception e)
{
}
return true;
}
catch (IOException e)
{
flage = false;
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if (result)
{
try
{
Toast.makeText(context,
nameOfSong.substring(0, 30) + "Downloaded...",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(context,
"Song Downloaded...",
Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(context, "Sorry, song is not downloadable",
Toast.LENGTH_LONG).show();
}
progressDialog2.dismiss();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
progressDialog2.setProgress(values[0]);
}
}
Second Method using DownloadFile
public class DownloadFile extends AsyncTask<String, Integer, String>
{
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
public DownloadFile()
{
}
#Override
protected String doInBackground(String... params)
{
int count;
try
{
mp4load(videoToDownload);
}
catch (Exception e)
{
// TODO: handle exception
}
/*try
{
URL url = new URL(videoToDownload);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/xarwere/firstdownload.mp4");
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();
}
catch (Exception e)
{
e.printStackTrace();
}*/
return null;
}
public void mp4load(String urling)
{
try
{
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
//Log.v(LOG_TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "test.mp4";
File outputFile = new File(file, fileName);
if (!outputFile.exists())
{
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();//my doctory
InputStream is = con.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 (MalformedURLException e)
{
e.printStackTrace();
}
catch (ProtocolException e)
{
e.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
Where videoToDownload in DownloadFile.class is the URLi want to download. but at inputStream it gives exception.
And I call these AsyncTask like
new DownloadFile().execute();
new DownloadVideoTask(TestingActivity.this, "nameofsong").execute("http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4");
I slighthly modified your code, but it downloads the file well. Did you add the internet permission?
public class DownloadFile extends AsyncTask<String, Integer, String> {
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
#Override
protected String doInBackground(String... params) {
int count;
try {
mp4load(videoToDownload);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
public void mp4load(String urling) {
try {
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = "test.mp4";
File outputFile = new File(downloadsPath, fileName);
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();
InputStream is = con.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) {
e.printStackTrace();
}
}
}
following is my code,
From Activity class
Intent intent = new Intent(this, DownloadService.class);
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.setData(Uri.parse("http://www.abc.ezy.asia/E-MobApps/op.apk"));
intent.putExtra("urlpath", "http://www.abc.ezy.asia/E-MobApps/op.apk");
startService(intent);
I have overrided Service Class method onHandle Event
// DownloadService Class
#Override
protected void onHandleIntent(Intent intent) {
Uri data = intent.getData();
String urlPath = intent.getStringExtra("urlpath");
String fileName = data.getLastPathSegment();
File output = new File(Environment.getExternalStorageDirectory(),fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
fos = new FileOutputStream(output.getPath());
byte dataB[] = new byte[1024];
InputStreamReader reader = new InputStreamReader(stream);
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
fos.flush();
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = output.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
}
In above code I used File Streams & Input stream reader for downloading
when tried to download html file then complete file was downloaded to my sdcard.But when I tried for APK. The File downloaded of 2.2 mb instead of 2.4 mb Parsing problem is there. Kindly help me to resolve the issue.
try this piece of code :
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(output.getPath());
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
input.close();
result = Activity.RESULT_OK;