Downloading mp3 file and storing in app's directory - android

In my Android project, programmatically I need to download a .mp3 file from google drive download url and store in the app sandbox. Then, App can have play option to play this audio locally.
How is this possible to achieve downloading .mp3 file from server and store it locally in the app? Later, it can be played from local storage. Any help on this is very much appreciated.
Thank you.

You can use this method:
static void downloadFile(String dwnload_file_path, String fileName,
String pathToSave) {
int downloadedSize = 0;
int totalSize = 0;
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
// connect
urlConnection.connect();
File myDir;
myDir = new File(pathToSave);
myDir.mkdirs();
// create a new file, to save the downloaded file
String mFileName = fileName;
File file = new File(myDir, mFileName);
FileOutputStream fileOutput = new FileOutputStream(file);
// Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
// this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
// runOnUiThread(new Runnable() {
// public void run() {
// pb.setMax(totalSize);
// }
// });
// create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
// runOnUiThread(new Runnable() {
// public void run() {
// pb.setProgress(downloadedSize);
// float per = ((float)downloadedSize/totalSize) * 100;
// cur_val.setText("Downloaded " + downloadedSize + "KB / " +
// totalSize + "KB (" + (int)per + "%)" );
// }
// });
}
// close the output stream when complete //
fileOutput.close();
// runOnUiThread(new Runnable() {
// public void run() {
// // pb.dismiss(); // if you want close it..
// }
// });
} catch (final MalformedURLException e) {
// showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
// showError("Error : IOException " + e);
e.printStackTrace();
} catch (final Exception e) {
// showError("Error : Please check your internet connection " + e);
}
}
Call this method like this:
String SDCardRoot = Environment.getExternalStorageDirectory()
.toString();
Utils.downloadFile("http://my_audio_url/my_file.mp3", "my_file.mp3",
SDCardRoot+"/MyAudioFolder");
for playback:
String SDCardRoot = Environment.getExternalStorageDirectory()
.toString();
String audioFilePath = SDCardRoot + "/MyAudioFolder/my_file.mp3";
MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(audioFilePath);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e("AUDIO PLAYBACK", "prepare() failed");
}

a very simple solution is to use Android Download Manager Api
public void download(MediaRecords mediaRecords) {
try {
Toast.makeText(application, application.getString(R.string.download_started), Toast.LENGTH_SHORT).show();
MediaRecordsOffline mediaRecordsOffline = mediaRecords.toOfflineModel();
mediaRecordsOffline.setLocalFileUrl(Utils.getEmptyFile(mediaRecordsOffline.getId() + ".mp3").getAbsolutePath());
dao.insertOfflineMedia(mediaRecordsOffline);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mediaRecordsOffline.getFileUrl()))
.setTitle(mediaRecordsOffline.getName())// Title of the Download Notification
.setDescription(mediaRecordsOffline.getDescription())// Description of the Download Notification
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
.setAllowedOverMetered(true)// Set if download is allowed on Mobile network
.setDestinationUri(Uri.fromFile(Utils.getEmptyFile(mediaRecordsOffline.getId() + ".mp3")))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setAllowedOverRoaming(true);// Set if download is allowed on roaming network
DownloadManager downloadManager = (DownloadManager) application.getSystemService(Context.DOWNLOAD_SERVICE);
downloadManager.enqueue(request); // enqueue puts the download request in
} catch (Exception e) {
android.util.Log.i(TAG, "downloadManager: " + e.getMessage());
Toast.makeText(application, application.getString(R.string.error), Toast.LENGTH_SHORT).show();
}
}
Utils class which used to create the File :
public class Utils {
public static File getEmptyFile(String name) {
File folder = Utils.createFolders();
if (folder != null) {
if (folder.exists()) {
File file = new File(folder, name);
return file;
}
}
return null;
}
public static File createFolders() {
File baseDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
if (baseDir == null)
return Environment.getExternalStorageDirectory();
File aviaryFolder = new File(baseDir, ".playNow");
if (aviaryFolder.exists())
return aviaryFolder;
if (aviaryFolder.isFile())
aviaryFolder.delete();
if (aviaryFolder.mkdirs())
return aviaryFolder;
return Environment.getExternalStorageDirectory();
}
}

Related

Android : Download images and mp3 audio from server

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);
}

Saving the Images from string array to SD card and Phone gallery

I am using string array to hold images, i am fetching the imaes from the URLs. I have one imageview which when swipped changes the images in it. Now i want to download and save any image i want on the SD card and want it to appear in the phone gallery in a new folder.
I am using the following code but it is not working, it is showing no error at all.
private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... arg0) {
downloadImagesToSdCard("", "");
return null;
}
private void downloadImagesToSdCard(String downloadUrl, String imageName) {
try {
URL url = new URL(thumb[j]);
/* making a directory in sdcard */
String sdCard = Environment.getExternalStorageDirectory()
.toString();
File myDir = new File(sdCard, "test.jpg");
/* if specified not exist create new */
if (!myDir.exists()) {
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = imageName;
File file = new File(myDir, fname);
if (file.exists())
file.delete();
/* Open a connection */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection) ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
FileOutputStream fos = new FileOutputStream(file);
int totalSize = httpConn.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:", "downloadedSize:" + downloadedSize
+ "totalSize:" + totalSize);
}
fos.close();
Log.d("test", "Image Saved in sdcard..");
} catch (IOException io) {
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And i am executing it by
new ImageDownloadAndSave().execute("");
the name of my string array is "thumb" which is holding all the URLs. What am i doing wrong?
You should add image to gallery after save and then scan it. Please check the following topics:
Image, saved to sdcard, doesn't appear in Android's Gallery app
MediaScannerConnection
The file needs to be added to the Android MediaStore. This can be done easily by using below function.
public void scanFile(final File file) {
try {
new MediaScannerConnectionClient() {
private MediaScannerConnection mMs;
public void init() {
mMs = new MediaScannerConnection(myContext, this);
mMs.connect();
}
#Override
public void onMediaScannerConnected() {
mMs.scanFile(file.getAbsolutePath(), null);
mMs.disconnect();
}
#Override
public void onScanCompleted(String path, Uri uri) {
}
}.init();
} catch(Exception e) {
// Device does not support adding files manually.
// Sending Broadcast to start MediaScanner (slower than adding manually)
try {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
} catch(Exception ee) {
// Something went terribly wrong.
// Can't add file to MediaStore and can't send Broadcast to start MediaScanner.
}
}
}
You just need to add one line to your code:
// .....
fos.close();
Log.d("test", "Image Saved in sdcard..");
scanFile(file); // <------------- add this

Cannot open a file that was created in the temporary folder of an Android app - file does not exist or cannot be read

When I run the code below I get a prompt to open the file with an appropriate reader but the file does not get displayed.
I am new to Android App development and any help will be greatly appreciated.
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
file = File.createTempFile("Christo", ".pdf");
fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
runOnUiThread(new Runnable() {
public void run() {
pb.setMax(totalSize);
}
});
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
runOnUiThread(new Runnable() {
public void run() {
pb.setProgress(downloadedSize);
float per = ((float) downloadedSize / totalSize) * 100;
cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int) per + "%)");
}
});
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
public void run() {
// do not close progressbar
}
});
} catch (final MalformedURLException e) {
showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
showError("Error : IOException " + e);
e.printStackTrace();
} catch (final Exception e) {
showError("Error : Please check your internet connection " + e);
}
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
I think while creating the file it should be
file = File.createTempFile("Christo", "pdf");
The . [dot] is not required
You are creating the file in internal -private- memory unreachable for other apps. Create it in external memory instead. Ask external write permission in manifest.

Read an inputstream and download using DownloadManager

I am trying to download and save the file to sd card. The file url is as follows
http://test.com/net/Webexecute.aspx?fileId=120
This url provides a stream of data. I have the following option to read the input stream.
Use generic input and output stream (no handlers for connection fail
overs)
Download manager
Using HttpUrlConnection (possible timeout chances)
I have done the download using option a. But there are no handlers for connection fail overs. So I decided to go with option b
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse("http://test.com/net/Webexecute.aspx?fileId="+ fileId));
request.setMimeType("application/pdf");
request.setDescription("fileDownload");
request.setTitle(fileName);
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
dm.enqueue(request);
It is downloading the file. However, the file seems to be corrupted.
While doing the research, I never found DownloadManager being used to fetch an input stream and save that to a file. Is there anything I am lacking?
Please change your code to download a file.
protected Void downLoadFile(String fileURL) {
int count;
try {
URL url = new URL(fileURL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/filename.txt");
byte data[] = new byte[1024];
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
fos.write(data, 0, count);
}
is.close();
fos.close();
readStringFromFile(testDirectory);
} catch (Exception e) {
Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage());
e.printStackTrace();
}
return null;
}
The Below method is used to read string from file.
public String readStringFromFile(File file) {
String response = "";
try {
FileInputStream fileInputStream = new FileInputStream(file + "/filename.txt");
StringBuilder builder = new StringBuilder();
int ch;
while ((ch = fileInputStream.read()) != -1) {
builder.append((char) ch);
}
response = builder.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}

Copy all files from server to Android Device

i want to copy all files from server to Android device.
Suppose on server, my server ip is http://192.168.98.23 and the name of the server folder is Data. The Data folder contains many files.
I want to copy all files from the server Data to the SD Card of my Android device.
How can I do this?
As you can say you are using LAN to transfer files from server to Android (Sdcard).
For this purpose there are two approaches you can use.i.e i) TCP/IP protocol. ii) SMB (Server Message Block) protocol.
I recommend you to use SMB protocol because in this you have to just sharing a folder with full permissions and copy all the files to Android Sdcard. At Android side in this case which is your client side you have to use four things. i) IP Address of the server. ii) Password of the Server. iii) UserName of the server and the last iv) Shared FolderName.
With the help of these four parameters you make a connection and copy all the files which is placed into the Shared Folder.
Follow the code snippet that is used to make a connection using smb protocole.
public boolean VerifyUser(String address, String username, String password)
{
try
{
if (address != "" && username != "" && password != "")
{
setDomain(UniAddress.getByName(address));
setAuthentication(new NtlmPasswordAuthentication(null,
username, password));
SmbSession.logon(getDomain(), authentication);
return true;
}
else
{
return false;
}
}
catch (UnknownHostException e)
{
return false;
}
catch (SmbException e)
{
return false;
}
}// End VerifyUser Method.
// *******************************************************************************************************
Dowbload File from PC Server to Android Client using SMB Connections. where strPCPath = "smb://" + 192.168.98.23+ "/" + strFolderName + "/FileName"; blow code is download a single file includes .config extension you can used this for downloading multiple files.
public boolean downloadConfigFileFromServer(String strPCPath , String strSdcardPath)
{
SmbFile smbFileToDownload = null;
try
{
File localFilePath = new File(strSdcardPath);
// create sdcard path if not exist.
if (!localFilePath.isDirectory())
{
localFilePath.mkdir();
}
try
{
smbFileToDownload = new SmbFile(strPCPath , authentication);
String smbFileName = smbFileToDownload.getName();
if (smbFileName.toLowerCase().contains(".config"))
{
InputStream inputStream = smbFileToDownload.getInputStream();
//only folder's path of the sdcard and append the file name after.
localFilePath = new File(strSdcardPath+ "/" + smbFileName);
OutputStream out = new FileOutputStream(localFilePath);
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0)
{
out.write(buf, 0, len);
}
out.flush();
out.close();
inputStream.close();
return true;
}
else
return false;
}// End try
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}// End downloadConfigFileFromServer Method.
// *******************************************************************************************************
This logic download a data from server as .Zip file. This will fetch data from your domain server folder and saved into the PATH=""/data/data/your_pkg_name/app_my_sub_dir/images/";
// Download Contents
Thread t = new Thread() {
#Override
public void run() {
try {
URL url = new URL(
"http://192.168.98.23/Data");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
//System.out.println("fileLength: " + fileLength);
int size, BUFFER_SIZE = 8192;
int total = 0, progress = 0;
byte[] buffer = new byte[BUFFER_SIZE];
String PATH = "/data/data/your_pkg_name/app_my_sub_dir/";
String location = PATH + "images/";
try {
if (!location.endsWith("/")) {
location += "/";
}
File f = new File(location);
if (!f.isDirectory()) {
f.mkdirs();
}
ZipInputStream zin = new ZipInputStream(
connection.getInputStream());
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = location + ze.getName();
File unzipFile = new File(path);
if (ze.isDirectory()) {
if (!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
} else {
// check for and create parent
// directories if they don't exist
File parentDir = unzipFile
.getParentFile();
if (null != parentDir) {
if (!parentDir.isDirectory()) {
parentDir.mkdirs();
}
}
// unzip the file
FileOutputStream out = new FileOutputStream(
unzipFile, false);
BufferedOutputStream fout = new BufferedOutputStream(
out, BUFFER_SIZE);
try {
while ((size = zin.read(buffer, 0,
BUFFER_SIZE)) != -1) {
total += size;
progress += total * 70 / fileLength;
if (progress == 1) {
progressBarStatus = progressBarStatus
+ progress;
handlerProgressBar
.sendEmptyMessage(0);
total = progress = 0;
}
fout.write(buffer, 0, size);
fout.flush();
}
zin.closeEntry();
} finally {
fout.close();
}
}
}
} finally {
zin.close();
}
} catch (Exception e) {
}
// this.notify();
} catch (Exception e) {
interrput=true;
handler.sendEmptyMessage(1);
}
}
};
t.start();

Categories

Resources