Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1.  
  2. @Override
  3. public void downloadButtonClicked(Book book) {
  4. final int id = book.getId();
  5. final String title = book.getTitle();
  6. Thread t = new Thread(){
  7. @Override
  8. public void run(){
  9. downloadHandler.sendMessage(download(id, title));
  10. }
  11. };
  12. t.start();
  13. }
  14.  
  15. private Message download(int id, String title) {
  16. Log.d("downloadASDF", "made it to download");
  17. URL downloadURL;
  18.  
  19. String filePath = getExternalFilesDir(null).toString() +
  20. getResources().getString(R.string.audioBookDir) + "/" + title + ".wav";
  21. filePath = filePath.replace(" ", "");
  22. File outputFile = new File(filePath);
  23. outputFile.getParentFile().mkdirs();
  24.  
  25. try {
  26. downloadURL = new URL(getResources().getString(R.string.bookDownload)+ id);
  27. URLConnection connection = downloadURL.openConnection();
  28. int connectionLength = connection.getContentLength();
  29. Log.d("downloadASDF", downloadURL.toString());
  30. Log.d("downloadASDF", "opened connection " + connectionLength);
  31.  
  32.  
  33. DataInputStream inputStream = new DataInputStream(downloadURL.openStream());
  34.  
  35. byte[] buffer = new byte[connectionLength];
  36. inputStream.readFully(buffer);
  37. inputStream.close();
  38.  
  39. Log.d("downloadASDF", "a" + outputFile.getAbsolutePath());
  40.  
  41. if (!outputFile.exists())
  42. outputFile.createNewFile();
  43. DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(outputFile));
  44. outputStream.write(buffer);
  45. outputStream.flush();
  46. outputStream.close();
  47.  
  48. } catch (MalformedURLException ex) {
  49. ex.printStackTrace();
  50. Log.d("Malformed URL", "qwert");
  51. return null;
  52. } catch (IOException ex) {
  53. ex.printStackTrace();
  54. Log.d("IOException", "werty");
  55. return null;
  56. }
  57.  
  58. Message msg = Message.obtain();
  59. msg.what = 1;
  60.  
  61. return msg;
  62. }
  63.  
  64. Handler downloadHandler = new Handler(new Handler.Callback() {
  65.  
  66. @Override
  67. public boolean handleMessage(Message msg) {
  68. Log.d("handlerASDF", "made it to handler");
  69. if (msg == null) {
  70. //TODO worry about this later
  71. }
  72. else {
  73. MainActivity.this.bookDetailsFragment.downloaded = true;
  74. // MainActivity.this.bookDetailsFragment.refreshDownload();
  75. }
  76. return true;}
  77. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement