Giter Site home page Giter Site logo

zaid-mirza / attachmentmanager Goto Github PK

View Code? Open in Web Editor NEW
12.0 1.0 3.0 381 KB

Attachment Manager library to pick files/image from Android device

License: Apache License 2.0

Kotlin 93.45% Java 6.55%
androidx java gallery camera language kotlin image libra attachment filesystem

attachmentmanager's Introduction

AttachmentManager

API Language

Developed by Zaid Mirza and contributors

You can use this lightweight library to implement the attachment feature (taking pictures using the camera, picking up files/images from gallery or file system, or google drive). The library helps you to simplify all the processes related to picking files without worrying about system permissions

Language Support

  • English
  • Arabic

Warning!

  1. This library is build using AndroidX.So, I recommend you to migrate your project to AndroidX otherwise it may cause problem using both androidx and support libs togather.

  2. You might face error Invoke-customs are only supported starting with android 0 --min-api 26 .To solve this add below lines in app level build.gradle file.

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

Prerequisite

  1. Add permissions and provider in AndroidManifest.xml
    <uses-permission android:name="android.permission.READ_STORAGE_PERMISSION" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
    <uses-permission android:name="android.permission.CAMERA" />
 <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.attachmentmanager"
            android:exported="false"
            android:grantUriPermissions="true"
            tools:replace="android:authorities">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider"
                tools:replace="android:resource" />
  </provider>
  1. Create file_provider.xml in res/xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="myApp"
        path="Download/" />
    <external-files-path
        name="images"
        path="Pictures" />
</paths>
  1. If you are targeting Android 11+, you need to add following queries in AndroidManifest.xml
<queries>
        <intent>
            <action android:name="android.intent.action.OPEN_DOCUMENT" />
            <!-- If you don't know the MIME type in advance, set "mimeType" to "*/*". -->
            <data android:mimeType="*/*" />
        </intent>
        <intent>
            <action android:name="android.intent.action.PICK" />
            <!-- If you don't know the MIME type in advance, set "mimeType" to "*/*". -->
            <data android:mimeType="*/*" />
        </intent>
    </queries>
  
  1. Update project level build.gradle file.
allprojects {
   repositories {
      	jcenter()
       	maven { url "https://jitpack.io" }  //Make sure to add this in your project
   }
}
   implementation 'com.github.Zaid-Mirza:AttachmentManager:3.0.0'

Usage

  1. Initiate AttachmentManager object using builder pattern

Kotlin

private var attachmentManager: AttachmentManager? = null
var gallery = arrayOf("image/png",
            "image/jpg",
            "image/jpeg")
    var files = arrayOf("application/msword",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",  // .ppt & .pptx
            "application/pdf")

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
      attachmentManager = AttachmentManager.AttachmentBuilder(this) // must pass Context
            .fragment(null) // pass fragment reference if you are in fragment
            .setUiTitle("Choose File") // title of dialog or bottom sheet
            .allowMultiple(false) // set true if you want make multiple selection, default is false
            .asBottomSheet(true) // set true if you need to show selection as bottom sheet, default is as Dialog
            .setOptionsTextColor(android.R.color.holo_green_light) // change text color
            .setImagesColor(R.color.colorAccent) // change icon color
            .hide(HideOption.DOCUMENT) // You can hide any option do you want
            .setMaxPhotoSize(200000) // Set max  photo size in bytes
            .galleryMimeTypes(gallery) // mime types for gallery
            .filesMimeTypes(files) // mime types for files
            .build(); // Hide any of the three options
       
    }
    

Java

    private AttachmentManager attachmentManager = null;
    String[] gallery = {"image/png",
            "image/jpg",
            "image/jpeg"};
    String[] files  = { "application/msword",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .ppt & .pptx
            "application/pdf"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       attachmentManager = new AttachmentManager.AttachmentBuilder(this) // must pass Context
                .fragment(null) // pass fragment reference if you are in fragment
                .setUiTitle("Choose File") // title of dialog or bottom sheet
                .allowMultiple(false) // set true if you want make multiple selection, default is false
                .asBottomSheet(true) // set true if you need to show selection as bottom sheet, default is as Dialog
                .setOptionsTextColor(android.R.color.holo_green_light) // change text color
                .setImagesColor(R.color.colorAccent) // change icon color
                .hide(HideOption.DOCUMENT) // You can hide any option do you want
                .setMaxPhotoSize(200000) // Set max  photo size in bytes
                .galleryMimeTypes(gallery) // mime types for gallery
                .filesMimeTypes(files) // mime types for files
                .build(); // Hide any of the three options
    }
  1. Declare registerForActivityResult

Kotlin

 private var mLauncher = registerForActivityResult(StartActivityForResult()) { result ->

    val list =  attachmentManager?.manipulateAttachments(this,result.resultCode,result.data)
    Toast.makeText(this, list?.size.toString(), Toast.LENGTH_LONG).show()
}

Java

 ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {

        ArrayList<AttachmentDetail> list = attachmentManager.manipulateAttachments(this,result.getResultCode(),result.getData());

        });
  1. Call openSelection() method to show selection UI and pass ActivityResultLauncher

Kotlin

 attachmentManager?.openSelection(mLauncher)

Java

attachmentManager.openSelection(mLauncher);
  1. Override onRequestPermissionsResult (Optional)

Kotlin

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        attachmentManager?.handlePermissionResponse(requestCode, permissions, grantResults)
    }

Java

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        attachmentManager.handlePermissionResponse(requestCode,permissions,grantResults);
    }

Other Usage

  1. You can open gallery,camera or file system directly without showing selection UI to user

Kotlin

 attachmentManager?.startCamera(mLauncher)
 // OR
 attachmentManager?.openGallery(mLauncher)
 // OR
 attachmentManager?.openFilSystem(mLauncher)

Java

 attachmentManager.startCamera(mLauncher);
 // OR
 attachmentManager.openGallery(mLauncher);
 // OR
 attachmentManager.openFilSystem(mLauncher);

Note

Any kind of improvements and suggestions are welcomed. Also, if you are using this library in your project then please do provide me your app url. I will list your app here.

attachmentmanager's People

Contributors

zaid-mirza avatar zaidmirza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

attachmentmanager's Issues

Camera not showing.

can't available to start camera.

This is my codes.

class MyProfileFragment : BaseFragment<FragmentMyProfileBinding>() {
    private var attachmentManager: AttachmentManager? = null
    var gallery = arrayOf("image/png",
        "image/jpg",
        "image/jpeg")
    var files = arrayOf("application/pdf")
    private var mLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->

        val list =  attachmentManager?.manipulateAttachments(requireContext(), result.resultCode, result.data)
        Toast.makeText(requireContext(), list?.size.toString(), Toast.LENGTH_LONG).show()
    }

    override fun inflateBinding(layoutInflater: LayoutInflater): FragmentMyProfileBinding {
        return FragmentMyProfileBinding.inflate(layoutInflater)
    }

    override fun initViews() {
        initAttachmentManager()
        setupListeners()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        val newPermissions = permissions.map { it }
        attachmentManager?.handlePermissionResponse(requestCode, newPermissions.toTypedArray(), grantResults, mLauncher)
    }

    private fun initAttachmentManager() {
        attachmentManager = AttachmentManager.AttachmentBuilder(requireActivity() as AppCompatActivity) // must pass Context
            .fragment(this) // pass fragment reference if you are in fragment
            .setUiTitle("Choose File") // title of dialog or bottom sheet
            .allowMultiple(false) // set true if you want make multiple selection, default is false
            .asBottomSheet(false) // set true if you need to show selection as bottom sheet, default is as Dialog
            .setOptionsTextColor(R.color.text_color) // change text color
            .setImagesColor(R.color.text_color) // change icon color
            .setMaxPhotoSize(200000) // Set max  photo size in bytes
            .galleryMimeTypes(gallery) // mime types for gallery
            .filesMimeTypes(files) // mime types for files
            .build(); // Hide any of the three options
    }

    private fun setupListeners() = with(binding) {
        addAttachParent.setOnClickListener {
            attachmentManager?.openSelection(mLauncher)
        }
    }
}

When call above codes, app showing three options. (Gallery, Camera, Document)
Gallery and Document is working well.
But when I click Camera, not working.

Please help me.
Regards.
Dalibor

Not working with android 11

Hi,
First of all thanks foyr your great lib.
There is an issue with Android 11, the Gallery and Photo does not work.
Best regards

setUiTitle(String title) cannot resolve this methode

    attachmentManager = new AttachmentManager.AttachmentBuilder(this) // must pass Context
            .fragment(null) // pass fragment reference if you are in fragment
            .setUiTitle("Choose File") // title of dialog or bottom sheet
            .allowMultiple(false) // set true if you want make multiple selection, default is false
            .asBottomSheet(true) // set true if you need to show selection as bottom sheet, default is as Dialog
            .setOptionsTextColor(android.R.color.holo_green_light) // change text color
            .setImagesColor(R.color.colorAccent) // change icon color
            .hide(HideOption.DOCUMENT) // You can hide any option do you want
            .setMaxPhotoSize(200000) // Set max  photo size in bytes
            .galleryMimeTypes(gallery) // mime types for gallery
             // mime types for files
            .build(); //
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.