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:de.baumann.browser.Browser_right.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwoDark)); WebView.enableSlowWholeDocumentDraw(); setContentView(R.layout.activity_browser); helper_main.onStart(Browser_right.this); PreferenceManager.setDefaultValues(this, R.xml.user_settings, false); PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); sharedPref.edit()/* ww w. j a v a 2s. c om*/ .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/")) .apply(); sharedPref.edit().putInt("keyboard", 0).apply(); sharedPref.getInt("keyboard", 0); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setBackgroundColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwo)); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer); progressBar = (ProgressBar) findViewById(R.id.progressBar); editText = (EditText) findViewById(R.id.editText); editText.setVisibility(View.GONE); editText.setHint(R.string.app_search_hint); editText.clearFocus(); urlBar = (TextView) findViewById(R.id.urlBar); imageButton = (ImageButton) findViewById(R.id.imageButton); imageButton.setVisibility(View.INVISIBLE); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mWebView.scrollTo(0, 0); imageButton.setVisibility(View.INVISIBLE); if (!actionBar.isShowing()) { urlBar.setText(mWebView.getTitle()); actionBar.show(); } helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right); } }); SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe); assert swipeView != null; swipeView.setColorSchemeResources(R.color.colorTwo, R.color.colorAccent); swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mWebView.reload(); } }); mWebView = (ObservableWebView) findViewById(R.id.webView); if (sharedPref.getString("fullscreen", "2").equals("2") || sharedPref.getString("fullscreen", "2").equals("3")) { mWebView.setScrollViewCallbacks(this); } mWebChromeClient = new myWebChromeClient(); mWebView.setWebChromeClient(mWebChromeClient); imageButton_left = (ImageButton) findViewById(R.id.imageButton_left); imageButton_right = (ImageButton) findViewById(R.id.imageButton_right); if (sharedPref.getBoolean("arrow", false)) { imageButton_left.setVisibility(View.VISIBLE); imageButton_right.setVisibility(View.VISIBLE); } else { imageButton_left.setVisibility(View.INVISIBLE); imageButton_right.setVisibility(View.INVISIBLE); } helper_webView.webView_Settings(Browser_right.this, mWebView); helper_webView.webView_WebViewClient(Browser_right.this, swipeView, mWebView, urlBar); mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); if (isNetworkUnAvailable()) { if (sharedPref.getBoolean("offline", false)) { if (isNetworkUnAvailable()) { // loading offline mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show(); } } else { Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show(); } } mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimetype, long contentLength) { registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); Snackbar snackbar = Snackbar .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG) .setAction(getString(R.string.toast_yes), new View.OnClickListener() { @Override public void onClick(View view) { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url)); request.allowScanningByMediaScanner(); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed! request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(request); Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename, Snackbar.LENGTH_SHORT).show(); } }); snackbar.show(); } }); helper_browser.toolbar(Browser_right.this, Browser_left.class, mWebView, toolbar); helper_editText.editText_EditorAction(editText, Browser_right.this, mWebView, urlBar); helper_editText.editText_FocusChange(editText, Browser_right.this); helper_main.grantPermissionsStorage(Browser_right.this); onNewIntent(getIntent()); }
From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.FiskInfoUtility.java
public boolean writeMapLayerToExternalStorage(Activity activity, byte[] data, String writableName, String format, String downloadSavePath, boolean showToasts) { if (FiskInfoUtility.shouldAskPermission()) { String[] perms = { "android.permission.WRITE_EXTERNAL_STORAGE" }; int permsRequestCode = 0x001; // activity.requestPermissions(perms, permsRequestCode); ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, permsRequestCode);/* w ww. j a va 2 s . c o m*/ } String filePath; OutputStream outputStream = null; filePath = downloadSavePath; boolean success = false; String fileEnding = format; File directory = filePath == null ? null : new File(filePath); if (directory != null && !directory.isDirectory() && !directory.mkdirs()) { directory = null; } if (directory == null) { String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) .toString(); String directoryName = "FiskInfo"; filePath = directoryPath + "/" + directoryName + "/"; new File(filePath).mkdirs(); } if (fileEnding != null && fileEnding.equals(activity.getBaseContext().getString(R.string.olex))) { fileEnding = "olx.gz"; } try { File dir = new File(filePath); File file = new File(filePath + writableName + "." + fileEnding); if (!dir.canWrite()) { Toast.makeText(activity.getBaseContext(), R.string.error_cannot_write_to_directory, Toast.LENGTH_LONG); throw new IOException(activity.getResources().getString(R.string.error_cannot_write_to_directory)); } // index 1 is leef when plugged in. Dirs[1].getAbsoluteFile() is writable // File[] dirs = ContextCompat.getExternalFilesDirs(activity.getBaseContext(), null); outputStream = new FileOutputStream(file); outputStream.write(data); if (showToasts) { Toast.makeText(activity.getBaseContext(), "Fil lagret til " + filePath, Toast.LENGTH_LONG).show(); } success = true; } catch (IOException e) { if (showToasts) { Toast.makeText(activity.getBaseContext(), R.string.disk_write_failed, Toast.LENGTH_LONG).show(); } e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return success; }
From source file:mgks.os.webview.MainActivity.java
@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" }) @Override/*from w ww . java 2 s .co m*/ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.w("READ_PERM = ", Manifest.permission.READ_EXTERNAL_STORAGE); Log.w("WRITE_PERM = ", Manifest.permission.WRITE_EXTERNAL_STORAGE); //Prevent the app from being started again when it is still alive in the background if (!isTaskRoot()) { finish(); return; } setContentView(R.layout.activity_main); asw_view = findViewById(R.id.msw_view); final SwipeRefreshLayout pullfresh = findViewById(R.id.pullfresh); if (ASWP_PULLFRESH) { pullfresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { pull_fresh(); pullfresh.setRefreshing(false); } }); asw_view.getViewTreeObserver() .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if (asw_view.getScrollY() == 0) { pullfresh.setEnabled(true); } else { pullfresh.setEnabled(false); } } }); } else { pullfresh.setRefreshing(false); pullfresh.setEnabled(false); } if (ASWP_PBAR) { asw_progress = findViewById(R.id.msw_progress); } else { findViewById(R.id.msw_progress).setVisibility(View.GONE); } asw_loading_text = findViewById(R.id.msw_loading_text); Handler handler = new Handler(); //Launching app rating request if (ASWP_RATINGS) { handler.postDelayed(new Runnable() { public void run() { get_rating(); } }, 1000 * 60); //running request after few moments } //Getting basic device information get_info(); //Getting GPS location of device if given permission if (ASWP_LOCATION && !check_permission(1)) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm); } get_location(); //Webview settings; defaults are customized for best performance WebSettings webSettings = asw_view.getSettings(); if (!ASWP_OFFLINE) { webSettings.setJavaScriptEnabled(ASWP_JSCRIPT); } webSettings.setSaveFormData(ASWP_SFORM); webSettings.setSupportZoom(ASWP_ZOOM); webSettings.setGeolocationEnabled(ASWP_LOCATION); webSettings.setAllowFileAccess(true); webSettings.setAllowFileAccessFromFileURLs(true); webSettings.setAllowUniversalAccessFromFileURLs(true); webSettings.setUseWideViewPort(true); webSettings.setDomStorageEnabled(true); asw_view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); asw_view.setHapticFeedbackEnabled(false); asw_view.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) { if (!check_permission(2)) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }, file_perm); } else { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setMimeType(mimeType); String cookies = CookieManager.getInstance().getCookie(url); request.addRequestHeader("cookie", cookies); request.addRequestHeader("User-Agent", userAgent); request.setDescription(getString(R.string.dl_downloading)); request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType)); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); assert dm != null; dm.enqueue(request); Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG) .show(); } } }); if (Build.VERSION.SDK_INT >= 21) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark)); asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null); webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } else if (Build.VERSION.SDK_INT >= 19) { asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null); } asw_view.setVerticalScrollBarEnabled(false); asw_view.setWebViewClient(new Callback()); //Rendering the default URL aswm_view(ASWV_URL, false); asw_view.setWebChromeClient(new WebChromeClient() { //Handling input[type="file"] requests for android API 16+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { if (ASWP_FUPLOAD) { asw_file_message = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(ASWV_F_TYPE); if (ASWP_MULFILE) { i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } startActivityForResult(Intent.createChooser(i, getString(R.string.fl_chooser)), asw_file_req); } } //Handling input[type="file"] requests for android API 21+ public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (check_permission(2) && check_permission(3)) { if (ASWP_FUPLOAD) { if (asw_file_path != null) { asw_file_path.onReceiveValue(null); } asw_file_path = filePathCallback; Intent takePictureIntent = null; if (ASWP_CAMUPLOAD) { takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) { File photoFile = null; try { photoFile = create_image(); takePictureIntent.putExtra("PhotoPath", asw_cam_message); } catch (IOException ex) { Log.e(TAG, "Image file creation failed", ex); } if (photoFile != null) { asw_cam_message = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); } else { takePictureIntent = null; } } } Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); if (!ASWP_ONLYCAM) { contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType(ASWV_F_TYPE); if (ASWP_MULFILE) { contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } } Intent[] intentArray; if (takePictureIntent != null) { intentArray = new Intent[] { takePictureIntent }; } else { intentArray = new Intent[0]; } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser)); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooserIntent, asw_file_req); } return true; } else { get_file(); return false; } } //Getting webview rendering progress @Override public void onProgressChanged(WebView view, int p) { if (ASWP_PBAR) { asw_progress.setProgress(p); if (p == 100) { asw_progress.setProgress(0); } } } // overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { if (Build.VERSION.SDK_INT < 23 || check_permission(1)) { // location permissions were granted previously so auto-approve callback.invoke(origin, true, false); } else { // location permissions not granted so request them ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm); } } }); if (getIntent().getData() != null) { String path = getIntent().getDataString(); /* If you want to check or use specific directories or schemes or hosts Uri data = getIntent().getData(); String scheme = data.getScheme(); String host = data.getHost(); List<String> pr = data.getPathSegments(); String param1 = pr.get(0); */ aswm_view(path, false); } }
From source file:com.brewcrewfoo.performance.activities.PCSettings.java
@Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { String key = preference.getKey(); if (key.equals("use_light_theme")) { mPreferences.edit().putBoolean("theme_changed", true).commit(); finish();/*from w w w. j a v a2 s. c o m*/ return true; } else if (key.equals("visible_tabs")) { startActivity(new Intent(this, HideTabs.class)); return true; } else if (key.equals("boot_mode")) { if (mInitd.isChecked()) { LayoutInflater factory = LayoutInflater.from(this); final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null); final EditText tv = (EditText) editDialog.findViewById(R.id.vprop); final TextView tn = (TextView) editDialog.findViewById(R.id.nprop); tv.setText(mPreferences.getString("script_name", "99PC")); tn.setText(""); tn.setVisibility(TextView.GONE); new AlertDialog.Builder(this).setTitle(getString(R.string.pt_script_name)).setView(editDialog) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String s = tv.getText().toString(); if ((s != null) && (s.length() > 0)) { mPreferences.edit().putString("script_name", s).apply(); } mInitd.setSummary(INIT_D + mPreferences.getString("script_name", "99PC")); new BootClass(c, mPreferences).writeScript(); } }).create().show(); } else { final StringBuilder sb = new StringBuilder(); sb.append("mount -o rw,remount /system;\n"); sb.append("busybox rm ").append(INIT_D).append(mPreferences.getString("script_name", "99PC")) .append(";\n"); sb.append("mount -o ro,remount /system;\n"); Helpers.shExec(sb, c, true); } return true; } else if (key.equals("int_sd")) { LayoutInflater factory = LayoutInflater.from(this); final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null); final EditText tv = (EditText) editDialog.findViewById(R.id.vprop); final TextView tn = (TextView) editDialog.findViewById(R.id.nprop); tv.setText(""); tn.setText(getString(R.string.info_auto_sd)); new AlertDialog.Builder(this).setTitle(getString(R.string.pt_int_sd)).setView(editDialog) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String s = tv.getText().toString(); if ((s != null) && (s.length() > 0)) { if (s.endsWith("/")) { s = s.substring(0, s.length() - 1); } if (!s.startsWith("/")) { s = "/" + s; } final File dir = new File(s); if (dir.exists() && dir.isDirectory() && dir.canRead() && dir.canWrite()) mPreferences.edit().putString("int_sd_path", s).apply(); } else { mPreferences.edit().remove("int_sd_path").apply(); } mIntSD.setSummary(mPreferences.getString("int_sd_path", Environment.getExternalStorageDirectory().getAbsolutePath())); } }).create().show(); } else if (key.equals("ext_sd")) { LayoutInflater factory = LayoutInflater.from(this); final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null); final EditText tv = (EditText) editDialog.findViewById(R.id.vprop); final TextView tn = (TextView) editDialog.findViewById(R.id.nprop); tv.setText(""); tn.setText(getString(R.string.info_auto_sd)); new AlertDialog.Builder(this).setTitle(getString(R.string.pt_ext_sd)).setView(editDialog) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String s = tv.getText().toString(); if ((s != null) && (s.length() > 0)) { if (s.endsWith("/")) { s = s.substring(0, s.length() - 1); } if (!s.startsWith("/")) { s = "/" + s; } final File dir = new File(s); if (dir.exists() && dir.isDirectory() && dir.canRead() && dir.canWrite()) mPreferences.edit().putString("ext_sd_path", s).apply(); } else { mPreferences.edit().remove("ext_sd_path").apply(); } mExtSD.setSummary(mPreferences.getString("ext_sd_path", Helpers.extSD())); } }).create().show(); } else if (key.equals("br_op")) { startActivity(new Intent(this, BackupRestore.class)); } else if (key.equals("version_info")) { if (isupdate && !NO_UPDATE) { LayoutInflater factory = LayoutInflater.from(this); final View editDialog = factory.inflate(R.layout.ver_dialog, null); final TextView msg = (TextView) editDialog.findViewById(R.id.msg); msg.setText(det); new AlertDialog.Builder(c).setView(editDialog).setTitle(getString(R.string.pt_update)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setPositiveButton(getString(R.string.btn_download), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (isDownloadManagerAvailable(c)) { String url = URL + TAG + ".apk"; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); //request.setDescription(""); request.setTitle(TAG + " " + ver); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { request.allowScanningByMediaScanner(); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, TAG + "-" + ver + ".apk"); DownloadManager manager = (DownloadManager) getSystemService( Context.DOWNLOAD_SERVICE); manager.enqueue(request); } else { Toast.makeText(c, getString(R.string.no_download_manager), Toast.LENGTH_LONG) .show(); } } }).create().show(); } return true; } else if (key.equals("pref_donate")) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(PAYPAL + PAYPAL_BTN))); } return false; }
From source file:de.baumann.browser.Browser_left.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(ContextCompat.getColor(Browser_left.this, R.color.colorPrimaryDark)); WebView.enableSlowWholeDocumentDraw(); setContentView(R.layout.activity_browser); helper_main.checkPin(Browser_left.this); helper_main.onStart(Browser_left.this); PreferenceManager.setDefaultValues(this, R.xml.user_settings, false); PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); sharedPref.edit().putBoolean("isOpened", true).apply(); boolean show = sharedPref.getBoolean("introShowDo_notShow", true); if (show) {// ww w . ja v a 2s . co m helper_main.switchToActivity(Browser_left.this, Activity_intro.class, "", false); } sharedPref.edit() .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/")) .apply(); sharedPref.edit().putInt("keyboard", 0).apply(); sharedPref.getInt("keyboard", 0); if (sharedPref.getString("saved_key_ok", "no").equals("no")) { char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!$%&/()=?;:_-.,+#*<>" .toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 25; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } sharedPref.edit().putString("saved_key", sb.toString()).apply(); sharedPref.edit().putString("saved_key_ok", "yes").apply(); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer); progressBar = (ProgressBar) findViewById(R.id.progressBar); editText = (EditText) findViewById(R.id.editText); editText.setVisibility(View.GONE); editText.setHint(R.string.app_search_hint); editText.clearFocus(); urlBar = (TextView) findViewById(R.id.urlBar); imageButton = (ImageButton) findViewById(R.id.imageButton); imageButton.setVisibility(View.INVISIBLE); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mWebView.scrollTo(0, 0); imageButton.setVisibility(View.INVISIBLE); if (!actionBar.isShowing()) { urlBar.setText(mWebView.getTitle()); actionBar.show(); } helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right); } }); SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe); assert swipeView != null; swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent); swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mWebView.reload(); } }); mWebView = (ObservableWebView) findViewById(R.id.webView); if (sharedPref.getString("fullscreen", "2").equals("2") || sharedPref.getString("fullscreen", "2").equals("3")) { mWebView.setScrollViewCallbacks(this); } mWebChromeClient = new myWebChromeClient(); mWebView.setWebChromeClient(mWebChromeClient); imageButton_left = (ImageButton) findViewById(R.id.imageButton_left); imageButton_right = (ImageButton) findViewById(R.id.imageButton_right); if (sharedPref.getBoolean("arrow", false)) { imageButton_left.setVisibility(View.VISIBLE); imageButton_right.setVisibility(View.VISIBLE); } else { imageButton_left.setVisibility(View.INVISIBLE); imageButton_right.setVisibility(View.INVISIBLE); } helper_webView.webView_Settings(Browser_left.this, mWebView); helper_webView.webView_WebViewClient(Browser_left.this, swipeView, mWebView, urlBar); mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); if (isNetworkUnAvailable()) { if (sharedPref.getBoolean("offline", false)) { if (isNetworkUnAvailable()) { // loading offline mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show(); } } else { Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show(); } } mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimetype, long contentLength) { registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); Snackbar snackbar = Snackbar .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG) .setAction(getString(R.string.toast_yes), new View.OnClickListener() { @Override public void onClick(View view) { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url)); request.allowScanningByMediaScanner(); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed! request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(request); Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename, Snackbar.LENGTH_SHORT).show(); } }); snackbar.show(); } }); helper_browser.toolbar(Browser_left.this, Browser_right.class, mWebView, toolbar); helper_editText.editText_EditorAction(editText, Browser_left.this, mWebView, urlBar); helper_editText.editText_FocusChange(editText, Browser_left.this); helper_main.grantPermissionsStorage(Browser_left.this); onNewIntent(getIntent()); }
From source file:com.android.mail.browse.AttachmentActionHandler.java
private File performAttachmentSave(final Attachment attachment) { try {/*from ww w .j av a2 s . c o m*/ File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); downloads.mkdirs(); File file = createUniqueFile(downloads, attachment.getName()); Uri contentUri = attachment.contentUri; InputStream in = mContext.getContentResolver().openInputStream(contentUri); OutputStream out = new FileOutputStream(file); int size = IOUtils.copy(in, out); out.flush(); out.close(); in.close(); String absolutePath = file.getAbsolutePath(); MediaScannerConnection.scanFile(mContext, new String[] { absolutePath }, null, null); DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); dm.addCompletedDownload(attachment.getName(), attachment.getName(), false /* do not use media scanner */, attachment.getContentType(), absolutePath, size, true /* show notification */); Toast.makeText(mContext, mContext.getResources().getString(R.string.save_to) + absolutePath, Toast.LENGTH_SHORT).show(); return file; } catch (IOException ioe) { // Ignore. Callers will handle it from the return code. } return null; }
From source file:jackpal.androidterm.TermPreferences.java
private void confirmWritePrefs() { File pathExternalPublicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); String downloadDir = pathExternalPublicDir.getPath(); final String filename = downloadDir + "/" + BuildConfig.APPLICATION_ID + ".xml"; if (new File(filename).exists()) { AlertDialog.Builder bld = new AlertDialog.Builder(this); bld.setIcon(android.R.drawable.ic_dialog_info); bld.setMessage(this.getString(R.string.prefs_write_confirm)); bld.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss();/*from w w w.j ava 2s .c o m*/ writePrefs(filename); } }); bld.setNegativeButton(this.getString(android.R.string.no), null); bld.create().show(); } else { writePrefs(filename); return; } }
From source file:org.wso2.app.catalog.api.ApplicationManager.java
/** * Initiate downloading via DownloadManager API. * * @param url - File URL.//from w ww. j a va 2 s . co m * @param appName - Name of the application to be downloaded. */ private void downloadViaDownloadManager(String url, String appName) { DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Uri downloadUri = Uri.parse(url); DownloadManager.Request request = new DownloadManager.Request(downloadUri); // 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(resources.getString(R.string.downloader_message_title)); // Set a description of this download, to be displayed in // notifications (if enabled) request.setDescription(resources.getString(R.string.downloader_message_description) + appName); // Set the local destination for the downloaded file to a path // within the application's external files directory request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, appName); // Enqueue a new download and same the referenceId downloadReference = downloadManager.enqueue(request); }
From source file:com.nbplus.hybrid.BasicWebViewClient.java
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // for excel download if (isDocumentMimeType(url)) { Log.d(TAG, "This url is document mimetype = " + url); if (StorageUtils.isExternalStorageWritable()) { Uri source = Uri.parse(url); // Make a new request pointing to the mp3 url DownloadManager.Request request = new DownloadManager.Request(source); // Use the same file name for the destination File destinationFile = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), source.getLastPathSegment()); request.setDestinationUri(Uri.fromFile(destinationFile)); // Add it to the manager mDownloadManager.enqueue(request); Toast.makeText(mContext, R.string.downloads_requested, Toast.LENGTH_SHORT).show(); } else {//from ww w . ja v a 2 s . com AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setPositiveButton("?", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //closeWebApplication(); } }); builder.setMessage(R.string.downloads_path_check); builder.show(); } return true; } if (url.startsWith("tel:")) { // phone call if (!PhoneState.hasPhoneCallAbility(mContext)) { Log.d(TAG, ">> This device has not phone call ability !!!"); return true; } mContext.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url))); } else if (url.startsWith("mailto:")) { url = url.replaceFirst("mailto:", ""); url = url.trim(); Intent i = new Intent(Intent.ACTION_SEND); i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[] { url }); mContext.startActivity(i); } else if (url.startsWith("geo:")) { Intent searchAddress = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); mContext.startActivity(searchAddress); } else { // URL ?? ? ??? . dismissProgressDialog(); loadWebUrl(url); showProgressDialog(); } return true; }
From source file:org.mozilla.gecko.GeckoAppShell.java
public static boolean loadLibsSetup(String apkName) { // The package data lib directory isn't placed in ld.so's // search path, so we have to manually load libraries that // libxul will depend on. Not ideal. GeckoApp geckoApp = GeckoApp.mAppContext; GeckoProfile profile = geckoApp.getProfile(); profile.moveProfilesToAppInstallLocation(); try {/* www.j a v a 2 s . c o m*/ String[] dirs = GeckoApp.mAppContext.getPluginDirectories(); StringBuffer pluginSearchPath = new StringBuffer(); for (int i = 0; i < dirs.length; i++) { Log.i(LOGTAG, "dir: " + dirs[i]); pluginSearchPath.append(dirs[i]); pluginSearchPath.append(":"); } GeckoAppShell.putenv("MOZ_PLUGIN_PATH=" + pluginSearchPath); } catch (Exception ex) { Log.i(LOGTAG, "exception getting plugin dirs", ex); } GeckoAppShell.putenv("HOME=" + profile.getFilesDir().getPath()); GeckoAppShell.putenv("GRE_HOME=" + GeckoApp.sGREDir.getPath()); Intent i = geckoApp.getIntent(); String env = i.getStringExtra("env0"); Log.i(LOGTAG, "env0: " + env); for (int c = 1; env != null; c++) { GeckoAppShell.putenv(env); env = i.getStringExtra("env" + c); Log.i(LOGTAG, "env" + c + ": " + env); } File f = geckoApp.getDir("tmp", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); if (!f.exists()) f.mkdirs(); GeckoAppShell.putenv("TMPDIR=" + f.getPath()); f = Environment.getDownloadCacheDirectory(); GeckoAppShell.putenv("EXTERNAL_STORAGE=" + f.getPath()); File cacheFile = getCacheDir(); String linkerCache = System.getenv("MOZ_LINKER_CACHE"); if (System.getenv("MOZ_LINKER_CACHE") == null) { GeckoAppShell.putenv("MOZ_LINKER_CACHE=" + cacheFile.getPath()); } File pluginDataDir = GeckoApp.mAppContext.getDir("plugins", 0); GeckoAppShell.putenv("ANDROID_PLUGIN_DATADIR=" + pluginDataDir.getPath()); // gingerbread introduces File.getUsableSpace(). We should use that. long freeSpace = getFreeSpace(); try { File downloadDir = null; File updatesDir = null; if (Build.VERSION.SDK_INT >= 8) { downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); updatesDir = GeckoApp.mAppContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); } else { updatesDir = downloadDir = new File(Environment.getExternalStorageDirectory().getPath(), "download"); } GeckoAppShell.putenv("DOWNLOADS_DIRECTORY=" + downloadDir.getPath()); GeckoAppShell.putenv("UPDATES_DIRECTORY=" + updatesDir.getPath()); } catch (Exception e) { Log.i(LOGTAG, "No download directory has been found: " + e); } putLocaleEnv(); boolean extractLibs = GeckoApp.ACTION_DEBUG.equals(i.getAction()); if (!extractLibs) { // remove any previously extracted libs File[] files = cacheFile.listFiles(); if (files != null) { Iterator<File> cacheFiles = Arrays.asList(files).iterator(); while (cacheFiles.hasNext()) { File libFile = cacheFiles.next(); if (libFile.getName().endsWith(".so")) libFile.delete(); } } } return extractLibs; }