3

Hi I want to download an image when long pressing an image. I can get the image to download, but I don't know where it is downloaded to. It is not in the Downloads directory.However, if I open it from the notification, I can see the image.

Below is my code snippet :

 @Override
    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo){
        super.onCreateContextMenu(contextMenu, view, contextMenuInfo);

        final WebView.HitTestResult webViewHitTestResult = webView.getHitTestResult();

        if (webViewHitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                webViewHitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

            contextMenu.setHeaderTitle("Download Image");

            contextMenu.add(0, 1, 0, "Save - Download Image")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {

                            String DownloadImageURL = webViewHitTestResult.getExtra();

                            if(URLUtil.isValidUrl(DownloadImageURL)){



                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);


                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
                                request.allowScanningByMediaScanner();
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                downloadManager.enqueue(request);

                                Toast.makeText(MainActivity.this,"Image Downloaded Successfully.",Toast.LENGTH_LONG).show();
                            }
                            else {
                                Toast.makeText(MainActivity.this,"Sorry.. Something Went Wrong.",Toast.LENGTH_LONG).show();
                            }
                            return false;
                        }
                    });
        }
    }
rgv
  • 1,186
  • 1
  • 17
  • 39
Mr Niceguy
  • 61
  • 3
  • Can you please take a look at this question : https://stackoverflow.com/q/9194361/4127441 – rgv Dec 27 '17 at 23:23
  • I looked at it, but that did not helped me a lot :/ – Mr Niceguy Dec 27 '17 at 23:28
  • 1
    `Toast.makeText(MainActivity.this,"Image Downloaded Successfully.",Toast.LENGTH_LONG).show();`. You cannot put that toast there. You just asked the download manager to download a file. Maybe the download has not even started yet. And the download can fail for a lot of reasons. – greenapps Dec 28 '17 at 09:26
  • 1
    `Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_D`OWNLOADS);`. That statement does nothing. You should tell the download manager this path of course. – greenapps Dec 28 '17 at 09:29

1 Answers1

0

This is sort of how your class should look like.

public class YourActivity extends Activity {

     private WebView webView; // make sure to init your webview
     private DownloadManager downloadManager;



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // your any other onCreate() code...
        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        registerReceiver(onDownloadComplete,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    @Override
     public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
        super.onCreateContextMenu(contextMenu, view, contextMenuInfo);

        final WebView.HitTestResult webViewHitTestResult = webView.getHitTestResult();
         if (isHitResultAnImage(webViewHitTestResult)) {
            contextMenu.setHeaderTitle("Download Image");
            contextMenu.add(0, 1, 0, "Save - Download Image")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {
                            return handleMenuItemClick(menuItem, webViewHitTestResult.getExtra());
                        }
                    });
         }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(onDownloadComplete);
    }


    private boolean isHitResultAnImage(WebView.HitTestResult hitTestResult) {
         return hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                 hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE;
    }

    private boolean handleMenuItemClick(MenuItem menuItem, String imageDownloadUrl) {
        if(URLUtil.isValidUrl(imageDownloadUrl)){
            downloadImage(imageDownloadUrl);
            Toast.makeText(this,"Image Downloaded Successfully.",Toast.LENGTH_LONG).show();
            return false;
        }
        Toast.makeText(this,"Sorry.. Something Went Wrong.",Toast.LENGTH_LONG).show();
        return false;
    }


    private void downloadImage(String imageUrl) {
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imageUrl));
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        downloadManager.enqueue(request);
    }


    public String getFilePathFromUri(Uri uri) {
        String filePath = null;
        if ("content".equals(uri.getScheme())) {
            String[] filePathColumn = { MediaStore.MediaColumns.DATA };
            ContentResolver contentResolver = getContentResolver();

            Cursor cursor = contentResolver.query(uri, filePathColumn, null,
                    null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
        } else if ("file".equals(uri.getScheme())) {
            filePath = new File(uri.getPath()).getAbsolutePath();
        }
        return filePath;
    }

     private void saveAsJpeg(Bitmap bitmapImage) {
        ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
        // path to /data/data/yourapp/app_data/imageDir
        File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        File mypath = new File(directory,"imageName.jpg");
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(mypath);
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            Cursor cursor = downloadManager.query(query);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(columnIndex)) {
                    String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    File file = new File(getFilePathFromUri(Uri.parse(uriString)));
                    try {
                    Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
                    saveAsJpeg(bitmap);
                } catch (FileNotFoundException e) {
                    // cant save
                }
                } else {
                    // downloadFailed, show toast or something..
                }
            }
        }
    };


}

This answer is based on code I found from the following resources : How to use Android DownloadManager?

https://stackoverflow.com/a/5879563/4127441

https://github.com/commonsguy/cw-android/blob/master/Internet/Download/src/com/commonsware/android/download/DownloadDemo.java

https://stackoverflow.com/a/19339672/4127441

rgv
  • 1,186
  • 1
  • 17
  • 39
  • 1
    I tried your Code sample. It works just like before. How can I write the file in .jpg in to the Directory? Because right now, it is just downloading it. – Mr Niceguy Dec 28 '17 at 12:08
  • I updated and added code to convert file to bitmap and method that takes a bitmap and saves it as a jpeg file. I found how to save a file as jpeg within 10 mins of googling. Try to break down your problem into smaller units of problems and solve them individually, this systematic approach will take you places. One more tip, Try to write code that is more readable, it will help you and anyone else reading your code. – rgv Dec 28 '17 at 20:28
  • It worked just like before. And also I could not find the Directory you created :/ Is it possible to use the Standard Downloads Directory? Or Pictures Directory? – Mr Niceguy Dec 29 '17 at 01:17
  • I created a chat room and upvoted your questions, you should have enough points able to enter chats, I will send you an invite to the chat and we can discuss this much easily there. – rgv Dec 29 '17 at 17:01
  • Very nice, thank you very much :) Where I can see your invite after you send it? – Mr Niceguy Dec 29 '17 at 18:47