Kotlin camera intent example

Kotlin camera intent example today learn this topic. Camera intent kotlin source code. From this Article. Follow the manifest permission using permission camera open. for more information visit google developer page

 

If an the kotlin camera intent example essential function of your application is taking pictures, then restrict its visibility on Google Play to devices that have a camera. To advertise that your application depends on having a camera, put a <uses-feature> tag in your manifest file:

 

<manifest ... >

    <uses-feature android:name="android.hardware.camera"

                  android:required="true" />

    ...

</manifest>

 

The Android way of delegating actions to other applications is to invoke an Intent that describes what you want done. This process involves three pieces: The Intent itself, a call to start the external Activity, and some code to handle the image data when focus returns to your activity.

 

 

Follow the source code  Kotlin camera intent



1.MainActivity.kt:


import android.Manifest.permission.CAMERA

import android.Manifest.permission.READ_EXTERNAL_STORAGE

import android.app.Activity

import android.content.Intent

import android.content.pm.PackageManager

import android.graphics.Bitmap

import android.graphics.BitmapFactory

import android.net.Uri

import android.os.Bundle

import android.os.Environment

import android.provider.MediaStore

import android.support.v4.app.ActivityCompat

import android.support.v4.content.ContextCompat

import android.support.v4.content.FileProvider

import android.support.v7.app.AppCompatActivity

import android.view.View

import android.widget.Button

import android.widget.ImageView

import android.widget.Toast

import java.io.File

import java.io.IOException

import java.text.SimpleDateFormat

import java.util.*



class MainActivity : AppCompatActivity() {

    lateinit var imageView: ImageView

    lateinit var captureButton: Button


    val REQUEST_IMAGE_CAPTURE = 1

    private val PERMISSION_REQUEST_CODE: Int = 101


    private var mCurrentPhotoPath: String? = null;

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)


        imageView = findViewById(R.id.image_view)

        captureButton = findViewById(R.id.btn_capture)

        captureButton.setOnClickListener(View.OnClickListener {

            if (checkPersmission()) takePicture() else requestPermission()

        })



    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {

        when (requestCode) {

            PERMISSION_REQUEST_CODE -> {


                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)

                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {


                    takePicture()


                } else {

                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()

                }

                return

            }


            else -> {


            }

        }

    }


    private fun takePicture() {


        val intent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

        val file: File = createFile()


        val uri: Uri = FileProvider.getUriForFile(

                this,

                "com.example.android.fileprovider",

                file

        )

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)

        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {


            //To get the File for further usage

            val auxFile = File(mCurrentPhotoPath)



            var bitmap: Bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath)

            imageView.setImageBitmap(bitmap)


        }

    }


    private fun checkPersmission(): Boolean {

        return (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) ==

                PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,

                android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)

    }


    private fun requestPermission() {

        ActivityCompat.requestPermissions(this, arrayOf(READ_EXTERNAL_STORAGE, CAMERA), PERMISSION_REQUEST_CODE)

    }


    @Throws(IOException::class)

    private fun createFile(): File {

        // Create an image file name

        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())

        val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)

        return File.createTempFile(

                "JPEG_${timeStamp}_", /* prefix */

                ".jpg", /* suffix */

                storageDir /* directory */

        ).apply {

            // Save a file: path for use with ACTION_VIEW intents

            mCurrentPhotoPath = absolutePath

        }

    }

}



2.activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">


    <LinearLayout

        android:layout_centerInParent="true"

        android:orientation="vertical"

        android:layout_width="match_parent"

        android:layout_height="wrap_content">


        <ImageView

            android:id="@+id/image_view"

            android:background="@drawable/img_placehlder"

            android:layout_gravity="center_horizontal"

            android:layout_width="200dp"

            android:layout_height="300dp" />

        <Button

            android:id="@+id/btn_capture"

            android:text="Capture"

            android:layout_marginTop="12dp"

            android:layout_gravity="center_horizontal"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content" />


    </LinearLayout>


</RelativeLayout>



3.create file follow code res---xml---file_paths.xml:


<?xml version="1.0" encoding="utf-8"?>

<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-files-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />

</paths>



4.AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.kotlin.cameraintent">


    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>


        <provider

            android:name="android.support.v4.content.FileProvider"

            android:authorities="com.example.android.fileprovider"

            android:exported="false"

            android:grantUriPermissions="true">

            <meta-data

                android:name="android.support.FILE_PROVIDER_PATHS"

                android:resource="@xml/file_path">


            </meta-data>

        </provider>

    </application>


</manifest>




 

 


Comments

Popular posts from this blog

android kotlin current date example

android kotlin listview example