Example usage for android.app DownloadManager enqueue

List of usage examples for android.app DownloadManager enqueue

Introduction

In this page you can find the example usage for android.app DownloadManager enqueue.

Prototype

public long enqueue(Request request) 

Source Link

Document

Enqueue a new download.

Usage

From source file:org.schabi.newpipe.DownloadDialog.java

@NonNull
@Override//from  w w  w.j  ava2s  .  c o m
public Dialog onCreateDialog(Bundle savedInstanceState) {
    arguments = getArguments();
    super.onCreateDialog(savedInstanceState);
    if (ContextCompat.checkSelfPermission(this.getContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        ActivityCompat.requestPermissions(getActivity(),
                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.download_dialog_title).setItems(R.array.download_options,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Context context = getActivity();
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                    String suffix = "";
                    String title = arguments.getString(TITLE);
                    String url = "";
                    File downloadDir = NewPipeSettings.getDownloadFolder();
                    switch (which) {
                    case 0: // Video
                        suffix = arguments.getString(FILE_SUFFIX_VIDEO);
                        url = arguments.getString(VIDEO_URL);
                        downloadDir = NewPipeSettings.getVideoDownloadFolder(context);
                        break;
                    case 1:
                        suffix = arguments.getString(FILE_SUFFIX_AUDIO);
                        url = arguments.getString(AUDIO_URL);
                        downloadDir = NewPipeSettings.getAudioDownloadFolder(context);
                        break;
                    default:
                        Log.d(TAG, "lolz");
                    }
                    if (!downloadDir.exists()) {
                        //attempt to create directory
                        boolean mkdir = downloadDir.mkdirs();
                        if (!mkdir && !downloadDir.isDirectory()) {
                            String message = context.getString(R.string.err_dir_create, downloadDir.toString());
                            Log.e(TAG, message);
                            Toast.makeText(context, message, Toast.LENGTH_LONG).show();

                            return;
                        }
                        String message = context.getString(R.string.info_dir_created, downloadDir.toString());
                        Log.e(TAG, message);
                        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                    }

                    File saveFilePath = new File(downloadDir, createFileName(title) + suffix);

                    long id = 0;
                    if (App.isUsingTor()) {
                        // if using Tor, do not use DownloadManager because the proxy cannot be set
                        Downloader.downloadFile(getContext(), url, saveFilePath, title);
                    } else {
                        DownloadManager dm = (DownloadManager) context
                                .getSystemService(Context.DOWNLOAD_SERVICE);
                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                        request.setDestinationUri(Uri.fromFile(saveFilePath));
                        request.setNotificationVisibility(
                                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

                        request.setTitle(title);
                        request.setDescription("'" + url + "' => '" + saveFilePath + "'");
                        request.allowScanningByMediaScanner();

                        try {
                            id = dm.enqueue(request);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    Log.i(TAG, "Started downloading '" + url + "' => '" + saveFilePath + "' #" + id);
                }
            });
    return builder.create();
}

From source file:mgks.os.webview.MainActivity.java

@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" })
@Override//w w w.jav  a 2  s  .c o  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.tml.sharethem.receiver.FilesListingFragment.java

private long postDownloadRequestToDM(Uri uri, String fileName) {

    // Create request for android download manager
    DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(uri);

    //Setting title of request
    request.setTitle(fileName);/*from  ww  w . j a  va  2 s . c o m*/

    //Setting description of request
    request.setDescription("ShareThem");
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    //Set the local destination for the downloaded file to a path
    //within the application's external files directory
    request.setDestinationInExternalFilesDir(getActivity(), Environment.DIRECTORY_DOWNLOADS, fileName);

    //Enqueue download and save into referenceId
    return downloadManager.enqueue(request);
}

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

@android.webkit.JavascriptInterface
@org.xwalk.core.JavascriptInterface//w  w w  . ja va2 s. c o m
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:com.irccloud.android.activity.VideoPlayerActivity.java

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
            && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
        DownloadManager d = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        if (d != null) {
            DownloadManager.Request r = new DownloadManager.Request(Uri.parse(getIntent().getDataString()
                    .replace(getResources().getString(R.string.VIDEO_SCHEME), "http")));
            r.setDestinationInExternalPublicDir(Environment.DIRECTORY_MOVIES,
                    getIntent().getData().getLastPathSegment());
            r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            r.allowScanningByMediaScanner();
            d.enqueue(r);
            Answers.getInstance().logShare(new ShareEvent().putContentType("Video").putMethod("Download"));
        }//from w  w  w.  java  2  s  .c  o  m
    } else {
        Toast.makeText(this, "Unable to download: permission denied", Toast.LENGTH_SHORT).show();
    }
}

From source file:com.irccloud.android.activity.VideoPlayerActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();/*from ww w  .  j a va 2  s  .  c om*/
        overridePendingTransition(R.anim.fade_in, R.anim.slide_out_right);
        return true;
    } else if (item.getItemId() == R.id.action_download) {
        if (Build.VERSION.SDK_INT >= 16 && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
        } else {
            DownloadManager d = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            if (d != null) {
                String uri = getIntent().getDataString()
                        .replace(getResources().getString(R.string.VIDEO_SCHEME), "http");
                DownloadManager.Request r = new DownloadManager.Request(Uri.parse(uri));
                r.setDestinationInExternalPublicDir(Environment.DIRECTORY_MOVIES,
                        getIntent().getData().getLastPathSegment());
                r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                r.allowScanningByMediaScanner();
                d.enqueue(r);
                Answers.getInstance().logShare(new ShareEvent().putContentType("Video").putMethod("Download"));
            }
        }
        return true;
    } else if (item.getItemId() == R.id.action_copy) {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData.newRawUri("IRCCloud Video URL", Uri.parse(
                getIntent().getDataString().replace(getResources().getString(R.string.VIDEO_SCHEME), "http")));
        clipboard.setPrimaryClip(clip);
        Toast.makeText(VideoPlayerActivity.this, "Link copied to clipboard", Toast.LENGTH_SHORT).show();
        Answers.getInstance().logShare(new ShareEvent().putContentType("Video").putMethod("Copy to Clipboard"));
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && item.getItemId() == R.id.action_share) {
        Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse(
                getIntent().getDataString().replace(getResources().getString(R.string.VIDEO_SCHEME), "http")));
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT,
                getIntent().getDataString().replace(getResources().getString(R.string.VIDEO_SCHEME), "http"));
        intent.putExtra(ShareCompat.EXTRA_CALLING_PACKAGE, getPackageName());
        intent.putExtra(ShareCompat.EXTRA_CALLING_ACTIVITY,
                getPackageManager().getLaunchIntentForPackage(getPackageName()).getComponent());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(Intent.createChooser(intent, "Share Video"));
        Answers.getInstance().logShare(new ShareEvent().putContentType("Video"));
    }
    return super.onOptionsItemSelected(item);
}

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()//from w w  w. ja va  2 s. 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:de.baumann.browser.Browser_right.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    final WebView.HitTestResult result = mWebView.getHitTestResult();
    final String url = result.getExtra();

    if (result.getType() == WebView.HitTestResult.IMAGE_TYPE) {

        final CharSequence[] options = { getString(R.string.context_saveImage),
                getString(R.string.context_shareImage), getString(R.string.context_readLater),
                getString(R.string.context_left) };
        new AlertDialog.Builder(Browser_right.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }//  www. j  a v a 2s . c om
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.context_saveImage))) {
                            if (url != null) {
                                try {
                                    Uri source = Uri.parse(url);
                                    DownloadManager.Request request = new DownloadManager.Request(source);
                                    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,
                                            helper_main.newFileName());
                                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                    dm.enqueue(request);
                                    Snackbar.make(mWebView, getString(R.string.context_saveImage_toast) + " "
                                            + helper_main.newFileName(), Snackbar.LENGTH_SHORT).show();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                                }
                            }
                        }
                        if (options[item].equals(getString(R.string.context_shareImage))) {
                            if (url != null) {

                                shareString = helper_main.newFileName();
                                shareFile = helper_main.newFile(mWebView);

                                try {
                                    Uri source = Uri.parse(url);
                                    DownloadManager.Request request = new DownloadManager.Request(source);
                                    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,
                                            shareString);
                                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                    dm.enqueue(request);

                                    Snackbar.make(mWebView, getString(R.string.context_saveImage_toast) + " "
                                            + helper_main.newFileName(), Snackbar.LENGTH_SHORT).show();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                                }
                                registerReceiver(onComplete2,
                                        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                            }
                        }
                        if (options[item].equals(getString(R.string.context_readLater))) {
                            if (url != null) {

                                if (Uri.parse(url).getHost().length() == 0) {
                                    domain = getString(R.string.app_domain);
                                } else {
                                    domain = Uri.parse(url).getHost();
                                }

                                String domain2 = domain.substring(0, 1).toUpperCase() + domain.substring(1);

                                DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_right.this);
                                db.open();
                                if (db.isExist(mWebView.getUrl())) {
                                    Snackbar.make(editText, getString(R.string.toast_newTitle),
                                            Snackbar.LENGTH_LONG).show();
                                } else {
                                    db.insert(domain2, url, "", "", helper_main.createDate());
                                    Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG)
                                            .show();
                                }
                            }
                        }
                        if (options[item].equals(getString(R.string.context_left))) {
                            if (url != null) {
                                helper_main.switchToActivity(Browser_right.this, Browser_left.class, url,
                                        false);
                            }
                        }
                    }
                }).show();

    } else if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {

        final CharSequence[] options = { getString(R.string.menu_share_link_copy),
                getString(R.string.menu_share_link), getString(R.string.context_readLater),
                getString(R.string.context_left) };
        new AlertDialog.Builder(Browser_right.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.menu_share_link_copy))) {
                            if (url != null) {
                                ClipboardManager clipboard = (ClipboardManager) Browser_right.this
                                        .getSystemService(Context.CLIPBOARD_SERVICE);
                                clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                                Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT)
                                        .show();
                            }
                        }
                        if (options[item].equals(getString(R.string.menu_share_link))) {
                            if (url != null) {
                                Intent sendIntent = new Intent();
                                sendIntent.setAction(Intent.ACTION_SEND);
                                sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                                sendIntent.setType("text/plain");
                                Browser_right.this.startActivity(Intent.createChooser(sendIntent,
                                        getResources().getString(R.string.app_share_link)));
                            }
                        }
                        if (options[item].equals(getString(R.string.context_readLater))) {
                            if (url != null) {

                                if (Uri.parse(url).getHost().length() == 0) {
                                    domain = getString(R.string.app_domain);
                                } else {
                                    domain = Uri.parse(url).getHost();
                                }

                                String domain2 = domain.substring(0, 1).toUpperCase() + domain.substring(1);

                                DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_right.this);
                                db.open();
                                if (db.isExist(mWebView.getUrl())) {
                                    Snackbar.make(editText, getString(R.string.toast_newTitle),
                                            Snackbar.LENGTH_LONG).show();
                                } else {
                                    db.insert(domain2, url, "", "", helper_main.createDate());
                                    Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG)
                                            .show();
                                }
                            }
                        }
                        if (options[item].equals(getString(R.string.context_left))) {
                            if (url != null) {
                                helper_main.switchToActivity(Browser_right.this, Browser_left.class, url,
                                        false);
                            }
                        }
                    }
                }).show();
    }
}

From source file:com.cuddlesoft.nori.fragment.ImageFragment.java

/**
 * Use the system {@link android.app.DownloadManager} service to download the image.
 *//*from ww w.  j av a  2 s .  c o  m*/
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: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) {//from   ww  w .  j  ava  2 s  .c  o 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());
}