***** UPDATE SOLUTION********
*****top of the class****
ArrayList<Homework_listpojo> homeworklist = new ArrayList<>();
Context mcontext;
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
int id = 1;
private long lastDownload=-1L;
DownloadManager mManager= null;
******When clicking on attachment then put this code under that scope :******
if (homeworklist.get(position).getDocument().isEmpty() ||
homeworklist.get(position).getDocument().equalsIgnoreCase("") ||
homeworklist.get(position).getDocument()== null){
Toast.makeText(mcontext, "Attacment not Available", Toast.LENGTH_SHORT).show();
}else {
new DownloadFile().execute(url);
mManager = (DownloadManager) mcontext.getSystemService(Context.DOWNLOAD_SERVICE);
/*...
now added code for auto open file
*/
registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
registerReceiver(onNotificationClick,
new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.mkdirs();
DownloadManager.Request mRqRequest = new DownloadManager.Request(
Uri.parse(url));
Toast.makeText(mcontext, "Downloading Started..", Toast.LENGTH_SHORT).show();
lastDownload= mManager.enqueue(mRqRequest);
// v.setEnabled(false);
// findViewById(R.id.attachment_homework).setEnabled(true);
mNotifyManager = (NotificationManager) mcontext.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(mcontext);
mBuilder.setContentTitle("File Download")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.ic_file_download_black_24dp);
// open downloaded file when click on notification
Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
PendingIntent pendingIntent = PendingIntent.getActivity(mcontext, 0, intent, 0);
mBuilder.setContentIntent(pendingIntent);
}
***** Inner class****
// download attachment
private class DownloadFile extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog;
private String fileName;
private String folder;
private boolean isDownloaded;
/**
* Before starting background thread
* Show Progress Bar Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
this.progressDialog = new ProgressDialog(mcontext);
this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.progressDialog.setCancelable(false);
this.progressDialog.show();
}
/**
* Downloading file in background thread
*/
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// getting file length
int lengthOfFile = connection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
//Extract file name from URL
fileName = f_url[0].substring(f_url[0].lastIndexOf('/') + 1, f_url[0].length());
//Append timestamp to file name
fileName = timestamp + "_" + fileName;
//External directory path to save file
folder = Environment.getExternalStorageDirectory() + File.separator + "aattachmentschool/";
//Create androiddeft folder if it does not exist
File directory = new File(folder);
if (!directory.exists()) {
directory.mkdirs();
}
// Output stream to write file
OutputStream output = new FileOutputStream(folder + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthOfFile));
// Log.d(TAG, "Progress: " + (int) ((total * 100) / lengthOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
return "Downloaded at: " + folder + fileName;
} catch (Exception e) {
e.printStackTrace();
}
return "Something went wrong";
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
progressDialog.setProgress(Integer.parseInt(progress[0]));
// Sets the progress indicator to a max value, the current completion percentage and "determinate" state
mBuilder.setProgress(100,Integer.parseInt(progress[0]), false);
// Displays the progress bar for the first time.
mNotifyManager.notify(id, mBuilder.build());
}
@Override
protected void onPostExecute(String message) {
// dismiss the dialog after the file was downloaded
this.progressDialog.dismiss();
//filePath= message;
mBuilder.setContentText("Download completed")
// Removes the progress bar
.setProgress(0, 0, false);
mNotifyManager.notify(id, mBuilder.build());
/*String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
openDownloadedAttachment(context, downloadId);
}*/
/* openDownloadedAttachment(mcontext, lastDownload);
viewLog();*/
//queryStatus();
/* Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
mBuilder.setContentIntent(pendingIntent);*/
// Display File path after downloading
Toast.makeText(mcontext, message, Toast.LENGTH_LONG).show();
}
}
**** outside from inner class*****
@Override
public void onDestroy() {
super.onDestroy();
try {
unregisterReceiver(onComplete);
} catch (Exception e) {
}
try {
unregisterReceiver(onNotificationClick);
} catch (Exception e) {
}
}
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
// findViewById(R.id.attachment_homework).setEnabled(true);
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
openDownloadedAttachment(context, downloadId);
}
}
};
BroadcastReceiver onNotificationClick=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(ctxt, "Ummmm...hi!", Toast.LENGTH_SHORT).show();
}
};
/**
* Used to open the downloaded attachment.
*
* @param context Content.
* @param downloadId Id of the downloaded file to open.
*/
private void openDownloadedAttachment(final Context context, final long downloadId) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
String downloadLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
String downloadMimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
openDownloadedAttachment(context, Uri.parse(downloadLocalUri), downloadMimeType);
}
}
cursor.close();
}
/**
* Used to open the downloaded attachment.
* <p/>
* 1. Fire intent to open download file using external application.
*
* 2. Note:
* 2.a. We can't share fileUri directly to other application (because we will get FileUriExposedException from Android7.0).
* 2.b. Hence we can only share content uri with other application.
* 2.c. We must have declared FileProvider in manifest.
* 2.c. Refer - https://developer.android.com/reference/android/support/v4/content/FileProvider.html
*
* @param context Context.
* @param attachmentUri Uri of the downloaded attachment to be opened.
* @param attachmentMimeType MimeType of the downloaded attachment.
*/
private void openDownloadedAttachment(final Context context, Uri attachmentUri, final String attachmentMimeType) {
if(attachmentUri!=null) {
// Get Content Uri.
if (ContentResolver.SCHEME_FILE.equals(attachmentUri.getScheme())) {
// FileUri - Convert it to contentUri.
File file = new File(attachmentUri.getPath());
attachmentUri = FileProvider.getUriForFile(context, "${applicationId}.provider", file);;
}
Intent openAttachmentIntent = new Intent(Intent.ACTION_VIEW);
openAttachmentIntent.setDataAndType(attachmentUri, attachmentMimeType);
openAttachmentIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
context.startActivity(openAttachmentIntent);
} catch (Exception e) {
Toast.makeText(context, context.getString(R.string.unable_to_open_file), Toast.LENGTH_LONG).show();
}
}
}
**** add in your Manifest****
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application.....
....
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
......
....
</application>
***** Make a directory in res folder with the name "xml" and then inside "xml"
create a new file with name "file_paths" and addd below code in that file*****
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
**** DONE****