Wednesday, 6 June 2018

Complete download file/image from server in android

1. Complete download file/image from server in android.
2. If file was downloaded in-complete then it will be deleted from storage and if user again try to download then it will download complete file.

Step-1

 Create Utils class and put below methods inside-

  public File createFileDirectory(Context context) {
        if (Utils.isSdCardAvailable() && Utils.isExternalStorageWritable()) {
            directory = new File(Utils.getDirectory());
        } else {
            ContextWrapper cw = new ContextWrapper(context);
            directory = cw.getDir(cw.getString(R.string.folder_name), Context.MODE_PRIVATE);
        }
        return directory;
    }

    public static String getDirectory() {
        String dirPath = null;
        try {
            dirPath = Environment.getExternalStorageDirectory() + subRootFolder;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dirPath;
    }

    /* Checks if external storage is available for read and write */
    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available for read and write */
    public static boolean isSdCardAvailable() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

Step -2

 MyActivity implements DownloadingAsync.IDownloadAttachment-

    File directory = null;
    String savingPath = null;


    boolean isFileAlreadyDownloaded(String mFile) {
        if (mFile != null) {
            Utils utils = new Utils();
            directory = utils.createFileDirectory(this);
            savingPath = directory + File.separator + mFile;
            File file = new File(savingPath);
            if (file.exists()) {
                return true;
            }
        }
        return false;
    }


    String fileUrl = UrlFactory.IMG_BASEURL +mFilteredList.get(position).getDownload_path();
    String file_name = mFilteredList.get(position).getFile_name();

     if (isFileAlreadyDownloaded(file_name)) {
                        Toast.makeText(getApplicationContext(), MyActivity.this.getString(R.string.file_already_downloaded), Toast.LENGTH_LONG).show();
                    } else {
                        if (Build.VERSION.SDK_INT >= 23) {
                            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    == PackageManager.PERMISSION_GRANTED) {
                                new DownloadingAsync(MyActivity.this, file_name, fileUrl, directory).execute();
                            } else {
                                ActivityCompat.requestPermissions(MyActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                            }
                        } else {
                            new DownloadingAsync(MyActivity.this, file_name, fileUrl, directory).execute();
                        }
      }


    @Override
    public void isAttachmentDownloaded(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        myDealsListAdapter.notifyDataSetChanged();
    }

Step-3

public class DownloadingAsync extends AsyncTask<Void, Void, Void> {
    private static final String TAG = "Download Task";
    private Context context;
    private String file_name;
    private String downloadUrl;
    private File outputFile = null;
    private long total = 0;
    private int contentLength = 0;
    private File mFileDirectory;
    private IDownloadAttachment iDownloadAttachment;
    private String deliverMessage = null;
    private ProgressDialog dialog;

    public DownloadingAsync(Context context, String file_name, String downloadUrl, File directory) {
        this.context = context;
        this.file_name = file_name;
        this.downloadUrl = downloadUrl;
        this.mFileDirectory = directory;
        iDownloadAttachment = (IDownloadAttachment) context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(context);
        dialog.setMessage("Downloading started, please wait.");
        dialog.show();
    }

    @Override
    protected void onPostExecute(Void result) {

        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        if (outputFile != null) {
            iDownloadAttachment.isAttachmentDownloaded(deliverMessage);
      /*    MimeTypeMap map = MimeTypeMap.getSingleton();
            String ext = MimeTypeMap.getFileExtensionFromUrl(file_name);
            String type = map.getMimeTypeFromExtension(ext);

            if (type == null)
              //  type = ";

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data = Uri.fromFile(outputFile);

            intent.setDataAndType(data, type);

            context.startActivity(intent); */
        }
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            String savingPath = null;
            URL url = new URL(downloadUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            //connect
            urlConnection.connect();
            switch (urlConnection.getResponseCode()) {
                case HttpURLConnection.HTTP_OK: {
                    contentLength = urlConnection.getContentLength();

                    //If File is not present create directory
                    if (!mFileDirectory.exists()) {
                        mFileDirectory.mkdir();
                    }
                   /* File parent = directory.getParentFile();
                    if (parent != null)
                        parent.mkdirs();*/

                    savingPath = mFileDirectory + File.separator + file_name;
                    outputFile = new File(mFileDirectory, file_name);

                    /**
                     * CHECK INCOMPLETE DOWNLOADED FILE
                     * IF TRUE THE DELETE THE INCOMPLETE FILE AND START DOWNLOAD        SAME FILE AGAIN
                     */
                    //**********************************************
                    File file = new File(savingPath);
                    if (file.exists()) {
                        if (file.length() != contentLength) {
                            if (outputFile.exists()) {
                                outputFile.delete();
                                     System.out.println(context.getString(R.string.incomplete_download_file_deleted));
                            }
                        } else {
                            contentLength = 0;
                            deliverMessage = context.getString(R.string.file_already_downloaded);
                            return null;
                        }
                    }
                    //**********************************************
                    try {
                        outputFile.createNewFile();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    try {
                        InputStream inputStream = urlConnection.getInputStream();
                        FileOutputStream outputStream = new FileOutputStream(outputFile);
                        int bytesRead = -1;
                        byte[] buffer = new byte[4096];
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            total += bytesRead;
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        outputStream.flush();
                        outputStream.close();
                        inputStream.close();

                    } catch (OutOfMemoryError e) {
                        // TODO: handle exception
                    }

                    if (total == contentLength) {
                        deliverMessage = context.getString(R.string.file_download_completed);
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.d(TAG, "Error : IOException " + e);
            e.printStackTrace();
        } catch (Exception e) {
            Log.d(TAG, "Error: Exception " + e);
        }

        return null;
    }

    public interface IDownloadAttachment {
        void isAttachmentDownloaded(String message);
    }
}

No comments:

Post a Comment