Monday, 26 February 2018

Download files in background service


Service class
class DownloadService extends IntentService {
RetrofitConnection retrofitInterface;
public DownloadService() {
super("Download Service");
}
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
private int totalFileSize;
private String image_url;
int type;
String filename;
@Override protected void onHandleIntent(Intent intent) {
if (intent.getExtras() != null && intent != null) {
image_url = intent.getStringExtra("img");
type = intent.getIntExtra("type", 0);
filename = intent.getStringExtra("filename");
Log.e("TYPE", "" + type);
}
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.downd)
.setContentTitle("Download")
.setContentText("Downloading image")
.setAutoCancel(true);
notificationBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notificationBuilder.build());
if (NetworkChecking.isConnected(getApplicationContext())) {
initDownload(image_url);
} else {
Utils.toastMessage(getApplicationContext(),
Utils.network_message);
}
}
private void initDownload(String url) {
downloadFile(request.execute().body());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void downloadFile(ResponseBody body) throws IOException {
int count;
byte data[] = new byte[1024 * 4];
long fileSize = body.contentLength();
InputStream bis = new BufferedInputStream(body.byteStream(),
1024 * 8);
Log.e("outputFile", "" + outputFile);
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1024, 2)));
double current = Math.round(total / (Math.pow(1024, 2)));
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download,outputFile.getPath());
timeCount++; }
output.write(data, 0, count);
}
onDownloadComplete(outputFile.getPath());
output.flush(); output.close();
private void sendNotification(Download download,String filePath) {
bis.close(); }
File file = new File(filePath);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(
file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
sendIntent(download);
notificationBuilder.setProgress(100, download.getProgress(),
false);
notificationBuilder.setContentText("Downloading file " +
download.getCurrentFileSize() + "/" + totalFileSize + " MB");
notificationBuilder.setContentIntent
(PendingIntent.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT));
notificationManager.notify(0, notificationBuilder.build());
}
private void sendIntent(Download download) {
Intent intent = new Intent(ShowImageActivity.MESSAGE_PROGRESS);
intent.putExtra("download", download);
LocalBroadcastManager.getInstance(DownloadService.this).
sendBroadcast(intent);
}
private void onDownloadComplete(String filePath) {
Download download = new Download();
download.setProgress(100);
sendIntent(download);
File file = new File(filePath);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl
(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
notificationManager.cancel(0);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder.setContentText("File Downloaded");
notificationBuilder.setContentIntent
(PendingIntent.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT));
notificationManager.notify(0, notificationBuilder.build());
}
@Override public void onTaskRemoved(Intent rootIntent) {
notificationManager.cancel(0);
}
public File getOutputMediaFile(int type) {
String folder_name = "TYC";
File mediaStorageDir = new File(Environment.
getExternalStorageDirectory() + "/" + folder_name, "IMAGES");
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
File f1 = new File(Environment.getExternalStorageDirectory()
+ "/" + folder_name, "DOCUMENTS");
if (!f1.exists()) {
f1.mkdirs();
}
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() +
File.separator + "img_" + timeStamp + ".jpg");
} else if (type == 2) {
mediaFile = new File(f1.getPath() + File.separator
+ "PDF_" + timeStamp + ".pdf");
} else if (type == 3) {
mediaFile = new File(f1.getPath() + File.separator
+ filename);
}else {
return null;
}
return mediaFile;
} }
Call service from Button click
Intent intent = new Intent(getActivity(), DownloadService.class);
intent.putExtra("img", "pass your file path");
intent.putExtra("type", 3);
intent.putExtra("filename", "Pass here your file name");
startService(intent);