Java Code Examples for android.webkit.URLUtil#guessFileName()

The following examples show how to use android.webkit.URLUtil#guessFileName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DownloadRequester.java    From AntennaPodSP with MIT License 6 votes vote down vote up
public String getMediafilename(FeedMedia media) {
    String filename;
    String titleBaseFilename = "";

    // Try to generate the filename by the item title
    if (media.getItem() != null && media.getItem().getTitle() != null) {
        String title = media.getItem().getTitle();
        // Delete reserved characters
        titleBaseFilename = title.replaceAll("[\\\\/%\\?\\*:|<>\"\\p{Cntrl}]", "");
        titleBaseFilename = titleBaseFilename.trim();
    }

    String URLBaseFilename = URLUtil.guessFileName(media.getDownload_url(),
            null, media.getMime_type());
    ;

    if (titleBaseFilename != "") {
        // Append extension
        filename = titleBaseFilename + FilenameUtils.EXTENSION_SEPARATOR +
                FilenameUtils.getExtension(URLBaseFilename);
    } else {
        // Fall back on URL file name
        filename = URLBaseFilename;
    }
    return filename;
}
 
Example 2
Source File: RestoreFromBackupActivity.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case RequestCode.SELECT_JSON_FILE:
                selectedFilePath = data.getData();
                rlJsonUp.setVisibility(View.GONE);
                rlJsonPath.setVisibility(View.VISIBLE);
                tlJsonPwd.setVisibility(View.VISIBLE);
                if (selectedFilePath != null) {
                    btnRestore.setEnabled(true);
                    String fileName = URLUtil.guessFileName(selectedFilePath.getLastPathSegment(), null, null);
                    tvJsonPath.setText(fileName);
                } else {
                    Toast.makeText(getApplicationContext(), getString(R.string.restore_backup_wrong_file_name), Toast.LENGTH_LONG).show();
                }
                break;
            case RequestCode.QR_CODE_REQUEST_CODE:
                String result = data.getStringExtra(Extras.QR_CODE_RESULT);
                if (!result.isEmpty()) {
                    String address = filterAddress(result);
                    etBackupPhrase.setText(address);
                }
                break;
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 3
Source File: RestoreFromBackupActivity.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case RequestCode.SELECT_JSON_FILE:
                selectedFilePath = data.getData();
                rlJsonUp.setVisibility(View.GONE);
                rlJsonPath.setVisibility(View.VISIBLE);
                tlJsonPwd.setVisibility(View.VISIBLE);
                if (selectedFilePath != null) {
                    btnRestore.setEnabled(true);
                    String fileName = URLUtil.guessFileName(selectedFilePath.getLastPathSegment(), null, null);
                    tvJsonPath.setText(fileName);
                } else {
                    Toast.makeText(getApplicationContext(), getString(R.string.restore_backup_wrong_file_name), Toast.LENGTH_LONG).show();
                }
                break;
            case RequestCode.QR_CODE_REQUEST_CODE:
                String result = data.getStringExtra(Extras.QR_CODE_RESULT);
                if (!result.isEmpty()) {
                    String address = filterAddress(result);
                    etBackupPhrase.setText(address);
                }
                break;
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 4
Source File: RestoreFromBackupActivity.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case RequestCode.SELECT_JSON_FILE:
                selectedFilePath = data.getData();
                rlJsonUp.setVisibility(View.GONE);
                rlJsonPath.setVisibility(View.VISIBLE);
                tlJsonPwd.setVisibility(View.VISIBLE);
                if (selectedFilePath != null) {
                    btnRestore.setEnabled(true);
                    String fileName = URLUtil.guessFileName(selectedFilePath.getLastPathSegment(), null, null);
                    tvJsonPath.setText(fileName);
                } else {
                    Toast.makeText(getApplicationContext(), getString(R.string.restore_backup_wrong_file_name), Toast.LENGTH_LONG).show();
                }
                break;
            case RequestCode.QR_CODE_REQUEST_CODE:
                String result = data.getStringExtra(Extras.QR_CODE_RESULT);
                if (!result.isEmpty()) {
                    String address = filterAddress(result);
                    etBackupPhrase.setText(address);
                }
                break;
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 5
Source File: Utils.java    From browser with GNU General Public License v2.0 5 votes vote down vote up
public static void downloadFile(final Activity activity, final String url,
		final String userAgent, final String contentDisposition, final boolean privateBrowsing) {
	String fileName = URLUtil.guessFileName(url, null, null);
	DownloadHandler.onDownloadStart(activity, url, userAgent, contentDisposition, null,
			privateBrowsing);
	Log.i(Constants.TAG, "Downloading" + fileName);
}
 
Example 6
Source File: LightningDownloadListener.java    From browser with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onDownloadStart(final String url, final String userAgent,
		final String contentDisposition, final String mimetype, long contentLength) {
	String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					DownloadHandler.onDownloadStart(mActivity, url, userAgent,
							contentDisposition, mimetype, false);
					break;

				case DialogInterface.BUTTON_NEGATIVE:
					break;
			}
		}
	};

	AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); // dialog
	builder.setTitle(fileName)
			.setMessage(mActivity.getResources().getString(R.string.dialog_download))
			.setPositiveButton(mActivity.getResources().getString(R.string.action_download),
					dialogClickListener)
			.setNegativeButton(mActivity.getResources().getString(R.string.action_cancel),
					dialogClickListener).show();
	Log.i(Constants.TAG, "Downloading" + fileName);

}
 
Example 7
Source File: OMADownloadHandler.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Enqueue a download request to the DownloadManager and starts downloading the OMA content.
 *
 * @param downloadId The unique identifier maintained by the Android DownloadManager.
 * @param downloadInfo Information about the download.
 * @param omaInfo Information about the OMA content.
 */
private void downloadOMAContent(long downloadId, DownloadInfo downloadInfo, OMAInfo omaInfo) {
    if (omaInfo == null) return;
    String mimeType = omaInfo.getDrmType();
    if (mimeType == null) {
        mimeType = getOpennableType(mContext.getPackageManager(), omaInfo);
    }
    String fileName = omaInfo.getValue(OMA_NAME);
    String url = omaInfo.getValue(OMA_OBJECT_URI);
    if (TextUtils.isEmpty(fileName)) {
        fileName = URLUtil.guessFileName(url, null, mimeType);
    }
    DownloadInfo newInfo = DownloadInfo.Builder.fromDownloadInfo(downloadInfo)
            .setFileName(fileName)
            .setUrl(url)
            .setMimeType(mimeType)
            .setDescription(omaInfo.getValue(OMA_DESCRIPTION))
            .setContentLength(getSize(omaInfo))
            .build();
    // If installNotifyURI is not empty, the downloaded content cannot
    // be used until the PostStatusTask gets a 200-series response.
    // Don't show complete notification until that happens.
    DownloadItem item = new DownloadItem(true, newInfo);
    item.setSystemDownloadId(downloadId);
    DownloadManagerService.getDownloadManagerService(mContext).enqueueDownloadManagerRequest(
            item, omaInfo.isValueEmpty(OMA_INSTALL_NOTIFY_URI));
    mPendingOMADownloads.put(downloadId, omaInfo);
}
 
Example 8
Source File: ChromeDownloadDelegate.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * For certain download types(OMA for example), android DownloadManager should
 * handle them. Call this function to intercept those downloads.
 *
 * @param url URL to be downloaded.
 * @return whether the DownloadManager should intercept the download.
 */
public boolean shouldInterceptContextMenuDownload(String url) {
    Uri uri = Uri.parse(url);
    String scheme = uri.normalizeScheme().getScheme();
    if (!"http".equals(scheme) && !"https".equals(scheme)) return false;
    String path = uri.getPath();
    // OMA downloads have extension "dm" or "dd". For the latter, it
    // can be handled when native download completes.
    if (path != null && (path.endsWith(".dm"))) {
        if (mTab == null) return true;
        String fileName = URLUtil.guessFileName(
                url, null, OMADownloadHandler.OMA_DRM_MESSAGE_MIME);
        final DownloadInfo downloadInfo =
                new DownloadInfo.Builder().setUrl(url).setFileName(fileName).build();
        WindowAndroid window = mTab.getWindowAndroid();
        if (window.hasPermission(permission.WRITE_EXTERNAL_STORAGE)) {
            onDownloadStartNoStream(downloadInfo);
        } else if (window.canRequestPermission(permission.WRITE_EXTERNAL_STORAGE)) {
            PermissionCallback permissionCallback = new PermissionCallback() {
                @Override
                public void onRequestPermissionsResult(
                        String[] permissions, int[] grantResults) {
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        onDownloadStartNoStream(downloadInfo);
                    }
                }
            };
            window.requestPermissions(
                    new String[] {permission.WRITE_EXTERNAL_STORAGE}, permissionCallback);
        }
        return true;
    }
    return false;
}
 
Example 9
Source File: FrescoUtil.java    From MyImageUtil with Apache License 2.0 5 votes vote down vote up
/**
 * 拷贝到某一个目录中,自动命名
 * @param url
 * @param dir
 * @return
 */
public static File copyCacheFileToDir(String url,File dir){
    url = append(url);
    if (dir == null ){
        return null;
    }
    if (!dir.isDirectory()){
        throw  new RuntimeException(dir + "is not a directory,you should call copyCacheFile(String url,File path)");
    }
    if (!dir.exists()){
        dir.mkdirs();
    }
    String fileName = URLUtil.guessFileName(url,"","");//android SDK 提供的方法.
    // 注意不能直接采用file的getName拿到文件名,因为缓存文件是用cacheKey命名的
    if (TextUtils.isEmpty(fileName)){
        fileName = UUID.randomUUID().toString();
    }
    File newFile = new File(dir,fileName);

   boolean isSuccess =  copyCacheFile(url,newFile);
    if (isSuccess){
        return newFile;
    }else {
        return null;
    }

}
 
Example 10
Source File: OMADownloadHandler.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Enqueue a download request to the DownloadManager and starts downloading the OMA content.
 *
 * @param downloadId The unique identifier maintained by the Android DownloadManager.
 * @param downloadInfo Information about the download.
 * @param omaInfo Information about the OMA content.
 */
private void downloadOMAContent(long downloadId, DownloadInfo downloadInfo, OMAInfo omaInfo) {
    if (omaInfo == null) return;
    String mimeType = omaInfo.getDrmType();
    if (mimeType == null) {
        mimeType = getOpennableType(mContext.getPackageManager(), omaInfo);
    }
    String fileName = omaInfo.getValue(OMA_NAME);
    String url = omaInfo.getValue(OMA_OBJECT_URI);
    if (TextUtils.isEmpty(fileName)) {
        fileName = URLUtil.guessFileName(url, null, mimeType);
    }
    DownloadInfo newInfo = DownloadInfo.Builder.fromDownloadInfo(downloadInfo)
            .setFileName(fileName)
            .setUrl(url)
            .setMimeType(mimeType)
            .setDescription(omaInfo.getValue(OMA_DESCRIPTION))
            .setContentLength(getSize(omaInfo))
            .build();
    // If installNotifyURI is not empty, the downloaded content cannot
    // be used until the PostStatusTask gets a 200-series response.
    // Don't show complete notification until that happens.
    DownloadItem item = new DownloadItem(true, newInfo);
    item.setSystemDownloadId(downloadId);
    DownloadManagerService.getDownloadManagerService(mContext).enqueueDownloadManagerRequest(
            item, omaInfo.isValueEmpty(OMA_INSTALL_NOTIFY_URI));
    mPendingOMADownloads.put(downloadId, omaInfo);
}
 
Example 11
Source File: ChromeDownloadDelegate.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * For certain download types(OMA for example), android DownloadManager should
 * handle them. Call this function to intercept those downloads.
 *
 * @param url URL to be downloaded.
 * @return whether the DownloadManager should intercept the download.
 */
public boolean shouldInterceptContextMenuDownload(String url) {
    Uri uri = Uri.parse(url);
    String scheme = uri.normalizeScheme().getScheme();
    if (!"http".equals(scheme) && !"https".equals(scheme)) return false;
    String path = uri.getPath();
    // OMA downloads have extension "dm" or "dd". For the latter, it
    // can be handled when native download completes.
    if (path == null || !path.endsWith(".dm")) return false;
    if (mTab == null) return true;
    String fileName = URLUtil.guessFileName(
            url, null, OMADownloadHandler.OMA_DRM_MESSAGE_MIME);
    final DownloadInfo downloadInfo =
            new DownloadInfo.Builder().setUrl(url).setFileName(fileName).build();
    WindowAndroid window = mTab.getWindowAndroid();
    if (window.hasPermission(permission.WRITE_EXTERNAL_STORAGE)) {
        onDownloadStartNoStream(downloadInfo);
    } else if (window.canRequestPermission(permission.WRITE_EXTERNAL_STORAGE)) {
        PermissionCallback permissionCallback = new PermissionCallback() {
            @Override
            public void onRequestPermissionsResult(
                    String[] permissions, int[] grantResults) {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onDownloadStartNoStream(downloadInfo);
                }
            }
        };
        window.requestPermissions(
                new String[] {permission.WRITE_EXTERNAL_STORAGE}, permissionCallback);
    }
    return true;
}
 
Example 12
Source File: FrescoUtils.java    From FrescoUtlis with Apache License 2.0 5 votes vote down vote up
/**
 * 拷贝到某一个目录中,自动命名
 * @param url
 * @param dir
 * @return
 */
public static File copyCacheFileToDir(String url,File dir){

    if (dir == null ){
        return null;
    }
    if (!dir.isDirectory()){
        throw  new RuntimeException(dir + "is not a directory,you should call copyCacheFile(String url,File path)");
    }
    if (!dir.exists()){
        dir.mkdirs();
    }
    String fileName = URLUtil.guessFileName(url,"","");//android SDK 提供的方法.
    // 注意不能直接采用file的getName拿到文件名,因为缓存文件是用cacheKey命名的
    if (TextUtils.isEmpty(fileName)){
        fileName = UUID.randomUUID().toString();
    }
    File newFile = new File(dir,fileName);

   boolean isSuccess =  copyCacheFile(url,newFile);
    if (isSuccess){
        return newFile;
    }else {
        return null;
    }

}
 
Example 13
Source File: Downloader.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
private String getFilenameFromUrl(String urlString) {
    String fileName = URLUtil.guessFileName(urlString, null, null);

    if (fileName.contains("#"))
        return fileName.split("#")[0];
    else if (fileName.contains("?"))
        return fileName.split("\\?")[0];
    else
        return fileName;

}
 
Example 14
Source File: OMADownloadHandler.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Enqueue a download request to the DownloadManager and starts downloading the OMA content.
 *
 * @param downloadId The unique identifier maintained by the Android DownloadManager.
 * @param downloadInfo Information about the download.
 * @param omaInfo Information about the OMA content.
 */
@VisibleForTesting
protected void downloadOMAContent(long downloadId, DownloadInfo downloadInfo, OMAInfo omaInfo) {
    if (omaInfo == null) return;
    String mimeType = omaInfo.getDrmType();
    if (mimeType == null) {
        mimeType = getOpennableType(mContext.getPackageManager(), omaInfo);
    }
    String fileName = omaInfo.getValue(OMA_NAME);
    String url = omaInfo.getValue(OMA_OBJECT_URI);
    if (TextUtils.isEmpty(fileName)) {
        fileName = URLUtil.guessFileName(url, null, mimeType);
    }
    DownloadInfo newInfo = DownloadInfo.Builder.fromDownloadInfo(downloadInfo)
            .setFileName(fileName)
            .setUrl(url)
            .setMimeType(mimeType)
            .setDescription(omaInfo.getValue(OMA_DESCRIPTION))
            .setBytesReceived(getSize(omaInfo))
            .build();
    // If installNotifyURI is not empty, the downloaded content cannot
    // be used until the PostStatusTask gets a 200-series response.
    // Don't show complete notification until that happens.
    DownloadItem item = new DownloadItem(true, newInfo);
    item.setSystemDownloadId(downloadId);
    mDownloadManagerDelegate.enqueueDownloadManagerRequest(
            item, omaInfo.isValueEmpty(OMA_INSTALL_NOTIFY_URI), this);
    mPendingOMADownloads.put(downloadId, omaInfo);
}
 
Example 15
Source File: ChromeDownloadDelegate.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * For certain download types(OMA for example), android DownloadManager should
 * handle them. Call this function to intercept those downloads.
 *
 * @param url URL to be downloaded.
 * @return whether the DownloadManager should intercept the download.
 */
public boolean shouldInterceptContextMenuDownload(String url) {
    Uri uri = Uri.parse(url);
    String scheme = uri.normalizeScheme().getScheme();
    if (!UrlConstants.HTTP_SCHEME.equals(scheme) && !UrlConstants.HTTPS_SCHEME.equals(scheme)) {
        return false;
    }
    String path = uri.getPath();
    if (!OMADownloadHandler.isOMAFile(path)) return false;
    if (mTab == null) return true;
    String fileName = URLUtil.guessFileName(
            url, null, OMADownloadHandler.OMA_DRM_MESSAGE_MIME);
    final DownloadInfo downloadInfo =
            new DownloadInfo.Builder().setUrl(url).setFileName(fileName).build();
    WindowAndroid window = mTab.getWindowAndroid();
    if (window.hasPermission(permission.WRITE_EXTERNAL_STORAGE)) {
        onDownloadStartNoStream(downloadInfo);
    } else if (window.canRequestPermission(permission.WRITE_EXTERNAL_STORAGE)) {
        PermissionCallback permissionCallback = new PermissionCallback() {
            @Override
            public void onRequestPermissionsResult(
                    String[] permissions, int[] grantResults) {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onDownloadStartNoStream(downloadInfo);
                }
            }
        };
        window.requestPermissions(
                new String[] {permission.WRITE_EXTERNAL_STORAGE}, permissionCallback);
    }
    return true;
}