Mindinventory / Lassi-Android

All in 1 picker library for android.
https://www.mindinventory.com/android-application-development.php
MIT License
201 stars 50 forks source link

how to implement in java #93

Closed Manli123 closed 1 year ago

sanjay-mi commented 1 year ago

Hello @Manli123

Thank you for using Lassi Library.

Here is the Lassi sample's MainActivity in Java.

package com.lassi.app;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.webkit.MimeTypeMap;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import com.lassi.app.adapter.SelectedMediaAdapter;
import com.lassi.app.databinding.ActivityMainBinding;
import com.lassi.common.utils.KeyUtils;
import com.lassi.data.media.MiMedia;
import com.lassi.domain.media.LassiOption;
import com.lassi.domain.media.MediaType;
import com.lassi.presentation.builder.Lassi;
import com.lassi.presentation.common.decoration.GridSpacingItemDecoration;
import com.lassi.presentation.cropper.CropImageView;
import java.io.File;
import java.util.List;
import java.util.Locale;
import kotlin.Unit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ActivityMainBinding binding;
    private SelectedMediaAdapter selectedMediaAdapter = new SelectedMediaAdapter(miMedia -> {
        onItemClicked(miMedia);
        return Unit.INSTANCE;
    });
    private ActivityResultLauncher<Intent> receiveData =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                    result -> {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            List<MiMedia> selectedMedia =
                                    (List<MiMedia>) result.getData().getSerializableExtra(KeyUtils.SELECTED_MEDIA);

                            if (!selectedMedia.isEmpty()) {
                                binding.ivEmpty.setVisibility(View.GONE);
                                selectedMediaAdapter.setList(selectedMedia);
                            }
                        }
                    });
    private ActivityResultLauncher<Intent> mPermissionSettingResult =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                    result -> {
                        requestPermissionForDocument();
                    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.btnImagePicker.setOnClickListener(this);
        binding.btnVideoPicker.setOnClickListener(this);
        binding.btnAudioPicker.setOnClickListener(this);
        binding.btnDocPicker.setOnClickListener(this);
        binding.btnImageCapture.setOnClickListener(this);
        binding.btnVideoCapture.setOnClickListener(this);
        binding.btnDocumentSystemIntent.setOnClickListener(this);
        binding.rvSelectedMedia.setAdapter(selectedMediaAdapter);
        binding.rvSelectedMedia.addItemDecoration(new GridSpacingItemDecoration(2, 10, true));
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnImagePicker) {

            Intent intent = new Lassi(this)
                    .with(LassiOption.CAMERA_AND_GALLERY)
                    .setMaxCount(1)
                    .setGridSize(2)
                    .setPlaceHolder(R.drawable.ic_image_placeholder)
                    .setErrorDrawable(R.drawable.ic_image_placeholder)
                    .setSelectionDrawable(R.drawable.ic_checked_media)
                    .setStatusBarColor(R.color.colorPrimaryDark)
                    .setToolbarColor(R.color.colorPrimary)
                    .setToolbarResourceColor(android.R.color.white)
                    .setAlertDialogNegativeButtonColor(R.color.cherry_red)
                    .setAlertDialogPositiveButtonColor(R.color.emerald_green)
                    .setProgressBarColor(R.color.colorAccent)
                    .setGalleryBackgroundColor(R.color.colorGrey)
                    .setCropType(CropImageView.CropShape.OVAL)
                    .setCropAspectRatio(1, 1)
                    .setCompressionRation(10)
                    .setMinFileSize(0)
                    .setMaxFileSize(10000)
                    .enableActualCircleCrop()
                    .setSupportedFileTypes("jpg", "jpeg", "png", "webp", "gif")
                    .enableFlip()
                    .enableRotate()
                    .build();

            receiveData.launch(intent);

        } else if (v.getId() == R.id.btnVideoPicker) {

            Intent intent = new Lassi(this)
                    .with(LassiOption.CAMERA_AND_GALLERY)
                    .setMaxCount(4)
                    .setGridSize(3)
                    .setMinTime(5)
                    .setMaxTime(30)
                    .setMinFileSize(0)
                    .setMaxFileSize(20000)
                    .setMediaType(MediaType.VIDEO)
                    .setStatusBarColor(R.color.colorPrimaryDark)
                    .setToolbarColor(R.color.colorPrimary)
                    .setToolbarResourceColor(android.R.color.white)
                    .setAlertDialogNegativeButtonColor(R.color.cherry_red)
                    .setAlertDialogPositiveButtonColor(R.color.emerald_green)
                    .setProgressBarColor(R.color.colorAccent)
                    .setGalleryBackgroundColor(R.color.colorGrey)
                    .setPlaceHolder(R.drawable.ic_video_placeholder)
                    .setErrorDrawable(R.drawable.ic_video_placeholder)
                    .setSelectionDrawable(R.drawable.ic_checked_media)
                    .setSupportedFileTypes("mp4", "mkv", "webm", "avi", "flv", "3gp")
                    .build();

            receiveData.launch(intent);

        } else if (v.getId() == R.id.btnAudioPicker) {

            Intent intent = new Lassi(this)
                    .setMediaType(MediaType.AUDIO)
                    .setMaxCount(4)
                    .setGridSize(2)
                    .setPlaceHolder(R.drawable.ic_audio_placeholder)
                    .setErrorDrawable(R.drawable.ic_audio_placeholder)
                    .setSelectionDrawable(R.drawable.ic_checked_media)
                    .setStatusBarColor(R.color.colorPrimaryDark)
                    .setToolbarColor(R.color.colorPrimary)
                    .setToolbarResourceColor(android.R.color.white)
                    .setProgressBarColor(R.color.colorAccent)
                    .setGalleryBackgroundColor(R.color.colorGrey)
                    .build();

            receiveData.launch(intent);

        } else if (v.getId() == R.id.btnDocPicker) {

            requestPermissionForDocument();

        } else if (v.getId() == R.id.btnDocumentSystemIntent) {
            Intent intent = new Lassi(this)
                    .setMediaType(MediaType.FILE_TYPE_WITH_SYSTEM_VIEW)
                    .setSupportedFileTypes(
                            "jpg",
                            "jpeg",
                            "png",
                            "webp",
                            "gif",
                            "mp4",
                            "mkv",
                            "webm",
                            "avi",
                            "flv",
                            "3gp",
                            "pdf",
                            "odt",
                            "doc",
                            "docs",
                            "docx",
                            "txt",
                            "ppt",
                            "pptx",
                            "rtf",
                            "xlsx",
                            "xls"
                    )
                    .setMaxCount(3)
                    .setCustomLimitExceedingErrorMessage(R.string.error_exceed_msg)
                    .build();

            receiveData.launch(intent);

        } else if (v.getId() == R.id.btnImageCapture) {
            Intent intent = new Lassi(this)
                    .with(LassiOption.CAMERA)
                    .setMaxCount(1)
                    .setGridSize(2)
                    .setPlaceHolder(R.drawable.ic_image_placeholder)
                    .setErrorDrawable(R.drawable.ic_image_placeholder)
                    .setSelectionDrawable(R.drawable.ic_checked_media)
                    .setStatusBarColor(R.color.colorPrimaryDark)
                    .setToolbarColor(R.color.colorPrimary)
                    .setToolbarResourceColor(android.R.color.white)
                    .setProgressBarColor(R.color.colorAccent)
                    .setGalleryBackgroundColor(R.color.colorGrey)
                    .setAlertDialogNegativeButtonColor(R.color.cherry_red)
                    .setAlertDialogPositiveButtonColor(R.color.emerald_green)
                    .setMediaType(MediaType.IMAGE)
                    .setCropType(CropImageView.CropShape.OVAL)
                    .setCropAspectRatio(1, 1)
                    .setCompressionRation(0)
                    .setMinFileSize(0)
                    .setMaxFileSize(1000000)
                    .enableActualCircleCrop()
                    .setSupportedFileTypes("jpg", "jpeg", "png", "webp", "gif")
                    .enableFlip()
                    .enableRotate()
                    .build();

            receiveData.launch(intent);

        } else if (v.getId() == R.id.btnVideoCapture) {
            Intent intent = new Lassi(this)
                    .with(LassiOption.CAMERA)
                    .setMaxCount(1)
                    .setGridSize(3)
                    .setMinTime(5)
                    .setMaxTime(30)
                    .setMinFileSize(0)
                    .setMaxFileSize(2000)
                    .setPlaceHolder(R.drawable.ic_image_placeholder)
                    .setErrorDrawable(R.drawable.ic_image_placeholder)
                    .setSelectionDrawable(R.drawable.ic_checked_media)
                    .setStatusBarColor(R.color.colorPrimaryDark)
                    .setToolbarColor(R.color.colorPrimary)
                    .setMediaType(MediaType.VIDEO)
                    .setToolbarResourceColor(android.R.color.white)
                    .setAlertDialogNegativeButtonColor(R.color.cherry_red)
                    .setAlertDialogPositiveButtonColor(R.color.emerald_green)
                    .setProgressBarColor(R.color.colorAccent)
                    .setGalleryBackgroundColor(R.color.colorGrey)
                    .setCropType(CropImageView.CropShape.OVAL)
                    .setCropAspectRatio(1, 1)
                    .setCompressionRation(0)
                    .setMinFileSize(0)
                    .setMaxFileSize(10000)
                    .enableActualCircleCrop()
                    .setSupportedFileTypes("jpg", "jpeg", "png", "webp", "gif")
                    .enableFlip()
                    .enableRotate()
                    .build();
            receiveData.launch(intent);
        }
    }

    private void launchDocPicker() {
        Intent intent = new Lassi(this)
                .setMediaType(MediaType.DOC)
                .setMaxCount(4)
                .setGridSize(2)
                .setPlaceHolder(R.drawable.ic_document_placeholder)
                .setErrorDrawable(R.drawable.ic_document_placeholder)
                .setSelectionDrawable(R.drawable.ic_checked_media)
                .setStatusBarColor(R.color.colorPrimaryDark)
                .setToolbarColor(R.color.colorPrimary)
                .setToolbarResourceColor(android.R.color.white)
                .setAlertDialogNegativeButtonColor(R.color.cherry_red)
                .setAlertDialogPositiveButtonColor(R.color.emerald_green)
                .setGalleryBackgroundColor(R.color.colorGrey)
                .setSupportedFileTypes(
                        "pdf",
                        "odt",
                        "doc",
                        "docs",
                        "docx",
                        "txt",
                        "ppt",
                        "pptx",
                        "rtf",
                        "xlsx",
                        "xls"
                )
                .setProgressBarColor(R.color.colorAccent)
                .build();
        receiveData.launch(intent);
    }

    private String getMimeType(Uri uri) {
        String mimeType;
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            mimeType = getContentResolver().getType(uri);
        } else {
            String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
            mimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(fileExtension.toLowerCase(Locale.getDefault()));
        }
        return mimeType;
    }

    private void onItemClicked(MiMedia miMedia) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (miMedia.getDoesUri()) {
            Uri uri = Uri.parse(miMedia.getPath());
            intent.setDataAndType(uri, getMimeType(uri));
        } else {
            File file = new File(miMedia.getPath());
            Uri fileUri = FileProvider.getUriForFile(
                    this,
                    getApplicationContext().getPackageName() + ".fileprovider", file
            );
            intent.setDataAndType(fileUri, getMimeType(fileUri));
        }
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(intent, "Open file"));
    }

    /**
     * If Android device SDK is >= 30 and wants to access document (only for choose the non media file)
     * then ask for "android.permission.MANAGE_EXTERNAL_STORAGE" permission
     */
    private void requestPermissionForDocument() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                launchDocPicker();
            } else {
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
                    mPermissionSettingResult.launch(intent);
                } catch (Exception e) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    mPermissionSettingResult.launch(intent);
                }
            }
        } else {
            launchDocPicker();
        }
    }
}

Thank you