How to download audio files from URL links? - android

I am creating an app in which I have to play audio from a number of URL links. At the first ever run of the app I am providing user the option of either downloading all of the audio files at once. Right now I am downloading each URL individually using Async Task. The problem with this approach is that since I have some 6000 url links for audio files it takes very long.
My questions is that is there any way I can quickly download audio files from these 6000 urls.
Below I am also providing the code that I am using for downloading each url.
public class DownloadAudio extends AsyncTask<Void, Void, String> {
public static final String TAG = DownloadAudio.class.getSimpleName();
ProgressDialog mProgressDialog;
Context context;
String stringUrl;
int index;
public DownloadAudio(Context context,String url, int randomNumber) {
this.context = context;
stringUrl=url;
index = randomNumber;
}
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, "Please wait", "Download …");
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(stringUrl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String[] path = url.getPath().split("/");
int temp = path.length - 1;
String mp3 = path[temp];
int lengthOfFile = c.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ "/MyAudioApp/" ;
Log.v(TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = mp3;
File outputFile = new File(file , fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return "done";
}
protected void onPostExecute(String result) {
if (result.equals("done")) {
mProgressDialog.dismiss();
}
}
}
Please any suggestions would be very helpful.

Related

unable to fetch apk file from https url while running smoothly with http url

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.

Android - Cannot play audio after downloading from Url because of wrong data source. How to solve this?

I have downloaded an audio file from Url thanks to Giridharan's answer in the link below:
Android - Save image from URL onto SD card
The problem is that I cannot play it, the error is as follows:
java.io.IOException: setDataSourceFD failed.: status=0x80000000
I'm sure that the audio url on the Internet is working fine, because I can play audio directly from that Url without downloading, but after download it then cannot play anymore, maybe the data source was changed incorrectly while downloading.
So how to solve this problem? Any help will be appreciated! Thanks for reading.
Download Audio from web using below code.
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
// Smaple url String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// create dialog if you want
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/myAudio.mp3");
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) {}
return null;
}
#Override
protected void onPostExecute(String unused) {
// hide/dismiss dialog if you have any
}
}
then play it using /sdcard/myAudio.mp3 path in your media player.
if have any issue see this thread.
Finally I found the solution to my question, and now I post here to help everyone else faces the same problem can overcome it.
public String downloadAudioFromUrl(String url) {
int count;
File file = null;
try {
URL urls = new URL(url);
URLConnection connection = urls.openConnection();
connection.connect();
// this will be useful to show the percentage 0-100% in progress bar
int lengthOfFile = connection.getContentLength();
File storageDir = new File(Environment.getExternalStorageDirectory().toString() + "/Photo_Quiz/Audio");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(new Date());
String filename = "audio_" + timeStamp + ".3gp";
file = new File(storageDir, filename);
InputStream input = new BufferedInputStream(urls.openStream());
OutputStream output = new FileOutputStream(file.getAbsolutePath());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress...
// publishProgress((int) (total * 100 / lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
notifyNewMediaFile(file);
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}

Calling publishProgress from another method in Android

I am trying to download a file from my server in Android and updating the progress..
On Async method in background I am calling a method that will download the file to my SD card now I would like update the progress hence trying publishProgress("" + progressvalue); which I am not able access from this method. How do I access the publishProgress?
Here is what I am trying:
private class FileDownloader extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... param) {
downloadFileToSdCard(param[0], "File" + counter + ".mp4");
return null;
}
protected void onProgressUpdate(String... values)
{
Log.d("ANDRO_ASYNC", values[0]);
}
}
downloadFileToSdCard method looks like this:
private void downloadImagesToSdCard(String downloadUrl, String fileName)]
{
FileOutputStream fos;
InputStream inputStream = null;
try {
URL url = new URL(downloadUrl);
String sdCard = Environment.getExternalStorageDirectory().toString();
File myDir = new File(sdCard, "AppDownload");
if (!myDir.exists()) {
myDir.mkdir();
}
String fname = fileName;
File file = new File(myDir, fname);
if (file.exists())
file.delete();
URLConnection ucon = url.openConnection();
final String contentLengthStr=ucon.getHeaderField("content-length");
int lenghtOfFile = Integer.valueOf(contentLengthStr);
HttpURLConnection httpConn = (HttpURLConnection) ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
inputStream = httpConn.getInputStream();
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
long total = 0;
int progress = 0;
while ((bufferLength = inputStream.read(buffer)) > 0)
{
total += bufferLength;
int progress_temp = (int) total * 100 / lenghtOfFile;
publishProgress("" + progress_temp);
if (progress_temp % 10 == 0 && progress != progress_temp)
{
progress = progress_temp;
}
fos.write(buffer, 0, bufferLength);
int downloadedSize = Integer.valueOf(contentLengthStr);
}
inputStream.close();
fos.close();
Log.e("Value", "File Saved in sdcard..");
} catch (IOException io) {
inputStream = null;
fos = null;
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
Can somebody help me fix this? Thanks!
Triy this:
keep you function inside into AsyncTask Class
private class FileDownloader extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... param) {
downloadFileToSdCard(param[0], "File" + counter + ".mp4");
return null;
}
protected void onProgressUpdate(String... values)
{
Log.d("ANDRO_ASYNC", values[0]);
}
private void downloadImagesToSdCard(String downloadUrl, String fileName)
{
//Publish Progress calling code
}
}
The first thing that hits me is to simply pass your AsyncTask to your sdcard method. AsyncTask.publishProgress is protected, so as long as your two classes are in the same package, you should be able to call publishProgress from the sdcard downloaded method.
A cleaner/prettier approach would be to define a callback interface such as ProgressUpdater, let the AsyncTask implement it, and have the sdcard method take a ProgressUpdater as a parameter. This interface would typically have a similar or even equal publishProgress method. This however decouples the AsyncTask itself from the rest of your program.

how to attach image in email in android

How to attach image in email? I am able to attach text in email but not attach image properly,
so only send the Text but not send the Image.
Problem with,
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
so Control direct put in catch statement after urlConnection.connect();, Image not save in SDACRD.so not attach the image. How to do?
My code in Below,
urlShare = "http://example.com/share.php?id="+ strId;
public class sendImageThroughEmail extends AsyncTask<Void, Void, Void> {
/** Hashmap for Share */
ArrayList<HashMap<String, String>> arrDataList = null;
String strMessage = null, strImageLocator = null;
ProgressDialog progressDialog;
String filePath, strImageName;
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(false);
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
arrDataList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONFunctions.getJSONfromURL(urlShare);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
strMessage = jsonobject.getString(TAG_MESSAGE);
strImageLocator = jsonobject.getString(TAG_DATA);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
URL url = new URL(strImageLocator);
//URL url = new URL("http://example.com/upload/images (8).jpg");
strImageName = strImageLocator.substring(strImageLocator
.lastIndexOf('/') + 1);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = strImageName;
Log.i("Local File:", filename);
File file = new File(SDCardRoot, filename);
if (file.createNewFile()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:", "downloadSize:" + downloadedSize
+ "totalSize:" + totalSize);
}
fileOutput.close();
if (downloadedSize == totalSize) {
filePath = file.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
Intent email = new Intent(Intent.ACTION_SEND);
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = strImageName;
File file = new File(SDCardRoot, filename);
Uri markPath = Uri.fromFile(file);
email.putExtra(Intent.EXTRA_STREAM, markPath);
email.putExtra(Intent.EXTRA_SUBJECT, "Share");
email.putExtra(Intent.EXTRA_TEXT, strMessage);
email.setType("image/png");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email Client"));
}
};
My ImageLocator Like this,
1) http://example.com/upload/images (8).jpg
2) http://example.com/upload/11_2134_232222_33.png
Please Guide me.
Thanks in advance...
Edit following strings in your email intent:
//...
email.setType("image/jpeg");
email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+file.getAbsolutePath()));
//...
For more info you can see this answer.
EDIT
To download file use this code:
private final static String SD_CARD = Environment
.getExternalStorageDirectory().getAbsolutePath();
private final static String PNG = ".png";
private final static String APP_FOLDER = "Folder Name";
/**
* Checking if the SD card is mounted
*
* #return SD card existence
*/
public static boolean isSdPresent()
{
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* Downloads image file onto SD card in specific folder
*
* #param fileUrl URL for downloading of file
* #throws IOException
*/
private static void downloadImage(String fileUrl) throws IOException
{
if (isSdPresent())
{
if (fileUrl.length() > 0)
{
URL url = new URL(fileUrl);
InputStream input = url.openStream();
File folder = new File(SD_CARD, APP_FOLDER);
if (!folder.exists())
folder.mkdir();
OutputStream output = new FileOutputStream(new File(folder,
fileUrl.substring(fileUrl.indexOf("=") + 1, fileUrl.length())
+ PNG));
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
{
output.write(buffer, 0, bytesRead);
}
output.close();
input.close();
}
}
else
{
if (BuildConfig.DEBUG)
Log.e("SD card", "not mounted");
}
}

Download different types of file from url

I want to download different types of file and there is possibility of link like
https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRpDmM-KiKgR-wcFtJnXUYVua-2409t5z7pjqski5wQ9pYZfOJG7nklFnc
where I don't know the file name, type and any of the description. then How to get those information. so I make that file name as default?
Thank You.
You have to use async task for downloading file
Call it with
String Your_Url = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRpDmM-KiKgR-wcFtJnXUYVua-2409t5z7pjqski5wQ9pYZfOJG7nklFnc";
new downloadProcess(Your_Url, Your_Context).execute();
public downLoadProcess(String Url , Context context)
{
context.Url = Url ;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<String> result)
{
super.onPostExecute(result);
}
#Override
protected ArrayList<String> doInBackground(Void... Params)
{
ArrayList<String> Data = new ArrayList<String>();
boolean flag = false;
URL url;
URLConnection conn;
int fileSize, lastSlash;
String fileName, path = null;
BufferedInputStream inStream;
BufferedOutputStream outStream;
File outFile;
FileOutputStream fileStream;
WebServiceMethods objWSMethod = new WebServiceMethods();
String downloadUrl = Url ;
try
{
url = new URL(downloadUrl);
conn = url.openConnection();
conn.setUseCaches(false);
fileSize = conn.getContentLength();
// get the filename
lastSlash = url.toString().lastIndexOf('/');
fileName = "file.bin";
if(lastSlash >=0)
{
fileName = url.toString().substring(lastSlash + 1);
}
if(fileName.equals(""))
{
fileName = "file.bin";
}
int DOWNLOAD_BUFFER_SIZE = fileSize;
// start download
inStream = new BufferedInputStream(conn.getInputStream());
path = Environment.getExternalStorageDirectory().toString() ;
File file = new File(path + "/Download");
file.mkdir();
path = Environment.getExternalStorageDirectory() + "/Download/" + fileName;
outFile = new File(path);
fileStream = new FileOutputStream(outFile);
outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0, totalRead = 0;
while((bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
if(Check_your_Internet_is_on?)
{
outStream.write(data, 0, bytesRead);
totalRead += bytesRead;
flag = true;
}
else
{
flag = outFile.delete();
flag = false;
}
}
outStream.close();
fileStream.close();
inStream.close();
}
catch(MalformedURLException e)
{
}
catch(FileNotFoundException e)
{
}
catch(Exception e)
{
}
return Data;
}
}
Hope it will help you..!

Categories

Resources