How To Enable Download Option In Android? Java For Enable Download Option
Enable Download Option In Android

How To Enable Download Option In Android? Java For Enable Download Option

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 100;
    private ImageView imageView;
    private String imageUrl = "YOUR_IMAGE_URL_HERE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize imageView
        imageView = findViewById(R.id.imageView);

        // Load image using Glide library
        Glide.with(this)
                .load(imageUrl)
                .into(imageView);

        // Request storage permission if not granted
        requestStoragePermission();
    }

    // Method to request storage permission
    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }

    // Callback method for permission request result
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, proceed with download
                downloadImage();
            } else {
                // Permission denied, show a toast message
                Toast.makeText(this, "Permission denied, unable to download image.", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // Method to download image
    private void downloadImage() {
        Glide.with(this)
                .load(imageUrl)
                .into(new CustomTarget<Drawable>() {
                    @RequiresApi(api = Build.VERSION_CODES.Q)
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @NonNull Transition<? super Drawable> transition) {
                        // Save image to external storage
                        saveImage(resource);
                    }

                    @Override
                    public void onLoadCleared(@NonNull Drawable placeholder) {
                        // Not implemented
                    }
                });
    }

    // Method to save image to external storage
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void saveImage(Drawable drawable) {
        File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(directory, "image_" + System.currentTimeMillis() + ".jpg");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            drawableToBitmap(drawable).compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            // Image saved, show a toast message
            Toast.makeText(this, "Image saved successfully.", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            // Error occurred while saving image, show a toast message
            Toast.makeText(this, "Failed to save image.", Toast.LENGTH_SHORT).show();
        }
    }

    // Method to convert drawable to bitmap
    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }
}
        
Nadia Urooj

Frontend Developer | Web Designer | Helping Small Businesses Modernize Outdated Websites with User-Centered, Responsive Designs | ReactJS, UI/UX, Web Applications

10 个月

Enabling download option in Android can enhance user experience. Java is an ideal language for this task. Exciting to see what you're working on!

回复

要查看或添加评论,请登录

Majharul Islam Tayef的更多文章