i am trying to download mp file in back ground using AsyncTask into the emulator it works properly.. but in divice it doesn't show the progressbar
this problem is due to the when i am running this code the
int lenghtOfFile = c.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
that gives me -1 why this happning? my code is
#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 = GlobalVariable.Getstrpath().toString();
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 " + GlobalVariable.Getstrpath()
+ " complete.", Toast.LENGTH_LONG).show();
// Intent i = new Intent(FindFilesByType.this, SongList.class);
// finish();
// startActivity(i);
try{
Intent i = new Intent(FindFilesByType.this, SongList.class);
finish();
startActivity(i);}catch (Exception e) {
// TODO: handle exception
}
}
}
the entiere code works fine for emulator
but it always doesn't display me progress but download happens sucessfully thanks Pragna
Somethimes java can't retrive the size of a remote file, and i think that is your problem.
But please check internet connection on your phone when debugging the code.
Got the same problem (on Android 4.0 only), and removing
c.setDoOutput(true);
fixed it for me.
Related
I want to update my app through local server. I have placed my application on server and through this code i am doing the task of updating it
public class UpdateClass extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
int status = 0;
private Context context;
public void onPreExecute() {
progressDialog = new ProgressDialog(Update.this);
progressDialog.setMessage("Please Wait.......");
progressDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
// String PATH = Environment.getExternalStorageDirectory() + "/Download/";
String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/";
System.out.println("path..........." + Environment.getExternalStorageDirectory());
File file = new File(dir);
file.mkdirs();
File outputFile = new File(file, "location.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();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() +
"/Download/" + "location.apk")), "application/vnd.android.package-archive");
System.out.println("path........dsffffffffffffffsdfffff..." + Environment.getExternalStorageDirectory());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (FileNotFoundException fnfe) {
status = 1;
// Toast.makeText(context, "App not Available", Toast.LENGTH_LONG).show();
Log.e("File", "FileNotFoundException! " + fnfe);
} catch (Exception e) {
// Toast.makeText(context, "App update", Toast.LENGTH_LONG).show();
Log.e("UpdateAPP", "Exception " + e);
}
return null;
}
public void onPostExecute(String unused) {
progressDialog.dismiss();
/* if (status == 1)
Toast.makeText(context, "App not Available", Toast.LENGTH_LONG).show();
}*/
}
}
the code works fine with "http://localhost/androidservices/location.apk"
but when i replace this url with my server address that is https://liveserver/androidservices/location.apk then i get file not found exception in my logcat and in mobile phone a file with same file name is downloaded which size is 0 kb. i can access the url through browser as the file is easily being downloaded when opened with browser(chrome,mozilla).
I found the solution for this query. IIS servers don't support post methods and the method this url was using was post since i had used
c.setRequestMethod("GET");
c.setDoOutput(true);
Although i was passing GET but the method used was post.I changed it to
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnectionurl.openConnection();
c.connect();
and removed setDoOutput(true) and thus the method changed to GET and program started to work smoothly.
I want to download all mp3 files from server one by one and save into sd card folder. I have no any errors or exception but mp3 does not downloaded and does not show in SD card. Can someone help how to solve this issue.Here is my code.
if (imageName.endsWith(mp3_Pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
Log.e("######### ", "str_DownLoadUrl = " + str_DownLoadUrl);
download_Mp3File(str_DownLoadUrl);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
void download_Mp3File(final String fileUrl) {
new AsyncTask<String, Integer, String>()
{
#Override
protected String doInBackground(String... arg0)
{
int count;
File file = new File(newFolder, System.currentTimeMillis() + imageName);
try
{
URL url = new URL(fileUrl);
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(file);
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) {
}
return null;
}
}.execute();
}
place a breakpoint in inputstream object to see is there any stream. then debug output stream to see the results.
I want to download MP3 audio and images from server.File is downloaded but not goes into sd card folder.Below my code is correct or not or something wrong in downloading on store into sd card folder.How to work with download media files and save into sd card folder.Thanks in advanced.
Here is my MP3 download code.
public void DownLoadAudioFile(final String mp3Url , final String strImageName) {
new AsyncTask<String, String, String>()
{
#Override
protected String doInBackground(String... f_url) {
int count;
try
{
f_url[0] = mp3Url;
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
Log.e("lenghtOfFile "," = " + lenghtOfFile);
// input stream to read file - with 8k buffer
if(lenghtOfFile > 0)
{
InputStream input = new BufferedInputStream(url.openStream(),10*1024);
// Output stream to write file in SD card
newFolder = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "classnkk_audio");
File file = new File(newFolder, strImageName);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Log.e("Audio Files", "DownLoad ans save in SD card Fully !!!");
Log.e("======================"," DownloadMusicfromInternet ======================");
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
}.execute();
}
and here is my image download code
void download_PngFile(String fileUrl, String ImageName) {
try {
URL ImgUrl = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) ImgUrl.openConnection();
conn.connect();
int lenghtOfImage_File = conn.getContentLength();
Log.e("lenghtOfImage_File "," = "+lenghtOfImage_File);
if(lenghtOfImage_File > 0)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap imagenObtenida = BitmapFactory.decodeStream(conn.getInputStream(), null, options);
File file = new File(newFolder, ImageName);
if (file.exists()) file.delete();
try
{
FileOutputStream out = new FileOutputStream(file);
imagenObtenida.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
int imagenObtenidaW = imagenObtenida.getWidth();
int imagenObtenidaH = imagenObtenida.getHeight();
Log.e("imagenObtenidaW " ," = +" + imagenObtenidaW + " imagenObtenidaH = " + imagenObtenidaH);
} catch (Exception e) {
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (imageName.endsWith(mp3_Pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/"+imageName;
DownLoadAudioFile(str_DownLoadUrl ,imageName);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
if (imageName.endsWith(png_Pattern) || imageName.endsWith(jpg_pattern) || imageName.endsWith(bmp_pattern) || imageName.endsWith(gif_pattern) || imageName.endsWith(jpeg_pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
download_PngFile(str_DownLoadUrl,imageName);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
I am creating an app for my client, one of his requirements is to download and install an external apk (size approx. 62mb) on the device. The devices will be rooted, so that's not a problem. But, while downloading the apk using AsyncTask, the progress bar resets to 0% after reaching 34% (exact 34% every time, even on different devices) and throws java.io.IOException: unexpected end of stream.
Here is the code I'm using :
public class InstallAPK extends AsyncTask<Void,Integer,Void> {
ProgressDialog progressDialog;
int status = 0;
private Context context;
public InstallAPK(Context context, ProgressDialog progress){
this.context = context;
this.progressDialog = progress;
}
public void onPreExecute() {
if(progressDialog!=null)
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(context.getString(R.string.kodi_apk_link));
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
// getting file length
int lenghtOfFile = c.getContentLength();
Log.e("File length", ""+lenghtOfFile);
File outputFile = new File(context.getFilesDir(), context.getString(R.string.kodi_apk_name));
if(outputFile.exists()){
if(outputFile.length() != lenghtOfFile)
outputFile.delete();
else {
publishProgress(-1);
final String libs = "LD_LIBRARY_PATH=/vendor/lib:/system/lib ";
final String commands = libs + "pm install -r " + context.getFilesDir().getAbsolutePath() + "/"
+ context.getString(R.string.kodi_apk_name);
installApk(commands);
return null;
}
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
//i tried both, with and without buffered reader
BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len1 = 0, total=0;
if (lenghtOfFile != -1)
{
buffer = new byte[lenghtOfFile];
do {
len1 += bufferedInputStream.read(buffer, len1, lenghtOfFile-len1);
publishProgress((int)((len1*100)/lenghtOfFile));
} while (len1 < lenghtOfFile);
}
//I was using this code before, but it's not working too
/*while ((len1 = is.read(buffer)) != -1) {
total += len1;
publishProgress((int)((total*100)/lenghtOfFile));
fos.write(buffer, 0, len1);
}*/
fos.flush();
fos.close();
bufferedInputStream.close();
is.close();
//Log.e("Directory path", myDir.getAbsolutePath());
publishProgress(-1);
final String libs = "LD_LIBRARY_PATH=/vendor/lib:/system/lib ";
final String commands = libs + "pm install -r " + context.getFilesDir().getAbsolutePath() + "/"
+ context.getString(R.string.kodi_apk_name);
installApk(commands);
} catch (FileNotFoundException fnfe) {
status = 1;
Log.e("File", "FileNotFoundException! " + fnfe);
}
catch(Exception e)
{
Log.e("UpdateAPP", "Exception " + e);
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
if(progress[0]!=-1) {
// setting progress percentage
progressDialog.setProgress(progress[0]);
} else {
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Installing Kodi...");
}
}
public void onPostExecute(Void unused) {
if(progressDialog!=null) {
progressDialog.dismiss();
}
if(status == 1)
Toast.makeText(context,"App Not Available",Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"Successfully installed the app",Toast.LENGTH_LONG).show();
Intent LaunchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getString(R.string.kodi_apk_package));
if(LaunchIntent!=null)
context.startActivity(LaunchIntent);
else
Toast.makeText(context, "Error in installig Kodi, Try again.", Toast.LENGTH_LONG).show();
}
private void installApk(String commands) {
try {
Process p = Runtime.getRuntime().exec("su");
InputStream es = p.getErrorStream();
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes(commands + "\n");
os.writeBytes("exit\n");
os.flush();
int read;
byte[] buffer = new byte[4096];
String output = new String();
while ((read = es.read(buffer)) > 0) {
output += new String(buffer, 0, read);
}
Log.v("AutoUpdaterActivity", output.toString());
p.waitFor();
} catch (IOException e) {
Log.v("AutoUpdaterActivity", e.toString());
} catch (InterruptedException e) {
Log.v("AutoUpdaterActivity", e.toString());
}
}
}
I tried everything to make this code work. But, it didn't. Then I found an alternative to this. I tried IntentService to download the apk, and surprisingly it worked. I think AsyncTask might have some kind of limit for downloading. To download using IntentService I used this code. The answer is very informative. It also has some other alternatives for downloading.
You should add connection timeout for HttpURLConnection.
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
//set timeout to 5 seconds , set your time here
c.setConnectTimeout(5000);
c.connect();
Its work for me.I hope its work for you.
I need to get the time of download when I launch my android application. So, I added 2 Log and System.currentTimeMillis(). But, I can’t find the exact location to put these tools.
To get the start time, I added this :
period=System.currentTimeMillis();
System.out.println("Début téléchargement : "+System.currentTimeMillis());
To ser the end time, I added this :
System.out.println("Fin téléchargement : "+System.currentTimeMillis());
period=(System.currentTimeMillis()-period);
System.out.println("La durée de téléchargement : "+period+"ms");
And this is all the code to download file :
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
File vSDCard = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
vSDCard = Environment.getExternalStorageDirectory();
File vFile = new File(vSDCard.getParent() + "/" + vSDCard.getName() + "/"
+ "image.jpg");
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
conexion.connect();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(vFile);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e);
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
ProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
I need your suggestion please.
First block before open URL connection or just before you start reding from input stream.
Second block after close of connection or just after the loop.
What's so difficult about it? Am I missing something ?