I created an app which allows the user to download audio file and store it in their SD card. The code below is actually working, but the problem is every time I hit the download button, the whole app freezes until the download is over. How can I solve this issue so that it wont freeze whenever I hit the download button? Please help me, I have been struggling for days trying to figure out te solution for this, I would really appreciate your help a lot. Thanks in advance.
try {
URL url = new URL("http://www.yourfile.mp3");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
Log.v("", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "yourfilename.mp3";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
开发者_JAVA百科 while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}catch (IOException e) {
e.printStackTrace();
}
}
Since your download method works downloading your file, it will create an impression like the app has freezed. But the truth is your method is executing in the back. So to avoid app freeze you can show an ProgressDialog til the download method is downloading and after it gets executed you can cancel the ProgressDialog.
So you have to use a separate thread to download. Here is the link which explains you how to download and show an progressDialog in the mean time.
http://www.bogotobogo.com/Android/android23HTTP.html
Each time you click the button call the AsynchTask.Do your downloading in the doInBackground method. this class is designed exactly for the kind of work you are looking for.Use doInBackground() method to accomplish the task and onPreExecute you can show a progress Dialog.
精彩评论