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);
    }
}

Capture image from camera and set to imageview with runtime permission

private int hasCameraPermission;
private List<String> permissions = new ArrayList<>();
private final static int PERMISSION_CODE = 100;
private Bitmap mBitmap=null;
private String mImagePath = null;

Step-1

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkCameraPermissions()) {
        openCamera();
    } else {
        requestCameraPermissions();
    }
} else {
    openCamera();
}

private boolean checkCameraPermissions() {
    hasCameraPermission= ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (hasCameraPermission== PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    return false;
}

@RequiresApi(api = Build.VERSION_CODES.M)
private void requestCameraPermissions() {
    if (hasCameraPermission!= PackageManager.PERMISSION_GRANTED) {
        permissions.add(android.Manifest.permission.CAMERA);
    }
    if (!permissions.isEmpty()) {
        requestPermissions(permissions.toArray(new String[permissions.size()]), PERMISSION_CODE);
    }
}

Step-2
private void openCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAMERA_REQUEST);
}


Step-3

@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
   
    if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) {
        if (data != null && data.getExtras() != null) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");

            // CALL THIS METHOD TO GET THE URI FROM THE BITMAP            Uri mUri = getImageUri(getApplicationContext(), photo);

            // CALL THIS METHOD TO GET THE ACTUAL PATH            File mFile = new File(getRealPathFromURI(mUri));

            // Save a file: path for use with ACTION_VIEW intents            mImagePath = mFile.getAbsolutePath();

            Bitmap bm = BitmapFactory.decodeFile(mImagePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object            byte[] byteArrayImage = baos.toByteArray();
            String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
            byte[] decodeResponse = Base64.decode(encodedImage, Base64.DEFAULT | Base64.NO_WRAP);
            mBitmap= BitmapFactory.decodeByteArray(decodeResponse, 0, decodeResponse.length); // load
            mBitmap= Bitmap.createScaledBitmap(mBitmap, 400, 400, false);

            imageView.setImageBitmap(mBitmap);
        
        }
    } 
}

public Uri getImageUri(Context mContext, Bitmap image) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(mContext.getContentResolver(), image, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(index);
}