Android browser overwrite download prompt [Android source code browser Series 1]

Source: Internet
Author: User

The official Android browser is really not well written. Last month, I made a function to modify the Browser Download. If this file is available in sdcard, a dialog will pop up, the prompt is "the file already exists. Do you want to overwrite it? ", Yes. delete the file and download it again. If not, no operation is performed! The process of Google source code is to download a file with another name. For details, see the naming rule for repeated file downloads in Android [Android source code parsing 7, introduction to naming rules for files downloaded from Google source code!

Daming original, reproduced please indicate the source: http://blog.csdn.net/wdaming1986/article/details/7413150

 

Main ideas:

1. Analyze the naming rules for Android downloads;

2. Analyze the path to save the downloaded Android files;

3. The path + file name can constitute a file to determine whether the file exists?

4. When dialog is displayed, the system prompts whether to overwrite it?

5. If you select Yes, delete the file and download it again. If you select no, no operation is performed!

 

See the code below: in the browser project;

In/* package */void/* download stream */ondownloadstartnostream (string URL, string useragent,
String contentdisposition, string mimetype, long contentlength ){

In this method:

Modify final URI contenturi = getcontentresolver (). insert (downloads. impl. content_uri,
Values );

This method;

private static String sdcardPath = "/mnt/sdcard/download/";            /*add by wangxianming in order to make the same file             *when downloading Prompt             *"whether is cover the file or not"             *on 2012-3-2             *on start             */boolean isInsert = true;File base = new File(sdcardPath);                String downloadfilename = filename.replaceAll("[^a-zA-Z0-9\\.\\-_]+", "_");                // Split filename between base and extension                // Add an extension if filename does not have one                String extension = null;                int dotIndex = downloadfilename.indexOf('.');                if (dotIndex < 0) {                    extension = chooseExtensionFromMimeType(mimetype, true);                } else {                    extension = chooseExtensionFromFilename(mimetype, downloadfilename, dotIndex);                }                if(extension != null && !"".equals(extension) && extension.length() > 1){                    base = new File(base,extension.substring(1).toLowerCase());                }                final String sdcardFilePath = base.getPath() + File.separator + downloadfilename;                File downloadFilePath = new File(sdcardFilePath);                if(downloadFilePath != null && downloadFilePath.exists()) {                    isInsert = false;                    new AlertDialog.Builder(this).setTitle(R.string.clear_history_tips)                            .setIcon(android.R.drawable.ic_dialog_alert).setMessage(                                    R.string.download_cover_or_not).setPositiveButton(                                    R.string.ok, new DialogInterface.OnClickListener() {                                        public void onClick(DialogInterface dialog,                                                int whichButton) {                                            int deleteNumRow = getContentResolver().delete(                                                    Downloads.Impl.CONTENT_URI,                                                    Downloads.Impl.COLUMN_FILE_NAME_HINT + "='"                                                            + filename + "'", null);                                            if (deleteNumRow != 0) {                                                if (sdcardFilePath != null) {                                                    File downloadfile = new File(sdcardFilePath);                                                    downloadfile.delete();                                                }                                            }                                            final Uri contentUri = getContentResolver().insert(Downloads.Impl.CONTENT_URI,                                                    values);                                            Toast.makeText(BrowserActivity.this, R.string.download_pending, Toast.LENGTH_SHORT).show();                                        }                                    }).setNegativeButton(R.string.cancel,                                    new DialogInterface.OnClickListener() {                                        public void onClick(DialogInterface dialog,                                                int whichButton) {                                        }                                    }).create().show();                }                if (isInsert) {                    final Uri contentUri = getContentResolver().insert(Downloads.Impl.CONTENT_URI,                            values);                    Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT).show();                }//on end

Method for Determining the type:

private static String chooseExtensionFromMimeType(String mimeType, boolean useDefaults) {        String extension = null;        if (mimeType != null) {            extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);            if (extension != null) {                if (true) {                    Log.v(LOGTAG, "adding extension from type");                }                extension = "." + extension;            } else {                if (true) {                    Log.v(LOGTAG, "couldn't find extension for " + mimeType);                }            }        }        if (extension == null) {            if (mimeType != null && mimeType.toLowerCase().startsWith("text/")) {                if (mimeType.equalsIgnoreCase("text/html")) {                    Log.v(LOGTAG, "adding default html extension");                    extension = ".html";                } else if (useDefaults) {                    Log.v(LOGTAG, "adding default text extension");                    extension = ".txt";                }            } else if (useDefaults) {                Log.v(LOGTAG, "adding default binary extension");                extension = ".bin";            }        }        return extension;    }

 

Truncate the last ., all files downloaded by Android in browser are placed in the download folder, and different types of files are intercepted before creating folders, such as MP3, APK, and so on. These files can all be folder names, then download the downloaded file category to the corresponding folder, and capture the ". as follows:

private static String chooseExtensionFromFilename(String mimeType,            String filename, int dotIndex) {        String extension = null;        if (mimeType != null) {            // Compare the last segment of the extension against the mime type.            // If there's a mismatch, discard the entire extension.            int lastDotIndex = filename.lastIndexOf('.');            String typeFromExt = MimeTypeMap.getSingleton().getMimeTypeFromExtension(                    filename.substring(lastDotIndex + 1));            if (typeFromExt == null || !typeFromExt.equalsIgnoreCase(mimeType)) {                extension = chooseExtensionFromMimeType(mimeType, false);                if (extension != null) {                    Log.v(LOGTAG, "substituting extension from type");                } else {                    Log.v(LOGTAG, "couldn't find extension for " + mimeType);                }            }        }        if (extension == null) {            Log.v(LOGTAG, "keeping extension");            extension = filename.substring(dotIndex);        }        return extension;    }

 

 

Variable for assembling the path of the entire file: final string sdcardfilepath = base. getpath () + file. Separator + downloadfilename;

 

In this way, it's okay. After testing and running for more than one month, there is no problem. Haha, so I will share the Code with you. This function has been implemented for three days! The middle thought went wrong. I took the URL from the database, which caused the judgment method to be not very good. After my boss instructed me to determine whether the file exists? So I did it with this idea. After one day, everything went well! It's a bit rewarding! You can leave a message if you have any good ideas! Share your thoughts and improve your communication skills!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.