Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DownloadService extends IntentService
- {
- public static final int NOTIFY_ID = 108;
- NotificationCompat.Builder builder;
- NotificationManagerCompat notificationManager;
- boolean isProgress;
- public DownloadService()
- {
- super("DownloadService");
- }
- @Override
- protected void onHandleIntent(Intent intent)
- {
- String urlToDownload = intent.getStringExtra("url");
- String fileName = intent.getStringExtra("fileName");
- try
- {
- URL url = new URL(urlToDownload);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.connect();
- int fileLength = connection.getContentLength();
- InputStream input = new BufferedInputStream(connection.getInputStream());
- OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + fileName);
- byte data[] = new byte[1024];
- long total = 0;
- int count;
- showNotification(fileName, 0);
- int progress = 0;
- while ((count = input.read(data)) != -1)
- {
- total += count;
- int newProgress = (int) total * 100 / fileLength;
- if(newProgress >= progress + 20){
- progress = newProgress;
- showNotification(fileName, progress);
- }
- output.write(data, 0, count);
- }
- output.flush();
- output.close();
- input.close();
- }
- catch (IOException e)
- {
- }
- finally{
- }
- }
- public void showNotification(String fileName, int progress)
- {
- builder = new NotificationCompat.Builder(this);
- builder.setTicker("Загрузка");
- builder.setContentTitle(fileName);
- if(progress >= 100){
- builder.setSmallIcon(R.drawable.done);
- builder.setContentText("Загрузка завершена");
- }
- else{
- builder.setSmallIcon(android.R.drawable.stat_sys_download);
- builder.setProgress(100, progress, false);
- }
- Notification notification = builder.build();
- notificationManager = NotificationManagerCompat.from(this);
- notificationManager.notify(NOTIFY_ID, notification);}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement