Home > Software design >  Trouble with dowload file from Android app
Trouble with dowload file from Android app

Time:12-07

It is necessary to download a file from a web server through the application, but the file is not loaded, here is the code that I am using:

 manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
 Uri uri = Uri.parse("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf");
 DownloadManager.Request request = new DownloadManager.Request(uri);
 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
 long reference = manager.enqueue(request);

In the manifest, I have these permissions:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
    <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES"/>

The file is created on the device, but the mark is "in the queue" and nothing further happens.

If you just follow the links in the browser, then the download occurs without problems.

Through the settings - access to the device's memory is also checked.

Where did I go wrong?

CodePudding user response:

Please just try this class of code way may help you

public class DownloadHelper {
    private long downloadReference = 0
    private DownloadManager downloadManager;
    DownloadCompleteListener completeListener= null;
    
    public interface DownloadCompleteListener{
        void ondownloadComplete(String name,String path,Uri uri);
        void ondownloadFailled(String error);
    }


    private BroadcastReceiver receiver = new BroadcastReceiver () {
        
        @Override
        void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (downloadId != downloadReference) {
                    context.unregisterReceiver(this);
                    return;
                }
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadReference);
                Cursor cursor = downloadManager.query(query);
                if(cursor != null){
                    if (cursor.moveToFirst()) {
                        int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(columnIndex)) {
                            String localFile = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                            String localName = localFile.substring(localFile.lastIndexOf("/") 1);//cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME))
                            completeListener.ondownloadComplete(localName,localFile,null);
                        } else if (DownloadManager.STATUS_FAILED == cursor.getInt(columnIndex)) {
                            completeListener.ondownloadFailled(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)));
                        }
                    }else{
                        completeListener.ondownloadFailled("Download cancelled or failled");
                    }
                    cursor.close();
                }else{
                    completeListener.ondownloadFailled("Download cancelled or failled");
                }
                context.unregisterReceiver(this);
            }
        }
    };

    public String getallreadyfile(String name){
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .getAbsolutePath().toString()   "/"   name;
    }

    public void downloadFile(Context context,String url,String mimeType,DownloadCompleteListener completeListener) {
        this.completeListener = completeListener;
        String guessFileName = URLUtil.guessFileName(url, null, mimeType);
        if(url == null || url.isEmpty()){            
            return;
        }
        String allreadyfile = getallreadyfile(guessFileName);
        File applictionFile = new File(allreadyfile);
        if(isAllreadyAvailabel(context,applictionFile)){
            completeListener.ondownloadComplete(applictionFile.getName(),applictionFile.getAbsolutePath(),null);
            return
        }

        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        //setAllowedOverRoaming(true)
//            setTitle(guessFileName)
//            setDescription(guessFileName)
//            setVisibleInDownloadsUi(true)
        request.allowScanningByMediaScanner();
//            setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)

        //request.setDestinationUri(Uri.fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)))
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, guessFileName);

        context.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        downloadReference = downloadManager.enqueue(request);
    }

    public boolean isAllreadyAvailabel(Context context,File applictionFile){
        if(applictionFile.canRead() && applictionFile.length()>0) {
            return true;
        }else{
            try {
                File file = new File(applictionFile.getAbsolutePath());
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
  • Related