Example usage for android.os Environment DIRECTORY_DOWNLOADS

List of usage examples for android.os Environment DIRECTORY_DOWNLOADS

Introduction

In this page you can find the example usage for android.os Environment DIRECTORY_DOWNLOADS.

Prototype

String DIRECTORY_DOWNLOADS

To view the source code for android.os Environment DIRECTORY_DOWNLOADS.

Click Source Link

Document

Standard directory in which to place files that have been downloaded by the user.

Usage

From source file:gov.cdc.epiinfo.RecordList.java

private void CreateDefaultsFile() {
    try {/*from   www  .j  ava2  s  .  c o m*/
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        path.mkdirs();
        File file = new File(path, "/EpiInfo/defaults.xml");
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fileWriter);
        out.write("<Defaults Form=\"" + viewName + "\" Layout=\"-1\" />");
        out.close();
        Alert("Please restart the application for this action to take effect.");
        mnuSetDefault.setVisible(false);
        mnuExitDefault.setVisible(true);
    } catch (Exception ex) {

    }
}

From source file:gov.cdc.epiinfo.RecordList.java

private void DeleteDefaultsFile() {
    try {/*from   w  w w  . j av  a2  s  .  c  o m*/
        File file1 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                + "/EpiInfo/defaults.xml");
        file1.delete();
        Alert("Please restart the application for this action to take effect.");
        mnuSetDefault.setVisible(true);
        mnuExitDefault.setVisible(false);
    } catch (Exception ex) {

    }
}

From source file:com.stfalcon.contentmanager.ContentManager.java

private String generateFileName(String file) {
    String fileName = UUID.randomUUID().toString() + "." + guessFileExtensionFromUrl(file);
    String probableFileName = fileName;
    File directory = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    File probableFile = new File(directory.getAbsolutePath() + File.separator + probableFileName);
    int counter = 0;
    while (probableFile.exists()) {
        counter++;//from w  w w  . j  a  v a2s .  c om
        if (fileName.contains(".")) {
            int indexOfDot = fileName.lastIndexOf(".");
            probableFileName = fileName.substring(0, indexOfDot - 1) + "-" + counter + "."
                    + fileName.substring(indexOfDot + 1);
        } else {
            probableFileName = fileName + "(" + counter + ")";
        }
        probableFile = new File(directory.getAbsolutePath() + File.separator + probableFileName);
    }
    fileName = probableFileName;

    return directory.getAbsolutePath() + File.separator + fileName;
}

From source file:com.juce.JuceAppActivity.java

public static final String getDownloadsFolder()  { return getFileLocation (Environment.DIRECTORY_DOWNLOADS); }

From source file:com.mb.android.MainActivity.java

@android.webkit.JavascriptInterface
@org.xwalk.core.JavascriptInterface/*w w  w .j av a  2 s.com*/
public void downloadFile(String url, String path) {

    getLogger().Info("Downloading file %s", url);
    String filename = "download";

    if (path != null && path.length() > 0) {
        filename = new File(path).getName();

        // This doesn't appear to handle windows paths
        int index = filename.lastIndexOf('\\');
        if (index != -1) {
            filename = filename.substring(index + 1);
        }
    }

    DownloadManager.Request r = new DownloadManager.Request(android.net.Uri.parse(url));

    // This put the download in the same Download dir the browser uses
    r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);

    // When downloading music and videos they will be listed in the player
    // (Seems to be available since Honeycomb only)
    r.allowScanningByMediaScanner();

    // Notify user when download is completed
    // (Seems to be available since Honeycomb only)
    r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    // Start download
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    dm.enqueue(r);
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createSearchDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_search_tools,
            R.string.search_tools_title);

    final ScrollView scrollView = (ScrollView) dialog.findViewById(R.id.search_tools_dialog_scroll_view);
    final AutoCompleteTextView inputField = (AutoCompleteTextView) dialog
            .findViewById(R.id.search_tools_input_field);
    final LinearLayout rowsContainer = (LinearLayout) dialog.findViewById(R.id.search_tools_row_container);
    final Button viewInMapButton = (Button) dialog.findViewById(R.id.search_tools_view_in_map_button);
    final Button jumpToBottomButton = (Button) dialog.findViewById(R.id.search_tools_jump_to_bottom_button);
    Button dismissButton = (Button) dialog.findViewById(R.id.search_tools_dismiss_button);

    List<PropertyDescription> subscribables;
    PropertyDescription newestSubscribable = null;
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
            Locale.getDefault());
    Date cachedUpdateDateTime;/*from  w w w.  jav a2  s . c o  m*/
    Date newestUpdateDateTime;
    SubscriptionEntry cachedEntry;
    Response response;
    final JSONArray toolsArray;
    ArrayAdapter<String> adapter;
    String format = "JSON";
    String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString() + "/FiskInfo/Offline/";
    final JSONObject tools;
    final List<String> vesselNames;
    final Map<String, List<Integer>> toolIdMap = new HashMap<>();
    byte[] data = new byte[0];

    cachedEntry = user.getSubscriptionCacheEntry(getString(R.string.fishing_facility_api_name));

    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        subscribables = barentswatchApi.getApi().getSubscribable();
        for (PropertyDescription subscribable : subscribables) {
            if (subscribable.ApiName.equals(getString(R.string.fishing_facility_api_name))) {
                newestSubscribable = subscribable;
                break;
            }
        }
    } else if (cachedEntry == null) {
        Dialog infoDialog = dialogInterface.getAlertDialog(getActivity(), R.string.tools_search_no_data_title,
                R.string.tools_search_no_data, -1);

        infoDialog.show();
        return;
    }

    if (cachedEntry != null) {
        try {
            cachedUpdateDateTime = simpleDateFormat
                    .parse(cachedEntry.mLastUpdated.equals(getActivity().getString(R.string.abbreviation_na))
                            ? "2000-00-00T00:00:00"
                            : cachedEntry.mLastUpdated);
            newestUpdateDateTime = simpleDateFormat
                    .parse(newestSubscribable != null ? newestSubscribable.LastUpdated : "2000-00-00T00:00:00");

            if (cachedUpdateDateTime.getTime() - newestUpdateDateTime.getTime() < 0) {
                response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
                try {
                    data = FiskInfoUtility.toByteArray(response.getBody().in());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                        newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath,
                        false)) {
                    SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
                    entry.mLastUpdated = newestSubscribable.LastUpdated;
                    user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
                    user.writeToSharedPref(getActivity());
                }
            } else {
                String directoryFilePath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
                        + "/FiskInfo/Offline/";

                File file = new File(directoryFilePath + newestSubscribable.Name + ".JSON");
                StringBuilder jsonString = new StringBuilder();
                BufferedReader bufferReader = null;

                try {
                    bufferReader = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = bufferReader.readLine()) != null) {
                        jsonString.append(line);
                        jsonString.append('\n');
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bufferReader != null) {
                        try {
                            bufferReader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                data = jsonString.toString().getBytes();
            }

        } catch (ParseException e) {
            e.printStackTrace();
            Log.e(TAG, "Invalid datetime provided");
        }
    } else {
        response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
        try {
            data = FiskInfoUtility.toByteArray(response.getBody().in());
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath, false)) {
            SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
            entry.mLastUpdated = newestSubscribable.LastUpdated;
            user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
        }
    }

    try {
        tools = new JSONObject(new String(data));
        toolsArray = tools.getJSONArray("features");
        vesselNames = new ArrayList<>();
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, vesselNames);

        for (int i = 0; i < toolsArray.length(); i++) {
            JSONObject feature = toolsArray.getJSONObject(i);
            String vesselName = (feature.getJSONObject("properties").getString("vesselname") != null
                    && !feature.getJSONObject("properties").getString("vesselname").equals("null"))
                            ? feature.getJSONObject("properties").getString("vesselname")
                            : getString(R.string.vessel_name_unknown);
            List<Integer> toolsIdList = toolIdMap.get(vesselName) != null ? toolIdMap.get(vesselName)
                    : new ArrayList<Integer>();

            if (vesselName != null && !vesselNames.contains(vesselName)) {
                vesselNames.add(vesselName);
            }

            toolsIdList.add(i);
            toolIdMap.put(vesselName, toolsIdList);
        }

        inputField.setAdapter(adapter);
    } catch (JSONException e) {
        dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                R.string.search_tools_init_info, -1).show();
        Log.e(TAG, "JSON parse error");
        e.printStackTrace();

        return;
    }

    if (searchToolsButton.getTag() != null) {
        inputField.requestFocus();
        inputField.setText(searchToolsButton.getTag().toString());
        inputField.selectAll();
    }

    inputField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedVesselName = ((TextView) view).getText().toString();
            List<Integer> selectedTools = toolIdMap.get(selectedVesselName);
            Gson gson = new Gson();
            String toolSetDateString;
            Date toolSetDate;

            rowsContainer.removeAllViews();

            for (int toolId : selectedTools) {
                JSONObject feature;
                Feature toolFeature;

                try {
                    feature = toolsArray.getJSONObject(toolId);

                    if (feature.getJSONObject("geometry").getString("type").equals("LineString")) {
                        toolFeature = gson.fromJson(feature.toString(), LineFeature.class);
                    } else {
                        toolFeature = gson.fromJson(feature.toString(), PointFeature.class);
                    }

                    toolSetDateString = toolFeature.properties.setupdatetime != null
                            ? toolFeature.properties.setupdatetime
                            : "2038-00-00T00:00:00";
                    toolSetDate = simpleDateFormat.parse(toolSetDateString);

                } catch (JSONException | ParseException e) {
                    dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                            R.string.search_tools_init_info, -1).show();
                    e.printStackTrace();

                    return;
                }

                ToolSearchResultRow row = rowsInterface.getToolSearchResultRow(getActivity(),
                        R.drawable.ikon_kystfiske, toolFeature);
                long toolTime = System.currentTimeMillis() - toolSetDate.getTime();
                long highlightCutoff = ((long) getResources().getInteger(R.integer.milliseconds_in_a_day))
                        * ((long) getResources().getInteger(R.integer.days_to_highlight_active_tool));

                if (toolTime > highlightCutoff) {
                    int colorId = ContextCompat.getColor(getActivity(), R.color.error_red);
                    row.setDateTextViewTextColor(colorId);
                }

                rowsContainer.addView(row.getView());
            }

            viewInMapButton.setEnabled(true);
            inputField.setTag(selectedVesselName);
            searchToolsButton.setTag(selectedVesselName);
            jumpToBottomButton.setVisibility(View.VISIBLE);
            jumpToBottomButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.scrollTo(0, rowsContainer.getBottom());
                        }
                    });
                }
            });

        }
    });

    viewInMapButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String vesselName = inputField.getTag().toString();
            highlightToolsInMap(vesselName);

            dialog.dismiss();
        }
    });

    dismissButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    dialog.show();
}

From source file:net.potterpcs.recipebook.RecipeData.java

public String exportRecipes(long[] ids) throws IOException {
    // TODO file selection, sharing, etc.
    String filename = "exported-recipes-" + System.currentTimeMillis() + ".rcp";
    File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File export = new File(sd, filename);
    FileOutputStream fos = null;/* w  w  w . j a  va  2 s.  c o m*/
    sd.mkdirs();
    try {
        fos = new FileOutputStream(export);
        JSONArray ja = new JSONArray();
        for (long i : ids) {
            ja.put(getSingleRecipeObject(i).toJSON());
        }
        byte[] buffer = ja.toString().getBytes();
        fos.write(buffer);
        return export.toString();
    } catch (FileNotFoundException e) {
        //         Log.e(TAG, e.toString());
        return null;
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

From source file:com.oakesville.mythling.MediaActivity.java

protected void downloadItem(final Item item) {
    try {//  w  ww.j a  v  a2  s  . c  o  m
        final URL baseUrl = getAppSettings().getMythTvServicesBaseUrlWithCredentials();

        String fileUrl = baseUrl + "/Content/GetFile?";
        if (item.getStorageGroup() == null)
            fileUrl += "StorageGroup=None&";
        else
            fileUrl += "StorageGroup=" + item.getStorageGroup().getName() + "&";
        fileUrl += "FileName=" + URLEncoder.encode(item.getFilePath(), "UTF-8");

        Uri uri = Uri.parse(fileUrl.toString());
        ProxyInfo proxyInfo = MediaStreamProxy.needsAuthProxy(uri);
        if (proxyInfo != null) {
            // needs proxying to support authentication since DownloadManager doesn't support
            MediaStreamProxy proxy = new MediaStreamProxy(proxyInfo,
                    AuthType.valueOf(appSettings.getMythTvServicesAuthType()));
            proxy.init();
            proxy.start();
            fileUrl = "http://" + proxy.getLocalhost().getHostAddress() + ":" + proxy.getPort() + uri.getPath();
            if (uri.getQuery() != null)
                fileUrl += "?" + uri.getQuery();
        }

        Log.i(TAG, "Media download URL: " + fileUrl);

        stopProgress();

        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        Request request = new Request(Uri.parse(fileUrl));
        request.setTitle(item.getOneLineTitle());
        String downloadFilePath = null;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File downloadDir = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                if (downloadDir.exists()) {
                    String downloadPath = AppSettings.getExternalStorageDir() + "/";
                    if (getPath() != null && !getPath().isEmpty() && !getPath().equals("/"))
                        downloadPath += getPath() + "/";
                    File destDir = new File(downloadDir + "/" + downloadPath);
                    if (destDir.isDirectory() || destDir.mkdirs()) {
                        downloadFilePath = downloadPath + item.getDownloadFilename();
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                downloadFilePath);
                        request.allowScanningByMediaScanner();
                    }
                }
            }
        } catch (IllegalStateException ex) {
            // store internal
        } catch (Exception ex) {
            // log, report and store internal
            Log.e(TAG, ex.getMessage(), ex);
            if (getAppSettings().isErrorReportingEnabled())
                new Reporter(ex).send();
            Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(),
                    Toast.LENGTH_LONG).show();
        }
        long downloadId = dm.enqueue(request);
        registerDownloadReceiver(item, downloadId);
        Toast.makeText(getApplicationContext(), getString(R.string.downloading_) + item.getOneLineTitle(),
                Toast.LENGTH_LONG).show();
        getAppData().addDownload(new Download(item.getId(), downloadId, downloadFilePath, new Date()));
        if (item.isRecording() && (mediaList.isMythTv28() || getAppSettings().isMythlingMediaServices()))
            new GetCutListTask((Recording) item, downloadId).execute();
    } catch (Exception ex) {
        stopProgress();
        Log.e(TAG, ex.getMessage(), ex);
        if (getAppSettings().isErrorReportingEnabled())
            new Reporter(ex).send();
        Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(), Toast.LENGTH_LONG)
                .show();
    }
}

From source file:me.piebridge.bible.Bible.java

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public DownloadInfo download(String filename) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
        return null;
    }//from   www  . j  ava2  s . c om
    if (getExternalFilesDirWrapper() == null) {
        return null;
    }
    String url = BIBLEDATA_PREFIX + filename;
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setTitle(filename);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    return DownloadInfo.getDownloadInfo(mContext, dm.enqueue(request));
}

From source file:im.delight.android.webview.AdvancedWebView.java

/**
 * Handles a download by loading the file from `fromUrl` and saving it to `toFilename` on the external storage
 * <p/>//ww  w .  j  a v  a  2 s  . com
 * This requires the two permissions `android.permission.INTERNET` and `android.permission.WRITE_EXTERNAL_STORAGE`
 * <p/>
 * Only supported on API level 9 (Android 2.3) and above
 *
 * @param context    a valid `Context` reference
 * @param fromUrl    the URL of the file to download, e.g. the one from `AdvancedWebView.onDownloadRequested(...)`
 * @param toFilename the name of the destination file where the download should be saved, e.g. `myImage.jpg`
 * @return whether the download has been successfully handled or not
 */
@SuppressLint("NewApi")
public static boolean handleDownload(final Context context, final String fromUrl, final String toFilename) {
    if (Build.VERSION.SDK_INT < 9) {
        throw new RuntimeException("Method requires API level 9 or above");
    }

    final Request request = new Request(Uri.parse(fromUrl));
    if (Build.VERSION.SDK_INT >= 11) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, toFilename);

    final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    try {
        try {
            dm.enqueue(request);
        } catch (SecurityException e) {
            if (Build.VERSION.SDK_INT >= 11) {
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            }
            dm.enqueue(request);
        }

        return true;
    }
    // if the download manager app has been disabled on the device
    catch (IllegalArgumentException e) {
        // show the settings screen where the user can enable the download manager app again
        openAppSettings(context, AdvancedWebView.PACKAGE_NAME_DOWNLOAD_MANAGER);

        return false;
    }
}