List of usage examples for android.os Environment DIRECTORY_DOWNLOADS
String DIRECTORY_DOWNLOADS
To view the source code for android.os Environment DIRECTORY_DOWNLOADS.
Click Source Link
From source file:com.cuddlesoft.nori.fragment.ImageFragment.java
/** * Use the system {@link android.app.DownloadManager} service to download the image. *///www. j a v a2s. c om protected void downloadImage() { // Get download manager system service. DownloadManager downloadManager = (DownloadManager) getActivity() .getSystemService(Context.DOWNLOAD_SERVICE); // Extract file name from URL. String fileName = image.fileUrl.substring(image.fileUrl.lastIndexOf("/") + 1); // Create download directory, if it does not already exist. //noinspection ResultOfMethodCallIgnored Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs(); // Create and queue download request. DownloadManager.Request request = new DownloadManager.Request(Uri.parse(image.fileUrl)).setTitle(fileName) .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName) .setVisibleInDownloadsUi(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Trigger media scanner to add image to system gallery app on Honeycomb and above. request.allowScanningByMediaScanner(); // Show download UI notification on Honeycomb and above. request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } downloadManager.enqueue(request); }
From source file:file_manager.Activity_files.java
private void setFilesList() { deleteDatabase("files_DB_v01.db"); String folder = sharedPref.getString("folder", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()); File f = new File(sharedPref.getString("files_startFolder", folder)); final File[] files = f.listFiles(); if (files == null || files.length == 0) { Snackbar.make(listView, R.string.toast_files, Snackbar.LENGTH_LONG).show(); } else {// w w w . ja v a2 s . c o m // looping through all items <item> for (File file : files) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String file_Name = file.getName(); String file_Size = getReadableFileSize(file.length()); String file_date = formatter.format(new Date(file.lastModified())); String file_path = file.getAbsolutePath(); String file_ext; if (file.isDirectory()) { file_ext = "."; } else { file_ext = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".")); } db.open(); if (file_ext.equals(".") || file_ext.equals(".pdf") || file_ext.equals(".") || file_ext.equals(".jpg") || file_ext.equals(".JPG") || file_ext.equals(".jpeg") || file_ext.equals(".png")) { if (db.isExist(file_Name)) { Log.i(TAG, "Entry exists" + file_Name); } else { db.insert(file_Name, file_Size, file_ext, file_path, file_date); } } } } try { db.insert("...", "", "", "", ""); } catch (Exception e) { Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show(); } //display data final int layoutstyle = R.layout.list_item; int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes }; String[] column = new String[] { "files_title", "files_content", "files_creation" }; final Cursor row = db.fetchAllData(this); adapter = new SimpleCursorAdapter(this, layoutstyle, row, column, xml_id, 0) { @Override public View getView(final int position, View convertView, ViewGroup parent) { Cursor row2 = (Cursor) listView.getItemAtPosition(position); final String files_icon = row2.getString(row2.getColumnIndexOrThrow("files_icon")); final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment")); final String files_title = row2.getString(row2.getColumnIndexOrThrow("files_title")); final File pathFile = new File(files_attachment); View v = super.getView(position, convertView, parent); final ImageView iv = (ImageView) v.findViewById(R.id.icon_notes); iv.setVisibility(View.VISIBLE); if (pathFile.isDirectory()) { iv.setImageResource(R.drawable.folder); } else { switch (files_icon) { case ".gif": case ".bmp": case ".tiff": case ".svg": case ".png": case ".jpg": case ".JPG": case ".jpeg": try { Uri uri = Uri.fromFile(pathFile); Picasso.with(Activity_files.this).load(uri).resize(76, 76).centerCrop().into(iv); } catch (Exception e) { Log.w("HHS_Moodle", "Error Load image", e); } break; case ".pdf": iv.setImageResource(R.drawable.file_pdf); break; default: iv.setImageResource(R.drawable.arrow_up_dark); break; } } if (files_title.equals("...")) { new Handler().postDelayed(new Runnable() { public void run() { iv.setImageResource(R.drawable.arrow_up_dark); } }, 200); } return v; } }; //display data by filter final String note_search = sharedPref.getString("filter_filesBY", "files_title"); sharedPref.edit().putString("filter_filesBY", "files_title").apply(); filter.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.getFilter().filter(s.toString()); } }); adapter.setFilterQueryProvider(new FilterQueryProvider() { public Cursor runQuery(CharSequence constraint) { return db.fetchDataByFilter(constraint.toString(), note_search); } }); listView.setAdapter(adapter); //onClick function listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) { Cursor row2 = (Cursor) listView.getItemAtPosition(position); final String files_icon = row2.getString(row2.getColumnIndexOrThrow("files_icon")); final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment")); final File pathFile = new File(files_attachment); if (pathFile.isDirectory()) { try { sharedPref.edit().putString("files_startFolder", files_attachment).apply(); setFilesList(); } catch (Exception e) { Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show(); } } else if (files_attachment.equals("")) { try { final File pathActual = new File(sharedPref.getString("files_startFolder", Environment.getExternalStorageDirectory().getPath())); sharedPref.edit().putString("files_startFolder", pathActual.getParent()).apply(); setFilesList(); } catch (Exception e) { Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show(); } } else if (files_icon.equals(".pdf")) { Uri uri = Uri.fromFile(pathFile); Intent intent = new Intent(Activity_files.this, MuPDFActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.setData(uri); startActivity(intent); } else { helper_main.open(files_icon, Activity_files.this, pathFile, listView); } } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Cursor row2 = (Cursor) listView.getItemAtPosition(position); final String files_title = row2.getString(row2.getColumnIndexOrThrow("files_title")); final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment")); final File pathFile = new File(files_attachment); if (pathFile.isDirectory()) { Snackbar snackbar = Snackbar .make(listView, R.string.toast_remove_confirmation, Snackbar.LENGTH_LONG) .setAction(R.string.toast_yes, new View.OnClickListener() { @Override public void onClick(View view) { deleteRecursive(pathFile); setFilesList(); } }); snackbar.show(); } else { final CharSequence[] options = { getString(R.string.choose_menu_2), getString(R.string.choose_menu_3), getString(R.string.choose_menu_4) }; final AlertDialog.Builder dialog = new AlertDialog.Builder(Activity_files.this); dialog.setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); dialog.setItems(options, new DialogInterface.OnClickListener() { @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void onClick(DialogInterface dialog, int item) { if (options[item].equals(getString(R.string.choose_menu_2))) { if (pathFile.exists()) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("image/png"); sharingIntent.putExtra(Intent.EXTRA_SUBJECT, files_title); sharingIntent.putExtra(Intent.EXTRA_TEXT, files_title); Uri bmpUri = Uri.fromFile(pathFile); sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri); startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_file)))); } } if (options[item].equals(getString(R.string.choose_menu_4))) { Snackbar snackbar = Snackbar .make(listView, R.string.toast_remove_confirmation, Snackbar.LENGTH_LONG) .setAction(R.string.toast_yes, new View.OnClickListener() { @Override public void onClick(View view) { pathFile.delete(); setFilesList(); } }); snackbar.show(); } if (options[item].equals(getString(R.string.choose_menu_3))) { AlertDialog.Builder builder = new AlertDialog.Builder(Activity_files.this); View dialogView = View.inflate(Activity_files.this, R.layout.dialog_edit_file, null); final EditText edit_title = (EditText) dialogView.findViewById(R.id.pass_title); edit_title.setText(files_title); builder.setView(dialogView); builder.setTitle(R.string.choose_title); builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String inputTag = edit_title.getText().toString().trim(); File dir = pathFile.getParentFile(); File to = new File(dir, inputTag); pathFile.renameTo(to); pathFile.delete(); setFilesList(); } }); builder.setNegativeButton(R.string.toast_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); AlertDialog dialog2 = builder.create(); // Display the custom alert dialog on interface dialog2.show(); helper_main.showKeyboard(Activity_files.this, edit_title); } } }); dialog.show(); } return true; } }); }
From source file:me.kartikarora.transfersh.adapters.FileGridAdapter.java
private void beginDownload(String name, String type, String url) { tracker.send(new HitBuilders.EventBuilder().setCategory("Action").setAction("Download : " + url).build()); DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse(url);//w w w . ja v a 2s . co m DownloadManager.Request request = new DownloadManager.Request(uri); request.setDescription(context.getString(R.string.app_name)); request.setTitle(name); String dir = "/" + context.getString(R.string.app_name) + "/" + type + "/" + name; request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, dir); manager.enqueue(request); }
From source file:com.tonyodev.fetch.request.Request.java
private static String generateDirectoryName() { return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); }
From source file:net.sarangnamu.scroll_capture.MainActivity.java
private void scrollCapture() { mProgress.setVisibility(View.VISIBLE); BkCfg.hideKeyboard(mUrl);/*w w w . j av a2 s . co m*/ if (mLog.isDebugEnabled()) { String log = ""; log += "===================================================================\n"; log += "CAPTURE START\n"; log += "===================================================================\n"; mLog.debug(log); } new AsyncTask<Object, Integer, Boolean>() { Bitmap mBmp; @Override protected void onPreExecute() { int w, h; try { Picture pic = mWeb.capturePicture(); w = pic.getWidth(); h = pic.getHeight(); } catch (Exception e) { w = mWeb.getMeasuredWidth(); h = mWeb.getMeasuredHeight(); } mWeb.measure( View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); mBmp = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(mBmp); mWeb.draw(canvas); } @Override protected Boolean doInBackground(Object... objects) { Context context = (Context) objects[0]; File dnPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File ssPath = new File(dnPath, "screenshot"); if (!ssPath.exists()) { ssPath.mkdirs(); } String fileName = "test.png"; // DateFormat.format("yyyyMMdd-HHmmss", new Date()) + ".png"; File ssFile = new File(ssPath, fileName); try { FileOutputStream os = new FileOutputStream(ssFile); mBmp.compress(Bitmap.CompressFormat.PNG, 90, os); os.flush(); os.close(); sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + ssFile.getAbsolutePath()))); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return true; } @Override protected void onPostExecute(Boolean result) { if (mBmp != null) { mBmp.recycle(); mBmp = null; } if (mLog.isDebugEnabled()) { String log = ""; log += "===================================================================\n"; log += "CAPTURE END\n"; log += "===================================================================\n"; mLog.debug(log); } mProgress.setVisibility(View.GONE); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, MainActivity.this); }
From source file:uk.ac.ucl.excites.sapelli.collector.CollectorApp.java
/** * @return// w ww . j a v a 2 s .c o m * @throws FileStorageException */ private FileStorageProvider initialiseFileStorage() throws FileStorageException { File sapelliFolder = null; // Try to get Sapelli folder path from preferences: try { sapelliFolder = new File(preferences.getSapelliFolderPath()); } catch (NullPointerException npe) { } // Did we get the folder path from preferences? ... if (sapelliFolder == null) { // No: first installation or reset // Find appropriate files dir (using application-specific folder, which is removed upon app uninstall!): File[] paths = DeviceControl.getExternalFilesDirs(this, null); if (paths != null && paths.length != 0) { // We count backwards because we prefer secondary external storage (which is likely to be on an SD card rather unremovable memory) for (int p = paths.length - 1; p >= 0; p--) if (isMountedReadableWritableDir(paths[p])) { sapelliFolder = paths[p]; break; } } // Do we have a path? if (sapelliFolder != null) // Yes: store it in the preferences: preferences.setSapelliFolder(sapelliFolder.getAbsolutePath()); else // No :-( throw new FileStorageUnavailableException(); } else { // Yes, we got path from preferences, check if it is available ... if (!isMountedReadableWritableDir(sapelliFolder)) // (will also attempt to create the directory if it doesn't exist) // No :-( throw new FileStorageRemovedException(sapelliFolder.getAbsolutePath()); } // If we get here this means we have a non-null sapelliFolder object representing an accessible path... // Try to get the Android Downloads folder... File downloadsFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); if (!isMountedReadableWritableDir(downloadsFolder)) // check if we can access it (will also attempt to create the directory if it doesn't exist) // No :-( throw new FileStorageException("Cannot access downloads folder: " + downloadsFolder.getAbsolutePath()); // Return path provider return new AndroidFileStorageProvider(sapelliFolder, downloadsFolder); // Android specific subclass of FileStorageProvider, which generates .nomedia files }
From source file:com.tcity.android.ui.info.BuildArtifactsFragment.java
@NotNull private DownloadManager.Request calculateArtifactRequest(@NotNull BuildArtifact artifact) { if (artifact.contentHref == null) { throw new IllegalStateException("Build artifact hasn't content"); }//from ww w. ja v a 2 s . c om Preferences preferences = new Preferences(getActivity()); Uri src = Uri.parse(preferences.getUrl() + artifact.contentHref); String dest = artifact.name; DownloadManager.Request request = new DownloadManager.Request(src); request.addRequestHeader("Authorization", "Basic " + preferences.getAuth()); request.setTitle(dest); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, dest); return request; }
From source file:it.telecomitalia.my.base_struct_apps.VersionUpdate.java
@Override protected Void doInBackground(String... urls) { /* metodo principale per aggiornamento */ String xml = ""; try {/* ww w . ja v a 2 s . co m*/ /* tento di leggermi il file XML remoto */ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(SERVER + PATH + VERSIONFILE); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); /* ora in xml c' il codice della pagina degli aggiornamenti */ } catch (IOException e) { e.printStackTrace(); } // TODO: org.apache.http.conn.HttpHostConnectException ovvero host non raggiungibile try { /* nella variabile xml, c' il codice della pagina remota per gli aggiornamenti. * Per le mie esigenze, prendo dall'xml l'attributo value per vedere a che versione la * applicazione sul server.*/ DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // http://stackoverflow.com/questions/1706493/java-net-malformedurlexception-no-protocol InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8")); Document dom = db.parse(is); Element element = dom.getDocumentElement(); Element current = (Element) element.getElementsByTagName("current").item(0); currentVersion = current.getAttribute("value"); currentApkName = current.getAttribute("apk"); } catch (Exception e) { e.printStackTrace(); } /* con il costruttore ho stabilito quale versione sta girando sul terminale, e con questi * due try, mi son letto XML remoto e preso la versione disponibile sul server e il relativo * nome dell'apk, caso ai dovesse servirmi. Ora li confronto e decido che fare */ if (currentVersion != null & runningVersion != null) { /* esistono, li trasformo in double */ Double serverVersion = Double.parseDouble(currentVersion); Double localVersion = Double.parseDouble(runningVersion); /* La versione server superiore alla mia ! Occorre aggiornare */ if (serverVersion > localVersion) { try { /* connessione al server */ URL urlAPK = new URL(SERVER + PATH + currentApkName); HttpURLConnection con = (HttpURLConnection) urlAPK.openConnection(); con.setRequestMethod("GET"); con.setDoOutput(true); con.connect(); // qual' la tua directory di sistema Download ? File downloadPath = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File outputFile = new File(downloadPath, currentApkName); //Log.i("test", downloadPath.getAbsolutePath()); //Log.i("test", outputFile.getAbsolutePath()); // se esistono download parziali o vecchi, li elimino. if (outputFile.exists()) outputFile.delete(); /* mi creo due File Stream uno di input, quello che sto scaricando dal server, * e l'altro di output, quello che sto creando nella directory Download*/ InputStream input = con.getInputStream(); FileOutputStream output = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int count = 0; while ((count = input.read(buffer)) != -1) { output.write(buffer, 0, count); } output.close(); input.close(); /* una volta terminato il processo, attraverso un intent lancio il file che ho * appena scaricato in modo da installare immediatamente l'aggiornamento come * specificato qui * http://stackoverflow.com/questions/4967669/android-install-apk-programmatically*/ Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(outputFile.getAbsolutePath())), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } } return null; }
From source file:com.zsxj.pda.ui.client.LoginActivity.java
private void download(String url) { DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); Uri downloadUri = Uri.parse(url);/* w ww. ja va2 s. com*/ DownloadManager.Request request = new DownloadManager.Request(downloadUri); String fileName = url.substring(url.lastIndexOf("/") + 1); File downloadDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); Log.d("debug", downloadDir.toString()); File updateFile = new File(downloadDir, fileName); Log.d("debug", updateFile.toString()); if (updateFile.exists()) { Intent promtInstall = new Intent(Intent.ACTION_VIEW); promtInstall.setDataAndType(Uri.fromFile(updateFile), "application/vnd.android.package-archive"); startActivity(promtInstall); finish(); } else { request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName); long downloadId = dm.enqueue(request); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putLong(PrefKeys.DOWNLOAD_ID, downloadId); editor.commit(); } }
From source file:model.Document.java
/** * @return the validity in memory of this Document. A document is valid in * memory during a week// w w w . j av a 2 s .com */ public boolean isOnMemory() { if (mLoadedDate.plusWeeks(1).isAfterNow()) { // Exits the function if the storage is not writable! if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Log.d("ClaroClient", "Missing SDCard"); return false; } File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File file = new File(root.getAbsolutePath(), getTitle() + "." + getExtension()); return file.exists() && file.canRead(); } return false; }