RuntimePermissions sample: Creating kotlin version.

Bug: 64766103
Test: Manual
Change-Id: Ia4d67d46add5daa95fd01d4623ce967f07f48b16
diff --git a/system/RuntimePermissions/kotlinApp/.gitignore b/system/RuntimePermissions/kotlinApp/.gitignore
new file mode 100644
index 0000000..39fb081
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/.gitignore
@@ -0,0 +1,9 @@
+*.iml
+.gradle
+/local.properties
+/.idea/workspace.xml
+/.idea/libraries
+.DS_Store
+/build
+/captures
+.externalNativeBuild
diff --git a/system/RuntimePermissions/kotlinApp/app/.gitignore b/system/RuntimePermissions/kotlinApp/app/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/system/RuntimePermissions/kotlinApp/app/build.gradle b/system/RuntimePermissions/kotlinApp/app/build.gradle
new file mode 100644
index 0000000..d9fa949
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/build.gradle
@@ -0,0 +1,37 @@
+apply plugin: 'com.android.application'
+apply plugin: 'kotlin-android'
+apply plugin: 'kotlin-android-extensions'
+
+android {
+    compileSdkVersion 26
+    buildToolsVersion "26.0.1"
+    defaultConfig {
+        applicationId "com.example.android.system.runtimepermissions"
+        minSdkVersion 15
+        targetSdkVersion 26
+        versionCode 1
+        versionName "1.0"
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+}
+
+dependencies {
+    compile fileTree(dir: 'libs', include: ['*.jar'])
+    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
+        exclude group: 'com.android.support', module: 'support-annotations'
+    })
+    compile "com.android.support:support-v13:26.0.0"
+    compile "com.android.support:appcompat-v7:26.0.0"
+    compile 'com.android.support:design:26.0.0'
+    testCompile 'junit:junit:4.12'
+    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
+}
+repositories {
+    mavenCentral()
+}
diff --git a/system/RuntimePermissions/kotlinApp/app/proguard-rules.pro b/system/RuntimePermissions/kotlinApp/app/proguard-rules.pro
new file mode 100644
index 0000000..2136b0c
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/proguard-rules.pro
@@ -0,0 +1,25 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in <sdk root>/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/AndroidManifest.xml b/system/RuntimePermissions/kotlinApp/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..e84bbd5
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.example.android.system.runtimepermissions">
+
+    <!-- Note that all required permissions are declared here in the Android manifest.
+    On Android M and above, use of these permissions is only requested at run time. -->
+    <uses-permission android:name="android.permission.CAMERA" />
+
+    <!-- The following permissions are only requested if the device is on M or above.
+     On older platforms these permissions are not requested and will not be available. -->
+    <uses-permission-sdk-23 android:name="android.permission.READ_CONTACTS" />
+    <uses-permission-sdk-23 android:name="android.permission.WRITE_CONTACTS" />
+
+    <application
+        android:allowBackup="true"
+        android:icon="@mipmap/ic_launcher"
+        android:label="@string/app_name"
+        android:supportsRtl="true"
+        android:theme="@style/Theme.AppCompat.Light">
+        <activity android:name=".MainActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/MainActivity.kt b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/MainActivity.kt
new file mode 100644
index 0000000..f1dfeee
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/MainActivity.kt
@@ -0,0 +1,269 @@
+/*
+* Copyright 2017 The Android Open Source Project
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package com.example.android.system.runtimepermissions
+
+import android.Manifest
+import android.content.pm.PackageManager
+import android.os.Bundle
+import android.support.design.widget.Snackbar
+import android.support.v4.app.ActivityCompat
+import android.support.v7.app.AppCompatActivity
+import android.util.Log
+import android.view.View
+import com.example.android.system.runtimepermissions.camera.CameraPreviewFragment
+import com.example.android.system.runtimepermissions.contacts.ContactsFragment
+import com.example.android.system.runtimepermissions.extensions.batchRequestPermissions
+import com.example.android.system.runtimepermissions.extensions.containsOnly
+import com.example.android.system.runtimepermissions.extensions.isPermissionGranted
+import com.example.android.system.runtimepermissions.extensions.requestPermission
+import com.example.android.system.runtimepermissions.extensions.shouldShowPermissionRationale
+import kotlinx.android.synthetic.main.activity_main.*
+
+/**
+ * Launcher Activity that demonstrates the use of runtime permissions for Android M.
+ * It contains a summary sample description, sample log and a Fragment that calls callbacks on this
+ * Activity to illustrate parts of the runtime permissions API.
+ *
+ *
+ * This Activity requests permissions to access the camera ([android.Manifest.permission.CAMERA])
+ * when the 'Show Camera' button is clicked to display the camera preview.
+ * Contacts permissions (([android.Manifest.permission.READ_CONTACTS] and ([ ][android.Manifest.permission.WRITE_CONTACTS])) are requested when the 'Show and Add Contacts'
+ * button is
+ * clicked to display the first contact in the contacts database and to add a dummy contact
+ * directly to it. Permissions are verified and requested through compat helpers in the support v4
+ * library, in this Activity using [ActivityCompat].
+ * First, permissions are checked if they have already been granted through [ ][ActivityCompat.checkSelfPermission].
+ * If permissions have not been granted, they are requested through
+ * [ActivityCompat.requestPermissions] and the return value checked
+ * in
+ * a callback to the [android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback]
+ * interface.
+ *
+ *
+ * Before requesting permissions, [ActivityCompat.shouldShowRequestPermissionRationale]
+ * should be called to provide the user with additional context for the use of permissions if they
+ * have been denied previously.
+ *
+ *
+ * If this sample is executed on a device running a platform version below M, all permissions
+ * declared
+ * in the Android manifest file are always granted at install time and cannot be requested at run
+ * time.
+ *
+ *
+ * This sample targets the M platform and must therefore request permissions at runtime. Change the
+ * targetSdk in the file 'Application/build.gradle' to 22 to run the application in compatibility
+ * mode.
+ * Now, if a permission has been disable by the system through the application settings, disabled
+ * APIs provide compatibility data.
+ * For example the camera cannot be opened or an empty list of contacts is returned. No special
+ * action is required in this case.
+ *
+ *
+ * (This class is based on the MainActivity used in the SimpleFragment sample template.)
+ */
+class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsResultCallback {
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        setContentView(R.layout.activity_main)
+        if (savedInstanceState == null) {
+            supportFragmentManager.beginTransaction().apply {
+                replace(R.id.sampleContentFragment, RuntimePermissionsFragment())
+            }.commit()
+        }
+    }
+
+    /**
+     * Called when the 'show camera' button is clicked.
+     * Callback is defined in resource layout definition.
+     */
+    fun showCamera(view: View) {
+        Log.i(TAG, "Show camera button pressed. Checking permission.")
+        // Check if the Camera permission is already available.
+        if (!isPermissionGranted(Manifest.permission.CAMERA)) {
+            // Camera permission has not been granted.
+            requestCameraPermission()
+        } else {
+            // Camera permissions is already available, show the camera preview.
+            Log.i(TAG,
+                    "CAMERA permission has already been granted. Displaying camera preview.")
+            showCameraPreview()
+        }
+    }
+
+    /**
+     * Requests the Camera permission.
+     * If the permission has been denied previously, a SnackBar will prompt the user to grant the
+     * permission, otherwise it is requested directly.
+     */
+    private fun requestCameraPermission() {
+        Log.i(TAG, "CAMERA permission has NOT been granted. Requesting permission.")
+        if (shouldShowPermissionRationale(Manifest.permission.CAMERA)) {
+            // Provide an additional rationale to the user if the permission was not granted
+            // and the user would benefit from additional context for the use of the permission.
+            // For example if the user has previously denied the permission.
+            Log.i(TAG, "Displaying camera permission rationale to provide additional context.")
+            Snackbar.make(mainLayout, R.string.permission_camera_rationale,
+                    Snackbar.LENGTH_INDEFINITE)
+                    .setAction(R.string.ok, {
+                        requestPermission(Manifest.permission.CAMERA, REQUEST_CAMERA)
+                    })
+                    .show()
+        } else {
+
+            // Camera permission has not been granted yet. Request it directly.
+            requestPermission(Manifest.permission.CAMERA, REQUEST_CAMERA)
+        }
+    }
+
+    /**
+     * Called when the 'show camera' button is clicked.
+     * Callback is defined in resource layout definition.
+     */
+    fun showContacts(view: View) {
+        Log.i(TAG, "Show contacts button pressed. Checking permissions.")
+
+        // Verify that all required contact permissions have been granted.
+        if (!isPermissionGranted(Manifest.permission.READ_CONTACTS) ||
+                !isPermissionGranted(Manifest.permission.WRITE_CONTACTS)) {
+            // Contacts permissions have not been granted.
+            Log.i(TAG, "Contact permissions has NOT been granted. Requesting permissions.")
+            requestContactsPermissions()
+        } else {
+            // Contact permissions have been granted. Show the contacts fragment.
+            Log.i(TAG,
+                    "Contact permissions have already been granted. Displaying contact details.")
+            showContactDetails()
+        }
+    }
+
+    /**
+     * Requests the Contacts permissions.
+     * If the permission has been denied previously, a Snackbar will prompt the user to grant the
+     * permission, otherwise it is requested directly.
+     */
+    private fun requestContactsPermissions() {
+        if (shouldShowPermissionRationale(Manifest.permission.READ_CONTACTS) ||
+                shouldShowPermissionRationale(Manifest.permission.WRITE_CONTACTS)) {
+
+            // Provide an additional rationale to the user if the permission was not granted
+            // and the user would benefit from additional context for the use of the permission.
+            // For example, if the request has been denied previously.
+            Log.i(TAG, "Displaying contacts permission rationale to provide additional context.")
+
+            // Display a SnackBar with an explanation and a button to trigger the request.
+            Snackbar.make(mainLayout, R.string.permission_contacts_rationale,
+                    Snackbar.LENGTH_INDEFINITE)
+                    .setAction(R.string.ok, {
+                        batchRequestPermissions(PERMISSIONS_CONTACT, REQUEST_CONTACTS)
+                    })
+                    .show()
+        } else {
+            // Contact permissions have not been granted yet. Request them directly.
+            batchRequestPermissions(PERMISSIONS_CONTACT, REQUEST_CONTACTS)
+        }
+    }
+
+    /**
+     * Display the [CameraPreviewFragment] in the content area if the required Camera
+     * permission has been granted.
+     */
+    private fun showCameraPreview() {
+        supportFragmentManager.beginTransaction()
+                .replace(R.id.sampleContentFragment, CameraPreviewFragment.newInstance())
+                .addToBackStack("contacts")
+                .commit()
+    }
+
+    /**
+     * Display the [ContactsFragment] in the content area if the required contacts
+     * permissions have been granted.
+     */
+    private fun showContactDetails() {
+        supportFragmentManager.beginTransaction()
+                .replace(R.id.sampleContentFragment, ContactsFragment.newInstance())
+                .addToBackStack("contacts")
+                .commit()
+    }
+
+    /**
+     * Callback received when a permissions request has been completed.
+     */
+    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
+            grantResults: IntArray) {
+
+        if (requestCode == REQUEST_CAMERA) {
+            // Received permission result for camera permission.
+            Log.i(TAG, "Received response for Camera permission request.")
+
+            // Check if the permission has been granted
+            if (grantResults.containsOnly(PackageManager.PERMISSION_GRANTED)) {
+                // Camera permission has been granted, preview can be displayed
+                Log.i(TAG, "CAMERA permission has now been granted. Showing preview.")
+                Snackbar.make(mainLayout, R.string.permision_available_camera,
+                        Snackbar.LENGTH_SHORT).show()
+            } else {
+                Log.i(TAG, "CAMERA permission was NOT granted.")
+                Snackbar.make(mainLayout, R.string.permissions_not_granted,
+                        Snackbar.LENGTH_SHORT).show()
+
+            }
+        } else if (requestCode == REQUEST_CONTACTS) {
+            Log.i(TAG, "Received response for contact permissions request.")
+
+            // We have requested multiple permissions for contacts, so all of them need to be
+            // checked.
+            if (grantResults.containsOnly(PackageManager.PERMISSION_GRANTED)) {
+                // All required permissions have been granted, display contacts fragment.
+                Snackbar.make(mainLayout, R.string.permision_available_contacts,
+                        Snackbar.LENGTH_SHORT)
+                        .show()
+            } else {
+                Log.i(TAG, "Contacts permissions were NOT granted.")
+                Snackbar.make(mainLayout, R.string.permissions_not_granted,
+                        Snackbar.LENGTH_SHORT)
+                        .show()
+            }
+
+        } else {
+            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
+        }
+    }
+
+    fun onBackClick(view: View) {
+        supportFragmentManager.popBackStack()
+    }
+
+    companion object {
+
+        const val TAG = "MainActivity"
+        /**
+         * Id to identify a camera permission request.
+         */
+        const val REQUEST_CAMERA = 0
+        /**
+         * Id to identify a contacts permission request.
+         */
+        const val REQUEST_CONTACTS = 1
+        /**
+         * Permissions required to read and write contacts. Used by the [ContactsFragment].
+         */
+        val PERMISSIONS_CONTACT = arrayOf(Manifest.permission.READ_CONTACTS,
+                Manifest.permission.WRITE_CONTACTS)
+    }
+}
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/RuntimePermissionsFragment.kt b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/RuntimePermissionsFragment.kt
new file mode 100644
index 0000000..91a73c0
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/RuntimePermissionsFragment.kt
@@ -0,0 +1,44 @@
+/*
+* Copyright 2017 The Android Open Source Project
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package com.example.android.system.runtimepermissions
+
+import android.os.Build
+import android.os.Bundle
+import android.support.v4.app.Fragment
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import kotlinx.android.synthetic.main.fragment_main.*
+
+class RuntimePermissionsFragment : Fragment() {
+
+    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
+            savedInstanceState: Bundle?): View =
+            inflater.inflate(R.layout.fragment_main, container, false).apply {
+                if (Build.VERSION.SDK_INT < 23) {
+                    /*
+                    The contacts permissions have been declared in the AndroidManifest for Android M
+                    and above only. They are not available on older platforms, so we are hiding the
+                    button to access the contacts database.
+                    This shows how new runtime-only permissions can be added, that do not apply to
+                    older platform versions. This can be useful for automated updates where
+                    additional permissions might prompt the user on upgrade.
+                     */
+                    contactsButton.visibility = View.GONE
+                }
+            }
+}
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreview.kt b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreview.kt
new file mode 100644
index 0000000..187b55e
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreview.kt
@@ -0,0 +1,117 @@
+/*
+* Copyright 2017 The Android Open Source Project
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package com.example.android.system.runtimepermissions.camera
+
+import android.content.Context
+import android.hardware.Camera
+import android.util.Log
+import android.view.SurfaceHolder
+import android.view.SurfaceView
+import com.example.android.system.runtimepermissions.extensions.calculatePreviewOrientation
+import java.io.IOException
+
+/**
+ * Camera preview that displays a [Camera].
+ *
+ *
+ * Handles basic lifecycle methods to display and stop the preview.
+ *
+ *
+ * Implementation is based directly on the documentation at
+ * http://developer.android.com/guide/topics/media/camera.html
+ *
+ *
+ * Using deprecated android.hardware.Camera API in order to support {14 < API < 21}.
+ */
+class CameraPreview @JvmOverloads constructor(
+        context: Context,
+        private val camera: Camera? = null,
+        private val cameraInfo: Camera.CameraInfo? = null,
+        private val displayOrientation: Int = 0
+) : SurfaceView(context), SurfaceHolder.Callback {
+
+    private var surfaceHolder: SurfaceHolder? = null
+
+    init {
+
+        // Do not initialise if no camera has been set
+        if (camera != null && cameraInfo != null) {
+            // Install a SurfaceHolder.Callback so we get notified when the
+            // underlying surface is created and destroyed.
+            surfaceHolder = holder.apply {
+                addCallback(this@CameraPreview)
+            }
+        }
+    }
+
+    override fun surfaceCreated(holder: SurfaceHolder) {
+        // The Surface has been created, now tell the camera where to draw the preview.
+        try {
+            camera?.run {
+                setPreviewDisplay(holder)
+                startPreview()
+                Log.d(TAG, "Camera preview started.")
+            }
+        } catch (e: IOException) {
+            Log.d(TAG, "Error setting camera preview: " + e.message)
+        }
+
+    }
+
+    override fun surfaceDestroyed(holder: SurfaceHolder) {
+        // Empty. Take care of releasing the Camera preview in your activity.
+    }
+
+    override fun surfaceChanged(holder: SurfaceHolder, format: Int, w: Int, h: Int) {
+        // If your preview can change or rotate, take care of those events here.
+        // Make sure to stop the preview before resizing or reformatting it.
+
+        if (surfaceHolder?.surface == null) {
+            // preview surface does not exist
+            Log.d(TAG, "Preview surface does not exist")
+            return
+        }
+
+        // stop preview before making changes
+        try {
+            camera?.run {
+                stopPreview()
+                Log.d(TAG, "Preview stopped.")
+            }
+        } catch (e: Exception) {
+            // ignore: tried to stop a non-existent preview
+            Log.d(TAG, "Error starting camera preview: " + e.message)
+        }
+
+        try {
+            camera?.run {
+                cameraInfo?.run {
+                    setDisplayOrientation(calculatePreviewOrientation(displayOrientation))
+                }
+                setPreviewDisplay(surfaceHolder)
+                startPreview()
+                Log.d(TAG, "Camera preview started.")
+            }
+        } catch (e: Exception) {
+            Log.d(TAG, "Error starting camera preview: " + e.message)
+        }
+    }
+
+    companion object {
+        private const val TAG = "CameraPreview"
+    }
+}
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreviewFragment.kt b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreviewFragment.kt
new file mode 100644
index 0000000..2edbfba
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreviewFragment.kt
@@ -0,0 +1,99 @@
+/*
+* Copyright 2017 The Android Open Source Project
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package com.example.android.system.runtimepermissions.camera
+
+import android.hardware.Camera
+import android.os.Bundle
+import android.support.design.widget.Snackbar
+import android.support.v4.app.Fragment
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import com.example.android.system.runtimepermissions.R
+import kotlinx.android.synthetic.main.fragment_camera.*
+
+/**
+ * Displays a [CameraPreview] of the first [Camera].
+ * An error message is displayed if the Camera is not available.
+ *
+ *
+ * This Fragment is only used to illustrate that access to the Camera API has been granted (or
+ * denied) as part of the runtime permissions model. It is not relevant for the use of the
+ * permissions API.
+ *
+ *
+ * Implementation is based directly on the documentation at
+ * http://developer.android.com/guide/topics/media/camera.html
+ */
+class CameraPreviewFragment : Fragment() {
+
+    private lateinit var preview: CameraPreview
+    private var camera: Camera? = null
+
+    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
+            savedInstanceState: Bundle?): View {
+
+        // Open an instance of the first camera and retrieve its info.
+        camera = Camera.open(CAMERA_ID)
+        val cameraInfo: Camera.CameraInfo = Camera.CameraInfo()
+
+        if (camera != null) {
+            // Get camera info only if the camera is available
+            Camera.getCameraInfo(CAMERA_ID, cameraInfo)
+        }
+
+        val root: View
+
+        if (camera == null) {
+            // Camera is not available, display error message
+            root = inflater.inflate(R.layout.fragment_camera_unavailable, container, false)
+            Snackbar.make(root, "Camera is not available.", Snackbar.LENGTH_SHORT).show()
+        } else {
+            root = inflater.inflate(R.layout.fragment_camera, container, false)
+
+            // Get the rotation of the screen to adjust the preview image accordingly.
+            val displayRotation = activity.windowManager.defaultDisplay.rotation
+
+            // Create the Preview view and set it as the content of this Activity.
+            preview = CameraPreview(activity, camera, cameraInfo, displayRotation)
+            cameraPreview.addView(preview)
+        }
+
+        return root
+    }
+
+    override fun onPause() {
+        super.onPause()
+        // Stop camera access
+        releaseCamera()
+    }
+
+    private fun releaseCamera() {
+        camera?.release() // release the camera for other applications.
+        camera = null
+    }
+
+    companion object {
+
+        /**
+         * Id of the camera to access. 0 is the first camera.
+         */
+        private const val CAMERA_ID = 0
+
+        fun newInstance() = CameraPreviewFragment()
+    }
+}
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/contacts/ContactsFragment.kt b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/contacts/ContactsFragment.kt
new file mode 100644
index 0000000..b7af99f
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/contacts/ContactsFragment.kt
@@ -0,0 +1,153 @@
+/*
+* Copyright 2015 The Android Open Source Project
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package com.example.android.system.runtimepermissions.contacts
+
+import android.content.ContentProviderOperation
+import android.content.OperationApplicationException
+import android.database.Cursor
+import android.os.Bundle
+import android.os.RemoteException
+import android.provider.ContactsContract
+import android.support.design.widget.Snackbar
+import android.support.v4.app.Fragment
+import android.support.v4.app.LoaderManager
+import android.support.v4.content.CursorLoader
+import android.support.v4.content.Loader
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import com.example.android.system.runtimepermissions.R
+import kotlinx.android.synthetic.main.fragment_contacts.*
+import java.util.ArrayList
+
+/**
+ * Displays the first contact stored on the device and contains an option to add a dummy contact.
+ *
+ *
+ * This Fragment is only used to illustrate that access to the Contacts ContentProvider API has
+ * been granted (or denied) as part of the runtime permissions model. It is not relevant for the
+ * use
+ * of the permissions API.
+ *
+ *
+ * This fragments demonstrates a basic use case for accessing the Contacts Provider. The
+ * implementation is based on the training guide available here:
+ * https://developer.android.com/training/contacts-provider/retrieve-names.html
+ */
+class ContactsFragment : Fragment(), LoaderManager.LoaderCallbacks<Cursor> {
+
+    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
+            savedInstanceState: Bundle?): View =
+            inflater.inflate(R.layout.fragment_contacts, container, false).apply {
+                // Register a listener to add a dummy contact when a button is clicked.
+                contactAddButton.setOnClickListener { insertDummyContact() }
+
+                // Register a listener to display the first contact when a button is clicked.
+                contactLoadButton.setOnClickListener { loadContact() }
+            }
+
+    /**
+     * Restart the Loader to query the Contacts content provider to display the first contact.
+     */
+    private fun loadContact() {
+        loaderManager.restartLoader(0, Bundle(), this)
+    }
+
+    /**
+     * Initialises a new [CursorLoader] that queries the [ContactsContract].
+     */
+    override fun onCreateLoader(i: Int, bundle: Bundle): Loader<Cursor> =
+            CursorLoader(activity, ContactsContract.Contacts.CONTENT_URI, PROJECTION, null, null,
+                    ORDER)
+
+
+    /**
+     * Dislays either the name of the first contact or a message.
+     */
+    override fun onLoadFinished(loader: Loader<Cursor>, cursor: Cursor?) {
+        cursor?.run {
+            if (count > 0) {
+                moveToFirst()
+                val name = getString(getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
+                contactMessage.text = resources.getString(R.string.contacts_string, count, name)
+            } else {
+                contactMessage.text = resources.getString(R.string.contacts_empty)
+            }
+        }
+    }
+
+    override fun onLoaderReset(loader: Loader<Cursor>) {
+        contactMessage.text = getString(R.string.contacts_empty)
+    }
+
+    /**
+     * Accesses the Contacts content provider directly to insert a new contact.
+     *
+     *
+     * The contact is called "__DUMMY ENTRY" and only contains a name.
+     */
+    private fun insertDummyContact() {
+        // Two operations are needed to insert a new contact.
+        val operations = ArrayList<ContentProviderOperation>(2)
+
+        // First, set up a new raw contact.
+        operations.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
+                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
+                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
+                .build())
+
+        // Next, set the name for the contact.
+        operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+                .withValue(ContactsContract.Data.MIMETYPE,
+                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
+                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
+                        DUMMY_CONTACT_NAME)
+                .build())
+
+        // Apply the operations.
+        try {
+            activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations)
+        } catch (e: RemoteException) {
+            Snackbar.make(contactMessage.rootView, "Could not add a new contact: " + e.message,
+                    Snackbar.LENGTH_LONG)
+        } catch (e: OperationApplicationException) {
+            Snackbar.make(contactMessage.rootView, "Could not add a new contact: " + e.message,
+                    Snackbar.LENGTH_LONG)
+        }
+
+    }
+
+    companion object {
+
+        /**
+         * Projection for the content provider query includes the id and primary name of a contact.
+         */
+        @JvmField val PROJECTION = arrayOf(ContactsContract.Contacts._ID,
+                ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)
+        /**
+         * Sort order for the query. Sorted by primary name in ascending order.
+         */
+        const val ORDER = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC"
+        const val DUMMY_CONTACT_NAME = "__DUMMY CONTACT from runtime permissions sample"
+
+        /**
+         * Creates a new instance of a ContactsFragment.
+         */
+        fun newInstance() = ContactsFragment()
+    }
+}
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/AppCompatActivityExts.kt b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/AppCompatActivityExts.kt
new file mode 100644
index 0000000..ba1ec2a
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/AppCompatActivityExts.kt
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.example.android.system.runtimepermissions.extensions
+
+import android.content.pm.PackageManager
+import android.support.v4.app.ActivityCompat
+import android.support.v7.app.AppCompatActivity
+
+fun AppCompatActivity.isPermissionGranted(permission: String) =
+        ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
+
+fun AppCompatActivity.shouldShowPermissionRationale(permission: String) =
+        ActivityCompat.shouldShowRequestPermissionRationale(this, permission)
+
+fun AppCompatActivity.requestPermission(permission: String, requestId: Int) =
+        ActivityCompat.requestPermissions(this, arrayOf(permission), requestId)
+
+fun AppCompatActivity.batchRequestPermissions(permissions: Array<String>, requestId: Int) =
+        ActivityCompat.requestPermissions(this, permissions, requestId)
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/CameraExts.kt b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/CameraExts.kt
new file mode 100644
index 0000000..ffc6c76
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/CameraExts.kt
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.example.android.system.runtimepermissions.extensions
+
+import android.hardware.Camera
+import android.view.Surface
+
+/**
+ * Calculate the correct orientation for a [Camera] preview that is displayed on screen.
+ *
+ *
+ * Implementation is based on the sample code provided in
+ * [Camera.setDisplayOrientation].
+ */
+fun Camera.CameraInfo.calculatePreviewOrientation(rotation: Int): Int {
+
+    val degrees = when (rotation) {
+        Surface.ROTATION_0 -> 0
+        Surface.ROTATION_90 -> 90
+        Surface.ROTATION_180 -> 180
+        Surface.ROTATION_270 -> 270
+        else -> 0
+    }
+
+    return when (facing) {
+        Camera.CameraInfo.CAMERA_FACING_FRONT -> (360 - ((orientation + degrees) % 360)) % 360
+        Camera.CameraInfo.CAMERA_FACING_BACK -> (orientation - degrees + 360) % 360
+        else -> orientation
+    }
+}
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/CollectionsExts.kt b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/CollectionsExts.kt
new file mode 100644
index 0000000..36684e0
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/CollectionsExts.kt
@@ -0,0 +1,18 @@
+/*
+* Copyright 2017 The Android Open Source Project
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package com.example.android.system.runtimepermissions.extensions
+
+fun IntArray.containsOnly(num: Int): Boolean = filter { it == num }.isNotEmpty()
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/drawable/tile.9.png b/system/RuntimePermissions/kotlinApp/app/src/main/res/drawable/tile.9.png
new file mode 100644
index 0000000..1358628
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/drawable/tile.9.png
Binary files differ
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/activity_main.xml b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..7e2da81
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,59 @@
+<!--
+  Copyright 2017 The Android Open Source Project
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+  -->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/mainLayout"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical">
+
+    <ViewAnimator
+        android:id="@+id/sampleOutput"
+        android:layout_width="match_parent"
+        android:layout_height="0px"
+        android:layout_weight="1">
+
+        <ScrollView
+            style="@style/Widget.SampleMessageTile"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent">
+
+            <TextView
+                style="@style/Widget.SampleMessage"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:paddingBottom="@dimen/vertical_page_margin"
+                android:paddingLeft="@dimen/horizontal_page_margin"
+                android:paddingRight="@dimen/horizontal_page_margin"
+                android:paddingTop="@dimen/vertical_page_margin"
+                android:text="@string/intro_message" />
+        </ScrollView>
+
+    </ViewAnimator>
+
+    <View
+        android:layout_width="match_parent"
+        android:layout_height="1dp"
+        android:background="@android:color/darker_gray" />
+
+    <FrameLayout
+        android:id="@+id/sampleContentFragment"
+        android:layout_width="match_parent"
+        android:layout_height="0px"
+        android:layout_weight="2" />
+
+</LinearLayout>
+
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_camera.xml b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_camera.xml
new file mode 100644
index 0000000..5245b35
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_camera.xml
@@ -0,0 +1,33 @@
+<!--
+ Copyright 2017 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:orientation="vertical">
+
+    <Button
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center_horizontal"
+        android:onClick="onBackClick"
+        android:text="@string/back" />
+
+    <FrameLayout
+        android:id="@+id/cameraPreview"
+        android:layout_width="match_parent"
+        android:layout_height="0dp"
+        android:layout_weight="1" />
+</LinearLayout>
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_camera_unavailable.xml b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_camera_unavailable.xml
new file mode 100644
index 0000000..bb662d9
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_camera_unavailable.xml
@@ -0,0 +1,43 @@
+<!--
+ Copyright 2017 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:orientation="vertical">
+
+    <Button
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center_horizontal"
+        android:onClick="onBackClick"
+        android:text="@string/back" />
+
+    <ScrollView
+        android:layout_width="match_parent"
+        android:layout_height="fill_parent">
+
+        <TextView
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:paddingBottom="@dimen/vertical_page_margin"
+            android:paddingLeft="@dimen/horizontal_page_margin"
+            android:paddingRight="@dimen/horizontal_page_margin"
+            android:paddingTop="@dimen/vertical_page_margin"
+            android:text="@string/camera_unavailable" />
+
+    </ScrollView>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_contacts.xml b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_contacts.xml
new file mode 100644
index 0000000..da55692
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_contacts.xml
@@ -0,0 +1,55 @@
+<!--
+ Copyright 2017 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:id="@+id/contactsLayout"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:orientation="vertical"
+              android:paddingBottom="@dimen/vertical_page_margin"
+              android:paddingLeft="@dimen/horizontal_page_margin"
+              android:paddingRight="@dimen/horizontal_page_margin"
+              android:paddingTop="@dimen/vertical_page_margin">
+
+    <Button
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center_horizontal"
+        android:onClick="onBackClick"
+        android:text="@string/back" />
+
+    <TextView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/contacts_intro" />
+
+    <TextView
+        android:id="@+id/contactMessage"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content" />
+
+    <Button
+        android:id="@+id/contactAddButton"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/add_contact" />
+
+    <Button
+        android:id="@+id/contactLoadButton"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/show_contact" />
+
+</LinearLayout>
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_main.xml b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_main.xml
new file mode 100644
index 0000000..7bfb022
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/layout/fragment_main.xml
@@ -0,0 +1,48 @@
+<!--
+ Copyright 2017 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              xmlns:tools="http://schemas.android.com/tools"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:orientation="vertical"
+              android:paddingBottom="@dimen/vertical_page_margin"
+              android:paddingLeft="@dimen/horizontal_page_margin"
+              android:paddingRight="@dimen/horizontal_page_margin"
+              android:paddingTop="@dimen/vertical_page_margin"
+              tools:context=".RuntimePermissionsFragment">
+
+    <TextView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/main_introduction" />
+
+    <Button
+        android:id="@+id/cameraButton"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:onClick="showCamera"
+        android:text="@string/show_camera" />
+
+
+    <Button
+        android:id="@+id/contactsButton"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:onClick="showContacts"
+        android:text="@string/show_contacts" />
+
+</LinearLayout>
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-hdpi/ic_launcher.png b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..3279054
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-hdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-mdpi/ic_launcher.png b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..225fe42
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-mdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..c129dbb
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..b4ab118
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..99649fb
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/values/colors.xml b/system/RuntimePermissions/kotlinApp/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..8d19ba1
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/values/colors.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright 2017 The Android Open Source Project
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+  -->
+<resources>
+    <color name="colorPrimary">#3F51B5</color>
+    <color name="colorPrimaryDark">#303F9F</color>
+    <color name="colorAccent">#FF4081</color>
+</resources>
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/values/dimens.xml b/system/RuntimePermissions/kotlinApp/app/src/main/res/values/dimens.xml
new file mode 100644
index 0000000..2cf1fbe
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/values/dimens.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright 2017 The Android Open Source Project
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+  -->
+<resources>
+    <!-- Define standard dimensions to comply with Holo-style grids and rhythm. -->
+
+    <dimen name="margin_tiny">4dp</dimen>
+    <dimen name="margin_small">8dp</dimen>
+    <dimen name="margin_medium">16dp</dimen>
+    <dimen name="margin_large">32dp</dimen>
+    <dimen name="margin_huge">64dp</dimen>
+
+    <!-- Semantic definitions -->
+
+    <dimen name="horizontal_page_margin">@dimen/margin_medium</dimen>
+    <dimen name="vertical_page_margin">@dimen/margin_medium</dimen>
+</resources>
\ No newline at end of file
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/values/strings.xml b/system/RuntimePermissions/kotlinApp/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..54c043a
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/values/strings.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright 2017 The Android Open Source Project
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+  -->
+<resources>
+    <string name="app_name">RuntimePermissions</string>
+    <string name="intro_message">
+        <![CDATA[
+
+
+            This sample shows runtime permissions available in Android M and above.
+            Display the log on screen to follow the execution.
+            If executed on an Android M device, an additional option to access contacts is shown
+            that is declared with optional, M and above only permissions.
+
+
+        ]]>
+    </string>
+    <string name="ok">OK</string>
+    <string name="contacts_string">Total number of contacts: %1$,d\nFirst contact:<b>%2$s</b></string>
+    <string name="contacts_none">No contacts stored on device.</string>
+    <string name="contacts_empty">Contacts not loaded.</string>
+    <string name="add_contact">Add a contact</string>
+    <string name="show_contact">Show first contact</string>
+    <string name="contacts_intro">This fragment demonstrates access to the contact database on the device.\n
+            Clicking \"Add a contact\" adds a new contact named "__DUMMY ENTRY" directly into the database.\n
+    Clicking \"Show first contact\" accesses the contact database to display the name of the first contact.</string>
+    <string name="camera_unavailable"><b>Camera could not be opened.</b>\nThis occurs when the camera is not available (for example it is already in use) or if the system has denied access (for example when camera access has been disabled).</string>
+    <string name="back">Back</string>
+    <string name="show_camera">Show camera preview</string>
+    <string name="show_contacts">Show and add contacts</string>
+    <string name="main_introduction">Click the buttons below to show a camera preview or access the contacts database.\nNote that the contacts option is only available on Android M to illustrate the use of optional, M-only permissions that are not requested on lower SDK platforms.</string>
+    <string name="permision_available_camera">Camera Permission has been granted. Preview can now be opened.</string>
+    <string name="permision_available_contacts">Contacts Permissions have been granted. Contacts screen can now be opened.</string>
+    <string name="permissions_not_granted">Permissions were not granted.</string>
+    <string name="permission_camera_rationale">Camera permission is needed to show the camera preview.</string>
+    <string name="permission_contacts_rationale">Contacts permissions are needed to demonstrate access.</string>
+</resources>
diff --git a/system/RuntimePermissions/kotlinApp/app/src/main/res/values/styles.xml b/system/RuntimePermissions/kotlinApp/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..7adf89d
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/app/src/main/res/values/styles.xml
@@ -0,0 +1,39 @@
+<!--
+  Copyright 2017 The Android Open Source Project
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+  -->
+<resources>
+
+    <style name="Theme.Base" parent="android:Theme.Light" />
+
+    <style name="Theme.Sample" parent="Theme.Base" />
+
+    <style name="AppTheme" parent="Theme.Sample" />
+    <!-- Widget styling -->
+
+    <style name="Widget" />
+
+    <style name="Widget.SampleMessage">
+        <item name="android:textAppearance">?android:textAppearanceMedium</item>
+        <item name="android:lineSpacingMultiplier">1.1</item>
+    </style>
+
+    <style name="Widget.SampleMessageTile">
+        <item name="android:background">@drawable/tile</item>
+        <item name="android:shadowColor">#7F000000</item>
+        <item name="android:shadowDy">-3.5</item>
+        <item name="android:shadowRadius">2</item>
+    </style>
+
+</resources>
diff --git a/system/RuntimePermissions/kotlinApp/build.gradle b/system/RuntimePermissions/kotlinApp/build.gradle
new file mode 100644
index 0000000..e1bc7db
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/build.gradle
@@ -0,0 +1,25 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+    ext.kotlin_version = '1.1.4'
+    repositories {
+        jcenter()
+    }
+    dependencies {
+        classpath 'com.android.tools.build:gradle:2.3.3'
+        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+    }
+}
+
+allprojects {
+    repositories {
+        jcenter()
+        maven {
+            url 'https://maven.google.com'
+        }
+    }
+}
+
+task clean(type: Delete) {
+    delete rootProject.buildDir
+}
diff --git a/system/RuntimePermissions/kotlinApp/gradle.properties b/system/RuntimePermissions/kotlinApp/gradle.properties
new file mode 100644
index 0000000..aac7c9b
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/gradle.properties
@@ -0,0 +1,17 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx1536m
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
diff --git a/system/RuntimePermissions/kotlinApp/gradle/wrapper/gradle-wrapper.jar b/system/RuntimePermissions/kotlinApp/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..13372ae
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/system/RuntimePermissions/kotlinApp/gradle/wrapper/gradle-wrapper.properties b/system/RuntimePermissions/kotlinApp/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..c0e49f9
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Wed Aug 16 15:09:26 PDT 2017
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
diff --git a/system/RuntimePermissions/kotlinApp/gradlew b/system/RuntimePermissions/kotlinApp/gradlew
new file mode 100755
index 0000000..9d82f78
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/gradlew
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+    JAVACMD=`cygpath --unix "$JAVACMD"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/system/RuntimePermissions/kotlinApp/gradlew.bat b/system/RuntimePermissions/kotlinApp/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off

+@rem ##########################################################################

+@rem

+@rem  Gradle startup script for Windows

+@rem

+@rem ##########################################################################

+

+@rem Set local scope for the variables with windows NT shell

+if "%OS%"=="Windows_NT" setlocal

+

+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.

+set DEFAULT_JVM_OPTS=

+

+set DIRNAME=%~dp0

+if "%DIRNAME%" == "" set DIRNAME=.

+set APP_BASE_NAME=%~n0

+set APP_HOME=%DIRNAME%

+

+@rem Find java.exe

+if defined JAVA_HOME goto findJavaFromJavaHome

+

+set JAVA_EXE=java.exe

+%JAVA_EXE% -version >NUL 2>&1

+if "%ERRORLEVEL%" == "0" goto init

+

+echo.

+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:findJavaFromJavaHome

+set JAVA_HOME=%JAVA_HOME:"=%

+set JAVA_EXE=%JAVA_HOME%/bin/java.exe

+

+if exist "%JAVA_EXE%" goto init

+

+echo.

+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:init

+@rem Get command-line arguments, handling Windowz variants

+

+if not "%OS%" == "Windows_NT" goto win9xME_args

+if "%@eval[2+2]" == "4" goto 4NT_args

+

+:win9xME_args

+@rem Slurp the command line arguments.

+set CMD_LINE_ARGS=

+set _SKIP=2

+

+:win9xME_args_slurp

+if "x%~1" == "x" goto execute

+

+set CMD_LINE_ARGS=%*

+goto execute

+

+:4NT_args

+@rem Get arguments from the 4NT Shell from JP Software

+set CMD_LINE_ARGS=%$

+

+:execute

+@rem Setup the command line

+

+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

+

+@rem Execute Gradle

+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

+

+:end

+@rem End local scope for the variables with windows NT shell

+if "%ERRORLEVEL%"=="0" goto mainEnd

+

+:fail

+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of

+rem the _cmd.exe /c_ return code!

+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1

+exit /b 1

+

+:mainEnd

+if "%OS%"=="Windows_NT" endlocal

+

+:omega

diff --git a/system/RuntimePermissions/kotlinApp/settings.gradle b/system/RuntimePermissions/kotlinApp/settings.gradle
new file mode 100644
index 0000000..e7b4def
--- /dev/null
+++ b/system/RuntimePermissions/kotlinApp/settings.gradle
@@ -0,0 +1 @@
+include ':app'