The DownloadManager can only download to external storage , you need to implement your own download manager. Use this method to save file:
Home
Public
Questions
Tags
Users
Collectives
ExploreCollectives
FindaJob
Jobs
Companies
Teams
StackOverflowforTeams
–Collaborateandshareknowledgewithaprivategroup.
CreateafreeTeam
WhatisTeams?
Teams
CreatefreeTeam
CollectivesonStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
Howtosavedownloadedfileininternalstorageinandroidstudio?
AskQuestion
Asked
2years,8monthsago
Active
10monthsago
Viewed
8ktimes
0
3
Ihaveadownloadbuttoninmyapp.WhenIpressthedownloadbuttonitdownloadsanaudiofilefromprovidedurl.ButtheproblemisIwanttosavethefileinmyinternalstoragefoldercalled"DownloadTestFolder",itisshowinganerror.
publicclassDownloadTestextendsActivity{
DownloadManagerdownloadManager;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.download_test);
}
publicvoidDownload(Viewview){
downloadManager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uriuri=Uri.parse("MyUrl");
DownloadManager.Requestrequest=newDownloadManager.Request(uri);
try{
request.setDestinationInExternalPublicDir(getFilesDir()+"/DownloadTestFolder","/");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Longreference=downloadManager.enqueue(request);
}catch(Exceptione){
/*Error
}
}
}
javaandroid
Share
Follow
editedJul4'20at11:26
rahul
311silverbadge11bronzebadge
askedMar5'19at6:28
FurqanHussainFurqanHussain
11533silverbadges1414bronzebadges
2
checkthisitsgoodlibforthis-github.com/lingochamp/FileDownloader
– Adil
Mar5'19at6:43
Isthereanynecessarytagging"javascript"?
– GenoChen
Mar5'19at6:48
Addacomment
|
2Answers
2
Active
Oldest
Votes
1
TheDownloadManagercanonlydownloadtoexternalstorage,youneedtoimplementyourowndownloadmanager.
Usethismethodtosavefile:
//DownloadFileAsyncTask
privateclassDownloadFileextendsAsyncTask{
@Override
protectedvoidonPreExecute(){
super.onPreExecute();
}
@Override
protectedBitmapdoInBackground(String...URL){
StringimageURL=URL[0];
Bitmapbitmap=null;
try{
//DownloadImagefromURL
InputStreaminput=newjava.net.URL(URL).openStream();
//DecodeBitmap
bitmap=BitmapFactory.decodeStream(input);
}catch(Exceptione){
e.printStackTrace();
}
returnbitmap;
}
@Override
protectedvoidonPostExecute(Bitmapresult){
if(result!=null){
Filedir=newFile(mContext.getFilesDir(),"MyImages");
if(!dir.exists()){
dir.mkdir();
}
Filedestination=newFile(dir,"image.jpg");
try{
destination.createNewFile();
ByteArrayOutputStreambos=newByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG,0/*ignoredforPNG*/,bos);
byte[]bitmapdata=bos.toByteArray();
FileOutputStreamfos=newFileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
selectedFile=destination;
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
Usage:
newDownloadFile().execute("url_here");
Note:Ihaveaddedcodeforimagetypefile
Share
Follow
editedJan9at13:54
jox
1,8912020silverbadges3030bronzebadges
answeredMar5'19at6:42
QuicklearnerQuicklearner
8,00822goldbadges3232silverbadges4747bronzebadges
3
Thequestionspeciallyaskshowtodownloadtotheinternalstorage.
– coolcool1994
Jul30'20at15:11
context.getFilesDir()meansinternalstorage,updatedanswer
– Quicklearner
Jul31'20at11:20
Whatisthefileisexecutable,notimage,howcanIdecodeit.
– HasanAYousef
Apr1at21:36
Addacomment
|
0
Youcantrythis:
ContextWrappercontextWrapper=newContextWrapper(getApplicationContext());
Filedirectory=contextWrapper.getDir(getFilesDir().getName(),Context.MODE_PRIVATE);
Filefile=newFile(directory,”fileName”);
Stringdata=“TESTDATA”;
FileOutputStreamfos=newFileOutputStream(“fileName”,true);//save
fos.write(data.getBytes());
fos.close();
ThiswillwritefileinDevice'sinternalstorage(/data/user/0/com.yourapp/)
Share
Follow
answeredMar5'19at6:36
miladsalimimiladsalimi
1,42711goldbadge99silverbadges2424bronzebadges
1
Whereistheurlofthefiretobedownloaded
– HasanAYousef
Apr1at21:38
Addacomment
|
YourAnswer
ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers.
Draftsaved
Draftdiscarded
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingEmailandPassword
Submit
Postasaguest
Name
Email
Required,butnevershown
PostYourAnswer
Discard
Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaandroidoraskyourownquestion.
TheOverflowBlog
Whoownsthisoutage?BuildingintelligentescalationchainsformodernSRE
Podcast395:Whoisbuildingcloudsfortheindependentdeveloper?
FeaturedonMeta
Nowlive:Afullyresponsiveprofile
Reducingtheweightofourfooter
TwoBornottwoB-Farewell,BoltClockandBhargav!
Related
2771
HowcanIsaveanactivitystateusingthesaveinstancestate?
2031
HowtolazyloadimagesinListViewinAndroid
1918
HowtogetscreendimensionsaspixelsinAndroid
4135
Howdoyouclose/hidetheAndroidsoftkeyboardprogrammatically?
3057
HowtostopEditTextfromgainingfocusatActivitystartupinAndroid
18
HowdoIplayanaudiofileinAndroid?
1178
HowdoI"selectAndroidSDK"inAndroidStudio?
3
callfragmentswhenclickingRecyclerViewitemandshowthembothinthesameactivity
2
Spinnerdoesn'tshowarrayandtexts
0
RecyclerviewinsideCoordinatorlayout
HotNetworkQuestions
Usinga2TBSSDona2016MacBookPro
HowcanInotgetunfairlyblamedforthingsbymyboss?
What'sthepointofdouble-sidedSPDpedalsifSPDpedalswithplatformaremoreconvenientandlighter?
ShouldImakeequallysizedsamplesfortheMann-WhitneyUtestiforiginallyIhaveunequalsamplesizes
Questionabouttheabbreviationfor2instrumentsinanorchestrascore
Whofirstusedthephrase"DeflationaryTheoryofTruth"?
Whydon'tclimatechangeagreementsself-terminateifparticipantsfailtomeettheircommitments?
Shoulddukkhabetranslatedas`beingunexpected`?
CanImakeahelixwith4strands?
Couldsiliconbasedlifeformseatcarbonbasedfood
WhyisFIPS140-2compliancecontroversial?
Doestheabbreviation“ſ.”inthis1755workmean“sine”?
HowdoIgetridofthemessage:"InversefunctionsarebeingusedbySolve,...;useReduceforcompletesolutioninformation."
HowtomakeLinuxrebootinsteadofremountingthefilesystemasread-only?
Wheredidtheideaoftheornithopteroriginate?
whatcould"dippingfromthecompany'scoffers"possiblymean?
Sci-fistorywherepeoplearereincarnatedathubsandamanwantstofigureoutwhatishappening
Couldanyequationhavepredictedtheresultsofthissimulation?
Candefrostingvacuum-packedfishinitspackagingcausebotulism?
CananISPblockportforwarding?
LTspicefailsatasimpletwo-resistorvoltagedivider.HowcanIfixit?
Harmonicdivisornumbers
Whyisaccusativeusedinthissentence?
HowcanIworkonDSPusingC/C++?
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-java
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings