Downloading an mp3 file from server in android - android

I am trying to create an app that can download music files, .mp3 to be precise, from the server.As I am a rookie in this Android Development field so I will appreciate any help from you guys.
I need something to start on and I will really appreciate if u can give me some links for useful resources.
Thanks

If you want to play the .mp3 file from any url then follow the code suggested by nik.
But if you want to download a file form the server and store it in any place on sdcard or internal storage device then follow this code,
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... urlParams) {
int count;
try {
URL url = new URL("url of your .mp3 file");
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/somewhere/nameofthefile.mp3");
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;
}
EDIT: manifest permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

You can do it this way:
try {
MediaPlayer player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource("http://xty/MRESC/images/test/xy.mp3");
player.prepare();
player.start();
} catch (Exception e) {
// TODO: handle exception
}
Manifest permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Use this method
private void beginDownload(){
/*
Create a DownloadManager.Request with all the information necessary to start the download
*/
DownloadManager.Request request=new DownloadManager.Request(Uri.parse("http://examplewebsite.com/aaa.mp3"))
.setTitle("Dummy File")// Title of the Download Notification
.setDescription("Downloading")// Description of the Download Notification
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
// Uri of the destination file
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "" + System.currentTimeMillis());
.setRequiresCharging(false)// Set if charging is required to begin the download
.setAllowedOverMetered(true)// Set if download is allowed on Mobile network
.setAllowedOverRoaming(true);// Set if download is allowed on roaming network
DownloadManager downloadManager= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadID = downloadManager.enqueue(request);// enqueue puts the download request in the queue.
}
Here is the full code
private Button btnDownload;
private long downloadID;
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Fetching the download id received with the broadcast
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//Checking if the received broadcast is for our enqueued download by matching download id
if (downloadID == id) {
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.download);
registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
beginDownload();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(onDownloadComplete);
}
private void beginDownload(){
File file=new File(getExternalFilesDir(null),"Dummy");
/*
Create a DownloadManager.Request with all the information necessary to start the download
*/
DownloadManager.Request request=new DownloadManager.Request(Uri.parse("http://speedtest.ftp.otenet.gr/files/test10Mb.db"))
.setTitle("Dummy File")// Title of the Download Notification
.setDescription("Downloading")// Description of the Download Notification
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
.setDestinationUri(Uri.fromFile(file))// Uri of the destination file
.setRequiresCharging(false)// Set if charging is required to begin the download
.setAllowedOverMetered(true)// Set if download is allowed on Mobile network
.setAllowedOverRoaming(true);// Set if download is allowed on roaming network
DownloadManager downloadManager= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadID = downloadManager.enqueue(request);// enqueue puts the download request in the queue.

Related

Downloading file with DownloadManager Android

I am trying to download a file using the DownloadManager inside an AsyncTask
private class DownloadTask extends AsyncTask<String, Void, Boolean>
{
private Context mContext;
public DownloadTask(Context context)
{
mContext = context;
}
#Override
protected Boolean doInBackground(String... strings) {
String fileName = strings[2]+"_"+strings[3]+ strings[4];
String destination = mDestination + fileName;
final Uri uri = Uri.parse("file://" + destination);
mDownloading = true;
//If the file is already downloading just return.
File file = new File(destination);
if (file.exists()) {
return true;
}
//set downloadmanager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(strings[0]));
request.setDescription(mContext.getString(R.string.downloading)+ " "+strings[1]);
request.setTitle(mContext.getString(R.string.downloading_title));
//set destination
request.setDestinationUri(uri);
// get download service and enqueue file
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
//set BroadcastReceiver to enable next download
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
unregisterReceiver(this);
mDownloading = false;
}
};
//register receiver for when file download is compete
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
return true;
}
}`
The code works fine when I pass the url of the file. The thing is, that we want to make a GET call to a WEB made on PHP. This WEB method creates or selects a file and redirects using header("Location: ".$database->single()['Url']);
But when we make the call from DownloadManager it just calls registerReceiver right away.
Does anyone knows why this happens?
If we use a HttpURLConnection it works fine, but we would like to delegate all the hard work of the download in the DownloadManager.
Thank you for your comments.
3xx: redirects is't supported by DownloadManger. Source code at line 510
And it will download the redirect response and finish right way.
So you should get the response head[Location] by yourself, and pass it to the task.
By the way, you needn't put the download task in the AsyncTask.

WebView Direct Download returns HTML which use the original file extension

I am trying to perform a direct download inside the WebView, not linking to the browser.
webview.setDownloadListener(new DownloadListener() {
#SuppressLint("DefaultLocale")
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
MimeTypeMap mtm = MimeTypeMap.getSingleton();
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(url);
// get file name. if filename exists in contentDisposition, use it. otherwise, use the last part of the url.
String fileName = downloadUri.getLastPathSegment();
int pos = 0;
if ((pos = contentDisposition.toLowerCase().lastIndexOf("filename=")) >= 0) {
fileName = contentDisposition.substring(pos + 9);
pos = fileName.lastIndexOf(";");
if (pos > 0) {
fileName = fileName.substring(0, pos - 1);
}
}
// predict MIME Type
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
String mimeType = mtm.getMimeTypeFromExtension(fileExtension);
// request saving in Download directory
Request request = new DownloadManager.Request(downloadUri);
request.setTitle(fileName);
request.setDescription(url);
request.setMimeType(mimeType);
request.setDestinationInExternalPublicDir( Environment.DIRECTORY_DOWNLOADS, fileName);
Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).mkdirs();
// request in download manager
downloadManager.enqueue(request);
}
});
And to open it,
// download complete toast
private BroadcastReceiver completeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Resources res = context.getResources();
// make toast
Toast.makeText(context, res.getString(R.string.download_complete), Toast.LENGTH_SHORT).show();
// go to download finished window
startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
}
};
#Override
protected void onPause() {
super.onPause();
// if app stops, stop reciever
unregisterReceiver(completeReceiver);
}
#Override
protected void onResume() {
// app start, start reciever
IntentFilter completeFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(completeReceiver, completeFilter);
super.onResume();
}
}
However, the result is not the original file, but the HTML format of the source using the original file extension; e.g. it uses .pdf, but is a HTML file.
What is causing this problem, and How can I fix it?
Files I get
First of all, it is impossible to open with a normal PDF viewer, and when I don't open it as PDF, I get a normal HTML document:
<!DOCTYPE html>
<html>
…
</html>
There is NOTHING SPECIAL in the HTML document.
I found that your filename is coming with quote so just replace it.
fileName=fileName.replaceAll("\"", "");
you will get the proper file. I have also used that code in mine and it's successfully worked.

Control the download ordering of Download manager in android

have an use case like the following:
There are several files to download e.g. A B C D E F
When the downloading is started , say the A B is finished and C is downloading, I would like to interrupt the download of C and start the download of E
Then, after E is finished (if there is no other interruption), continue to C D F.
So far form my research there is only cancel method
downloadManager.remove(downloadReference);
How to achieve this through Download manager or are there other approach ? thanks
private long startDownload(String url) {
Uri DownloadUri = Uri.parse(url);
String fileName = StorageUtils.getFileNameFromUrl(url);
String destination = null;
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
DownloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle(fileName);
request.setDescription("com.example.services");
if (StorageUtils.isSDCardPresent()
&& StorageUtils.isSdCardWrittenable()
&& StorageUtils.checkAvailableStorage()) {
destination = StorageUtils.SDCARD_ROOT;
}
try {
StorageUtils.mkdir();
} catch (IOException e) {
e.printStackTrace();
}
request.setDestinationInExternalPublicDir(destination, fileName);
downloadReference = downloadManager.enqueue(request);
Log.d("Downloader","Start download manager: " + destination + fileName);
return downloadReference;
}
Regarding this answer, it looks like you can cancel the download and then download the rest of the file. For example:
Register a BrodcastReciever to notify you when C is completed:
BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//check if it is B that is complete
//cancel C
// download E
//check if it is E that is complete
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
// here "downloaded" is the data length already previously downloaded.
// Connect to server.
connection.connect();
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//download A
//download B
//download C

ProgressBar during download with DownloadManager and sleeping thread in Android

I use the DownloadManager to download a xml file from a URL. Then I use a Thread to wait 2 seconds to complete saving the file to the sd card.
I would like to have a activity circle as shown here. What is the easiest way to realize this? Do I need to implement a AsyncTask?
My code to download and wait:
//Download XML file from URL
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setTitle("Download von "+Name+".xml");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(FileSeperator+"XML"+FileSeperator, Name + FileExtension);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
File file = new File(Environment.getExternalStorageDirectory()+ FileSeperator
+"XML"+FileSeperator+ Name + FileExtension);
System.out.println("File existiert "+file.exists());
//insert delay after download to finish save progress before starting to parse the xml
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
UPDATE
Here is my implemented AsyncTask
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
//Download XML file from URL
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setTitle("Download von "+Name+".xml");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(FileSeperator+"XML"+FileSeperator, Name + FileExtension);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
File file = new File(Environment.getExternalStorageDirectory()+ FileSeperator
+"XML"+FileSeperator+ Name + FileExtension);
System.out.println("File existiert "+file.exists());
//insert delay after download to finish save progress before starting to parse the xml
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
protected void onPostExecute() {
super.onPreExecute();
pDialog.dismiss();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
}
And I call it like that:
// instantiate it within the onCreate method
pDialog = new ProgressDialog(CreateProject.this);
pDialog.setMessage("Lädt...");
pDialog.setIndeterminate(true);
// execute this when the downloader must be fired
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute();
I think yes, you should implement this with AsynsTask class, it's clear, fast and easy. You can read a short tutorial about AsyncTask here
You can very well full fill your requirement with asynctask onPreExecute() show your progress dialog do your process in the doInBackground() and onPostExecture dismiss the dialog and show your result.
Just call super.onPostExecute() instead of super.onPreExecute() in the subclass onPostExecute or it won't work well

Android DownloadManager API - opening file after download?

I am facing problem of opening downloaded file after successfull download via DownloadManager API. In my code:
Uri uri=Uri.parse("http://www.nasa.gov/images/content/206402main_jsc2007e113280_hires.jpg");
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.mkdirs();
lastDownload = mgr.enqueue(new DownloadManager.Request(uri)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("app update")
.setDescription("New version 1.1")
.setShowRunningNotification(true)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "a.apk"));
Cursor c=mgr.query(new DownloadManager.Query().setFilterById(lastDownload));
if(c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)) == 8) {
try {
mgr.openDownloadedFile(c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("MGR", "Error");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("MGR", "Error");
}
}
Problem is when is if(c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))==8) evoked. I got status -1 and an exception. Is there any better way, how to open downloaded files with DownloadManager API? In my example I am downloading a big image, in a real situation I would be downloading an APK file and I need to display an installation dialog immediately after udpate.
Edit: I figured out that status=8 is after successfull download. You might have different "checking successfull download" approach
Thanks
Problem
Android DownloadManager API - opening file after download?
Solution
/**
* Used to download the file from url.
* <p/>
* 1. Download the file using Download Manager.
*
* #param url Url.
* #param fileName File Name.
*/
public void downloadFile(final Activity activity, final String url, final String fileName) {
try {
if (url != null && !url.isEmpty()) {
Uri uri = Uri.parse(url);
activity.registerReceiver(attachmentDownloadCompleteReceive, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setMimeType(getMimeType(uri.toString()));
request.setTitle(fileName);
request.setDescription("Downloading attachment..");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
}
} catch (IllegalStateException e) {
Toast.makeText(activity, "Please insert an SD card to download file", Toast.LENGTH_SHORT).show();
}
}
/**
* Used to get MimeType from url.
*
* #param url Url.
* #return Mime Type for the given url.
*/
private String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
return type;
}
/**
* Attachment download complete receiver.
* <p/>
* 1. Receiver gets called once attachment download completed.
* 2. Open the downloaded file.
*/
BroadcastReceiver attachmentDownloadCompleteReceive = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
openDownloadedAttachment(context, downloadId);
}
}
};
/**
* Used to open the downloaded attachment.
*
* #param context Content.
* #param downloadId Id of the downloaded file to open.
*/
private void openDownloadedAttachment(final Context context, final long downloadId) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
String downloadLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
String downloadMimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
openDownloadedAttachment(context, Uri.parse(downloadLocalUri), downloadMimeType);
}
}
cursor.close();
}
/**
* Used to open the downloaded attachment.
* <p/>
* 1. Fire intent to open download file using external application.
*
* 2. Note:
* 2.a. We can't share fileUri directly to other application (because we will get FileUriExposedException from Android7.0).
* 2.b. Hence we can only share content uri with other application.
* 2.c. We must have declared FileProvider in manifest.
* 2.c. Refer - https://developer.android.com/reference/android/support/v4/content/FileProvider.html
*
* #param context Context.
* #param attachmentUri Uri of the downloaded attachment to be opened.
* #param attachmentMimeType MimeType of the downloaded attachment.
*/
private void openDownloadedAttachment(final Context context, Uri attachmentUri, final String attachmentMimeType) {
if(attachmentUri!=null) {
// Get Content Uri.
if (ContentResolver.SCHEME_FILE.equals(attachmentUri.getScheme())) {
// FileUri - Convert it to contentUri.
File file = new File(attachmentUri.getPath());
attachmentUri = FileProvider.getUriForFile(activity, "com.freshdesk.helpdesk.provider", file);;
}
Intent openAttachmentIntent = new Intent(Intent.ACTION_VIEW);
openAttachmentIntent.setDataAndType(attachmentUri, attachmentMimeType);
openAttachmentIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
context.startActivity(openAttachmentIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, context.getString(R.string.unable_to_open_file), Toast.LENGTH_LONG).show();
}
}
}
Initialize FileProvider Details
Decleare FileProvider in AndroidManifest
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.freshdesk.helpdesk.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_path"/>
</provider>
Add the following file "res -> xml -> file_path.xml"
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="attachment_file" path="."/>
</paths>
Note
Why Use FileProvider
From Android 7.0 we can't share FileUri with other appliction.
Using "DownloadManager.COLUMN_LOCAL_URI" we will get only FileUri hence we need to convert it into ContentUri & share with other application.
Provblem with using "DownloadManager.getUriForDownloadedFile(long id)"
Don't use "DownloadManager.getUriForDownloadedFile(long id)" - To get Uri from downloadId to open the file using external application.
Because from Android 6.0 & 7.0 "getUriForDownloadedFile" method returns local uri (Which can be accessed only by our application), we can't share that Uri with other application because they can't access that uri (But it is fixed in Android 7.1 see Android Commit Here).
Refere Android source code DownloadManager.java & Downloads.java
Hence always use Column "DownloadManager.COLUMN_LOCAL_URI" to get Uri.
Reference
https://developer.android.com/reference/android/app/DownloadManager.html
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
You need to register a reciever for when the download is complete:
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
and a BroadcastReciever handler
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
// Do Something
}
};
Buy instead of me ripping off everything, I suggest you'll check this out.
EDIT:
Just as a suggestion, I wouldn't recommend using API 9 just yet: http://developer.android.com/resources/dashboard/platform-versions.html
There are ways around this, by creating your very own download handler, like I did, because we didn't want to alienate most of our android's user base, for that you'll need:
Create AsyncTask which handles the file download.
and i'll recommend to create a download dialog of some sort (if you say it's a big file, i'd make it appear in the notification area).
and than you'll need to handle the opening of the file:
protected void openFile(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),
"MIME-TYPE");
startActivity(install);
}
For Kotlin, you can easily just use the URL.openStream() method to read and save your file in your directory.
If you want to do more fancier, like background threads.
You should checkout Elye's article on Medium.
https://medium.com/mobile-app-development-publication/download-file-in-android-with-kotlin-874d50bccaa2
private fun downloadVcfFile() {
CoroutineScope(Dispatchers.IO).launch {
val url = "https://srv-store5.gofile.io/download/JXLVFW/vcard.vcf"
val path = "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)}/contacts.vcf"
URL(url).openStream().use { input ->
FileOutputStream(File(path)).use { output ->
input.copyTo(output)
val file = File(path)
file.createNewFile()
onMain { saveVcfFile(file) }
}
}
}
}
remember add <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> to your AndroidMannifest.xml file

Categories

Resources