Search code examples
androiddownloadandroid-download-manager

Download Manager Sometimes Displays Unsuccessful


As the title says, I have a download manager and it works but only sometimes. It's very weird and I can't find a pattern. I have a button which when clicked, sends a request to a server which returns the file to download, and then sometimes it downloads, sometimes it doesn't. There's not a pattern that I can see and I'm not getting any errors from the phone or the server.

This is bad for my application because I need to know it's been successfully downloaded so I either need to find out why it doesn't work sometimes, or find a way to run a function if the download fails. Here is the code I use to download the file:

        GlobalVariables globalVariables = new GlobalVariables();
        String url = globalVariables.getIPAddress() + "downloadsong/" + Integer.toString(songId) + "/";
        SharedPreferences sharedPreferences = getSharedPreferences("StoredValues", MODE_PRIVATE);
        String token = sharedPreferences.getString("token", "null");

        DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle("Downloading");
        request.setDescription("Downloading new titles");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, "" + songId + ".mp3");
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.addRequestHeader("Authorization", "Token " + token);
        request.allowScanningByMediaScanner();
        request.setAllowedOverMetered(true);
        request.setAllowedOverRoaming(true);

        long downloadReference = downloadManager.enqueue(request);
        if (downloadReference != 0) {
            Toast.makeText(getApplicationContext(), "download started", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(getApplicationContext(), "no download started", Toast.LENGTH_SHORT).show();
        }

Any help or insight is appreciated. Thanks!


Solution

  • This is my example:

    public class MainActivity extends AppCompatActivity {
    
    private Button button;
    private long downloadID;
    
    private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (downloadID == id) {
                validDownload(MainActivity.this, downloadID);
            }
        }
    };
    
    public void validDownload(Context context, long downloadId) {
        DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (dm != null) {
            try (Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId))) {
                if (c.moveToFirst()) {
                    int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    if (status == DownloadManager.STATUS_SUCCESSFUL) {
                        Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show();
                    } else if (status == DownloadManager.STATUS_FAILED) {
                        Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.download);
        registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                if (downloadManager != null) {
                    downloadID = downloadManager.enqueue(prepareDownloadRequest());
                }
            }
        });
    }
    
    private DownloadManager.Request prepareDownloadRequest() {
        File file = new File(getExternalFilesDir(null), "Dummy");
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://speedtest.ftp.otenet.gr/files/test10Mb.db"))
                .setTitle("Dummy File")
                .setDescription("Downloading")
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
                .setDestinationUri(Uri.fromFile(file))// Uri of the destination file
                .setAllowedOverMetered(true)
                .setAllowedOverRoaming(true);// Set if download is allowed on roaming networ
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            request.setRequiresCharging(false);
        }
        return request;
    }
    

    }