0

I have a download feature in my android app. When I download a file, it will notify me by toast. I want to know how to have a toast notification when the download complete. I have trying other suggestions but haven't succeed in finding the result I expected.

Here is the download code.

webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                                        String mimeType, long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.setMimeType(mimeType);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie",cookies);
                request.addRequestHeader("User-Agent",userAgent);
                request.setDescription("Downloading File");
                request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                        URLUtil.guessFileName(url, contentDisposition, mimeType));
                DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                downloadManager.enqueue(request);
                Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
            }
        });

Thank you in advance.

Gedanggoreng
  • 186
  • 2
  • 11

2 Answers2

0

You can create a Broadcast Receiver to handle any file that had completed downloading :

Main Activity

public class MainActivity extends AppCompatActivity {

// create an object
OnComplete onComplete ;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    WebView webView = null;
    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition,
                                    String mimeType, long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setMimeType(mimeType);
            String cookies = CookieManager.getInstance().getCookie(url);
            request.addRequestHeader("cookie",cookies);
            request.addRequestHeader("User-Agent",userAgent);
            request.setDescription("Downloading File");
            request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                    URLUtil.guessFileName(url, contentDisposition, mimeType));
            DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            downloadManager.enqueue(request);
            Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
        }
    });

    // the broadcast receiver object
    onComplete = new OnComplete();

}

@Override
protected void onResume() {
    super.onResume();
    // to start handling any download that completes
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

@Override
protected void onPause() {
    super.onPause();
    // to stop handling download complete when exit app
    unregisterReceiver(onComplete);
}

}

The Broadcast Receiver (OnComplete)

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class OnComplete extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    // these codes will run when download completed
    // And you can do some thing
}
}

and please don't forget to add this in your Mainfest.xml at the <application/> tag

<receiver android:name=".OnComplete" />
a7d.24_
  • 170
  • 1
  • 12
  • I have another question here (https://stackoverflow.com/questions/69002074/open-pdf-automatically-after-downloaded). Can you help? – Gedanggoreng Aug 31 '21 at 17:04
  • You realize that in onReceive() you can obtain an uri for the downloaded file? You can use that uri in an ACTION_VIEW intent to let your file be opened by the pdf reader the user chooses. – blackapps Aug 31 '21 at 17:43
  • @blackapps Yes sir,you are right and this will be a great add to the app – a7d.24_ Aug 31 '21 at 18:11
  • @blackapps Please can you explain in detail how to do that? I really don't know how to do that. – Gedanggoreng Aug 31 '21 at 18:19
  • This is what I did in on Receive -> @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context.getApplicationContext(), "Download Success", Toast.LENGTH_SHORT).show(); } } – Gedanggoreng Aug 31 '21 at 18:22
  • @Gedanggoreng the `intent` that you get in `onReceive();` contains a data you can get it with `Uri uri = intent.getData(); ` then you can use this `uri` to open the file but, every file has it's way to open it ,so you should search for that. have a nice day ! – a7d.24_ Aug 31 '21 at 18:27
  • @Override public void onReceive(Context context, Intent intent) { Uri uri = intent.getData(); Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW); pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); pdfOpenintent.setDataAndType(uri, "application/pdf"); try { context.startActivity(pdfOpenintent); } catch (ActivityNotFoundException e) { Toast.makeText(context.getApplicationContext(), "No PDF Viewer Installed", Toast.LENGTH_LONG).show(); } } } -> Cannot display PDF (No Data Received) – Gedanggoreng Aug 31 '21 at 18:56
  • You forgot to set a flag permission to read uri. – blackapps Aug 31 '21 at 19:16
  • Uri uri = intent.getData(); Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW); pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION); pdfOpenintent.setDataAndType(uri, "application/pdf"); try { context.startActivity(pdfOpenintent); } -> Still Same Error "Cannot display PDF (No Data Received)" – Gedanggoreng Aug 31 '21 at 19:31
0

Thanks to @a7d.24_ for the answer given.

I have simplified the answer so I didn't need to create new Java Class (OnComplete) and therefore no need to add it to the Manifest.XML.

I just have to add single line of code inside webView.setDownloadListener and create new BroadcastReceiver in the WebView Class.

 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 ...

        webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition,
                                    String mimeType, long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setMimeType(mimeType);
            String cookies = CookieManager.getInstance().getCookie(url);
            request.addRequestHeader("cookie",cookies);
            request.addRequestHeader("User-Agent",userAgent);
            request.setDescription("Downloading File");
            request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                    URLUtil.guessFileName(url, contentDisposition, mimeType));
            DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            //Registering receiver in Download Manager
            registerReceiver(onCompleted, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));    
            downloadManager.enqueue(request);
            Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
        }
    });

 ...

 BroadcastReceiver onCompleted = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context.getApplicationContext(), "Download Finish", Toast.LENGTH_SHORT).show();
Gedanggoreng
  • 186
  • 2
  • 11