How to fix download files as .bin in Android Webview App

If you are having issue of download file as .bin format on your hybird Android webview app, you may add MIMEtype on DownlaodManger.request as follow:

request.setMimeType(mimeType="audio/mpeg");

 

Here is a sample code for your ref:

webViewWeb.setDownloadListener(new DownloadListener()
        {
            @Override
             public void onDownloadStart(String url, String userAgent,String contentDisposition, String mimeType,long contentLength) {

                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (ActivityCompat.checkSelfPermission(Objects.requireNonNull(getActivity()), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider writing
                            ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_REQUEST);

                            return;
                        }
                    }

                    String string = String.valueOf((URLUtil.guessFileName(url, contentDisposition, mimeType)));

                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                    request.setMimeType(mimeType="audio/mpeg");
                    String cookies = CookieManager.getInstance().getCookie(url);

                    String string_d = resources.getString(R.string.downloading_file);

                    request.addRequestHeader("cookie", cookies);
                    request.addRequestHeader("User-Agent", userAgent);
                    request.allowScanningByMediaScanner();
                    request.setDescription(string_d);
                    request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                    request.allowScanningByMediaScanner();

                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS ,  string);

                    DownloadManager dm = (DownloadManager)getActivity().getSystemService(DOWNLOAD_SERVICE);
                    dm.enqueue(request);

                    String string2 = resources.getString(R.string.downloading_file);
                    Toast.makeText(getContext(), string2, Toast.LENGTH_LONG).show();

                    }

        }

 

 

Published on: 03/01/2022, 8:25 AM