Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. public class DownloadService extends IntentService
  2. {
  3. public static final int NOTIFY_ID = 108;
  4. NotificationCompat.Builder builder;
  5. NotificationManagerCompat notificationManager;
  6. boolean isProgress;
  7. public DownloadService()
  8. {
  9. super("DownloadService");
  10. }
  11.  
  12. @Override
  13. protected void onHandleIntent(Intent intent)
  14. {
  15. String urlToDownload = intent.getStringExtra("url");
  16. String fileName = intent.getStringExtra("fileName");
  17. try
  18. {
  19. URL url = new URL(urlToDownload);
  20. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  21. connection.connect();
  22. int fileLength = connection.getContentLength();
  23. InputStream input = new BufferedInputStream(connection.getInputStream());
  24. OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + fileName);
  25.  
  26. byte data[] = new byte[1024];
  27. long total = 0;
  28. int count;
  29. showNotification(fileName, 0);
  30. int progress = 0;
  31. while ((count = input.read(data)) != -1)
  32. {
  33. total += count;
  34. int newProgress = (int) total * 100 / fileLength;
  35. if(newProgress >= progress + 20){
  36. progress = newProgress;
  37. showNotification(fileName, progress);
  38. }
  39. output.write(data, 0, count);
  40. }
  41. output.flush();
  42. output.close();
  43. input.close();
  44. }
  45. catch (IOException e)
  46. {
  47.  
  48. }
  49. finally{
  50.  
  51. }
  52. }
  53.  
  54. public void showNotification(String fileName, int progress)
  55. {
  56. builder = new NotificationCompat.Builder(this);
  57. builder.setTicker("Загрузка");
  58. builder.setContentTitle(fileName);
  59. if(progress >= 100){
  60. builder.setSmallIcon(R.drawable.done);
  61. builder.setContentText("Загрузка завершена");
  62. }
  63. else{
  64. builder.setSmallIcon(android.R.drawable.stat_sys_download);
  65. builder.setProgress(100, progress, false);
  66. }
  67. Notification notification = builder.build();
  68.  
  69. notificationManager = NotificationManagerCompat.from(this);
  70. notificationManager.notify(NOTIFY_ID, notification);}
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement