morristech
3/29/2019 - 6:47 AM

DownloadManager - download files using DownloadManager

DownloadManager - download files using DownloadManager

public class NewsDetailActivity extends AppCompatActivity implements View.OnClickListener {
Activity activity;
Toolbar toolbar;
File TEMP_FILE_SAVE_PATH = Environment.getExternalStorageDirectory();
String TEMP_FILE_NAME = "news_";
String URL="";
private DownloadManager downloadManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);
        findViews();
        if (newsmedia != null) {
            downloadref = new long[newsmedia.length];
            String fileName =URL.substring(URL.lastIndexOf('/') + 1);
            final File file = new File(Environment.getExternalStorageDirectory(), "/" + getResources().getString(R.string.app_name) + "/" + fileName);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int status = checkStatus(downloadref[id]);
                        if (file.exists() && status != DownloadManager.STATUS_RUNNING && status != DownloadManager.STATUS_PENDING) {
                            Uri uri = Uri.fromFile(file);
                            Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
                            String mime = "*/*";
                            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
                            if (mimeTypeMap.hasExtension(
                                    mimeTypeMap.getFileExtensionFromUrl(uri.toString())))
                                mime = mimeTypeMap.getMimeTypeFromExtension(
                                        mimeTypeMap.getFileExtensionFromUrl(uri.toString()));
                            intent.setDataAndType(uri, mime);
                            startActivity(intent);
                        } else {
                            if (status == DownloadManager.STATUS_RUNNING || status == DownloadManager.STATUS_PENDING) {
                                downloadManager.remove(downloadref[id]);
                                Toast.makeText(activity, "Download cancelled...", Toast.LENGTH_LONG).show();
                            } else {
                                downloadref[id] = downloadMedia(newsmedia[id].getUrl());
                            }
                        }
                    }
                });
            } 
            }

            IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            registerReceiver(downloadReceiver, filter);
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(downloadReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    public long downloadMedia(String URL) {
        long downloadReference;

        Uri Download_Uri = Uri.parse(URL);
        DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
        //Restrict the types of networks over which this download may proceed.
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        //Set whether this download may proceed over a roaming connection.
        request.setAllowedOverRoaming(false);
        //Set the title of this download, to be displayed in notifications (if enabled).
        request.setTitle(getResources().getString(R.string.app_name));
        //Set a description of this download, to be displayed in notifications (if enabled)
        request.setDescription("Downloding...");
        
        //TO USE THIS ADD PERMISSION IN MANIFEST
        <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
        request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
        //Set the local destination for the downloaded file to a path within the application's external files directory
        //request.setDestinationInExternalPublicDir(getResources().getString(R.string.app_name), "h‌​c.mp3");
        String fileName = URL.substring(URL.lastIndexOf('/') + 1);
        request.setDestinationInExternalPublicDir(getResources().getString(R.string.app_name), fileName);
        //Enqueue a new download and same the referenceId
        downloadReference = downloadManager.enqueue(request);
        Log.i("downloadReference", "" + downloadReference);

        return downloadReference;
    }

    @Override
    public void onClick(View v) {

    }

    private int checkStatus(long downloadReference) {
        DownloadManager.Query myDownloadQuery = new DownloadManager.Query();
        //set the query filter to our previously Enqueued download
        myDownloadQuery.setFilterById(downloadReference);
        //Query the download manager about downloads that have been requested.
        Cursor cursor = downloadManager.query(myDownloadQuery);
        if (cursor.moveToFirst()) {
            //checkStatus(cursor);

            //column for status
            int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            int status = cursor.getInt(columnIndex);
            //column for reason code if the download failed or paused
            int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
            int reason = cursor.getInt(columnReason);
            //get the download filename
            int filenameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
            String filename = cursor.getString(filenameIndex);

            String statusText = "";
            String reasonText = "";

            switch (status) {
                case DownloadManager.STATUS_FAILED:
                    statusText = "STATUS_FAILED";
                    switch (reason) {
                        case DownloadManager.ERROR_CANNOT_RESUME:
                            reasonText = "ERROR_CANNOT_RESUME";
                            break;
                        case DownloadManager.ERROR_DEVICE_NOT_FOUND:
                            reasonText = "ERROR_DEVICE_NOT_FOUND";
                            break;
                        case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
                            reasonText = "ERROR_FILE_ALREADY_EXISTS";
                            break;
                        case DownloadManager.ERROR_FILE_ERROR:
                            reasonText = "ERROR_FILE_ERROR";
                            break;
                        case DownloadManager.ERROR_HTTP_DATA_ERROR:
                            reasonText = "ERROR_HTTP_DATA_ERROR";
                            break;
                        case DownloadManager.ERROR_INSUFFICIENT_SPACE:
                            reasonText = "ERROR_INSUFFICIENT_SPACE";
                            break;
                        case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
                            reasonText = "ERROR_TOO_MANY_REDIRECTS";
                            break;
                        case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
                            reasonText = "ERROR_UNHANDLED_HTTP_CODE";
                            break;
                        case DownloadManager.ERROR_UNKNOWN:
                            reasonText = "ERROR_UNKNOWN";
                            break;
                    }
                    break;
                case DownloadManager.STATUS_PAUSED:
                    statusText = "STATUS_PAUSED";
                    switch (reason) {
                        case DownloadManager.PAUSED_QUEUED_FOR_WIFI:
                            reasonText = "PAUSED_QUEUED_FOR_WIFI";
                            break;
                        case DownloadManager.PAUSED_UNKNOWN:
                            reasonText = "PAUSED_UNKNOWN";
                            break;
                        case DownloadManager.PAUSED_WAITING_FOR_NETWORK:
                            reasonText = "PAUSED_WAITING_FOR_NETWORK";
                            break;
                        case DownloadManager.PAUSED_WAITING_TO_RETRY:
                            reasonText = "PAUSED_WAITING_TO_RETRY";
                            break;
                    }
                    break;
                case DownloadManager.STATUS_PENDING:
                    statusText = "STATUS_PENDING";
                    break;
                case DownloadManager.STATUS_RUNNING:
                    statusText = "STATUS_RUNNING";
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    statusText = "STATUS_SUCCESSFUL";
                    reasonText = "Filename:\n" + filename;
                    break;
            }


            Toast toast = Toast.makeText(NewsDetailActivity.this,
                    statusText + "\n" +
                            reasonText,
                    Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP, 25, 400);
            toast.show();
            return status;
        }
        return 0;
    }

    private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            //check if the broadcast message is for our Enqueued download
            long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (downloadReference == referenceId) {

            Button cancelDownload = (Button) findViewById(R.id.cancelDownload);
            cancelDownload.setEnabled(false);

            Toast toast = Toast.makeText(NewsDetailActivity.this,
                    "Download completed.", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP, 25, 400);
            toast.show();

           }
        }
    };

    void findViews() {
        activity = this;
        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    }
}