Add RuntimePermissions sample.
It shows use of runtime permissions API in M.
Change-Id: I29a1271186c2664a20f183b327ce6be25feec78f
diff --git a/system/RuntimePermissions/Application/.gitignore b/system/RuntimePermissions/Application/.gitignore
new file mode 100644
index 0000000..6eb878d
--- /dev/null
+++ b/system/RuntimePermissions/Application/.gitignore
@@ -0,0 +1,16 @@
+# Copyright 2013 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.
+src/template/
+src/common/
+build.gradle
diff --git a/system/RuntimePermissions/Application/proguard-project.txt b/system/RuntimePermissions/Application/proguard-project.txt
new file mode 100644
index 0000000..0d8f171
--- /dev/null
+++ b/system/RuntimePermissions/Application/proguard-project.txt
@@ -0,0 +1,20 @@
+ To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# 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 *;
+#}
diff --git a/system/RuntimePermissions/Application/src/main/AndroidManifest.xml b/system/RuntimePermissions/Application/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..050b051
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/AndroidManifest.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ 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.
+ -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.example.android.system.runtimepermissions" >
+
+ <!-- BEGIN_INCLUDE(manifest) -->
+
+ <!-- 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-m android:name="android.permission.READ_CONTACTS" />
+ <uses-permission-sdk-m android:name="android.permission.WRITE_CONTACTS" />
+
+ <!-- END_INCLUDE(manifest) -->
+
+ <application
+ android:allowBackup="true"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ <activity
+ android:name=".MainActivity"
+ android:label="@string/app_name" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+
+ </application>
+
+</manifest>
diff --git a/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/MainActivity.java b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/MainActivity.java
new file mode 100644
index 0000000..43436aa
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/MainActivity.java
@@ -0,0 +1,279 @@
+/*
+* 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;
+
+import com.example.android.common.activities.SampleActivityBase;
+import com.example.android.common.logger.Log;
+import com.example.android.common.logger.LogFragment;
+import com.example.android.common.logger.LogWrapper;
+import com.example.android.common.logger.MessageOnlyLogFilter;
+import com.example.android.system.runtimepermissions.camera.CameraPreviewFragment;
+import com.example.android.system.runtimepermissions.contacts.ContactsFragment;
+
+import android.Manifest;
+import android.app.Activity;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.support.v4.app.FragmentTransaction;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.widget.Toast;
+import android.widget.ViewAnimator;
+
+/**
+ * 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.
+ * <p>
+ * This Activity requests permissions to access the camera ({@link android.Manifest.permission#CAMERA})
+ * when the 'Show Camera' button is clicked to display the camera preview.
+ * Contacts permissions (({@link android.Manifest.permission#READ_CONTACTS} and ({@link
+ * 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. First, permissions are checked if they have already been granted through {@link
+ * android.app.Activity#checkSelfPermission(String)} (wrapped in {@link
+ * PermissionUtil#hasSelfPermission(Activity, String)} and {@link PermissionUtil#hasSelfPermission(Activity,
+ * String[])} for compatibility). If permissions have not been granted, they are requested through
+ * {@link Activity#requestPermissions(String[], int)} and the return value checked in {@link
+ * Activity#onRequestPermissionsResult(int, String[], int[])}.
+ * <p>
+ * 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.
+ * <p>
+ * 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.
+ * <p>
+ * (This class is based on the MainActivity used in the SimpleFragment sample template.)
+ */
+public class MainActivity extends SampleActivityBase {
+
+ public static final String TAG = "MainActivity";
+
+ /**
+ * Id to identify a camera permission request.
+ */
+ private static final int REQUEST_CAMERA = 0;
+
+ /**
+ * Id to identify a contacts permission request.
+ */
+ private static final int REQUEST_CONTACTS = 1;
+
+ /**
+ * Permissions required to read and write contacts. Used by the {@link ContactsFragment}.
+ */
+ private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS,
+ Manifest.permission.WRITE_CONTACTS};
+
+ // Whether the Log Fragment is currently shown.
+ private boolean mLogShown;
+
+
+ /**
+ * Called when the 'show camera' button is clicked.
+ * Callback is defined in resource layout definition.
+ */
+ public void showCamera(View view) {
+ Log.i(TAG, "Show camera button pressed. Checking permission.");
+ // BEGIN_INCLUDE(camera_permission)
+ // Check if the Camera permission is already available.
+ if (PermissionUtil.hasSelfPermission(this, Manifest.permission.CAMERA)) {
+ Log.i(TAG,
+ "CAMERA permission has already been granted. Displaying camera preview.");
+ // Camera permissions is already available, show the camera preview.
+ showCameraPreview();
+ } else {
+ Log.i(TAG, "CAMERA permission has NOT been granted. Requesting permission.");
+ // Camera permission has not been granted. Request it.
+ requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);
+ }
+ // END_INCLUDE(camera_permission)
+
+ }
+
+ /**
+ * Called when the 'show camera' button is clicked.
+ * Callback is defined in resource layout definition.
+ */
+ public void showContacts(View v) {
+ Log.i(TAG, "Show contacts button pressed. Checking permissions.");
+ // Verify that all required contact permissions have been granted.
+ if (PermissionUtil.hasSelfPermission(this, PERMISSIONS_CONTACT)) {
+ Log.i(TAG,
+ "Contact permissions have already been granted. Displaying contact details.");
+ // Contact permissions have been granted. Show the contacts fragment.
+ showContactDetails();
+ } else {
+ Log.i(TAG, "Contact permissions has NOT been granted. Requesting permission.");
+ // contact permissions has not been granted (read and write contacts). Request them.
+ requestPermissions(PERMISSIONS_CONTACT, REQUEST_CONTACTS);
+ }
+ }
+
+ /**
+ * Display the {@link CameraPreviewFragment} in the content area if the required Camera
+ * permission has been granted.
+ */
+ private void showCameraPreview() {
+ getSupportFragmentManager().beginTransaction()
+ .replace(R.id.sample_content_fragment, CameraPreviewFragment.newInstance())
+ .addToBackStack("contacts")
+ .commit();
+ }
+
+ /**
+ * Display the {@link ContactsFragment} in the content area if the required contacts
+ * permissions
+ * have been granted.
+ */
+ private void showContactDetails() {
+ getSupportFragmentManager().beginTransaction()
+ .replace(R.id.sample_content_fragment, ContactsFragment.newInstance())
+ .addToBackStack("contacts")
+ .commit();
+ }
+
+
+ /**
+ * Callback received when a permissions request has been completed.
+ */
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions,
+ int[] grantResults) {
+
+ if (requestCode == REQUEST_CAMERA) {
+ // BEGIN_INCLUDE(permission_result)
+ // Received permission result for camera permission.
+ Log.i(TAG, "Received response for Camera permission request.");
+
+ // Check if the only required permission has been granted
+ if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+ // Camera permission has been granted, preview can be displayed
+ Log.i(TAG, "CAMERA permission has now been granted. Showing preview.");
+ Toast.makeText(this, R.string.permision_available_camera, Toast.LENGTH_SHORT)
+ .show();
+ } else {
+ Log.i(TAG, "CAMERA permission was NOT granted.");
+ Toast.makeText(this, R.string.permissions_not_granted, Toast.LENGTH_SHORT).show();
+
+ }
+ // END_INCLUDE(permission_result)
+
+ } 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 (PermissionUtil.verifyPermissions(grantResults)) {
+ // All required permissions have been granted, display contacts fragment.
+ Toast.makeText(this, R.string.permision_available_contacts, Toast.LENGTH_SHORT)
+ .show();
+ } else {
+ Log.i(TAG, "Contacts permissions were NOT granted.");
+ Toast.makeText(this, R.string.permissions_not_granted, Toast.LENGTH_SHORT).show();
+ }
+
+ } else {
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults);
+ }
+ }
+
+ /* Note: Methods and definitions below are only used to provide the UI for this sample and are
+ not relevant for the execution of the runtime permissions API. */
+
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.main, menu);
+ return true;
+ }
+
+ @Override
+ public boolean onPrepareOptionsMenu(Menu menu) {
+ MenuItem logToggle = menu.findItem(R.id.menu_toggle_log);
+ logToggle.setVisible(findViewById(R.id.sample_output) instanceof ViewAnimator);
+ logToggle.setTitle(mLogShown ? R.string.sample_hide_log : R.string.sample_show_log);
+
+ return super.onPrepareOptionsMenu(menu);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case R.id.menu_toggle_log:
+ mLogShown = !mLogShown;
+ ViewAnimator output = (ViewAnimator) findViewById(R.id.sample_output);
+ if (mLogShown) {
+ output.setDisplayedChild(1);
+ } else {
+ output.setDisplayedChild(0);
+ }
+ supportInvalidateOptionsMenu();
+ return true;
+ }
+ return super.onOptionsItemSelected(item);
+ }
+
+ /** Create a chain of targets that will receive log data */
+ @Override
+ public void initializeLogging() {
+ // Wraps Android's native log framework.
+ LogWrapper logWrapper = new LogWrapper();
+ // Using Log, front-end to the logging chain, emulates android.util.log method signatures.
+ Log.setLogNode(logWrapper);
+
+ // Filter strips out everything except the message text.
+ MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
+ logWrapper.setNext(msgFilter);
+
+ // On screen logging via a fragment with a TextView.
+ LogFragment logFragment = (LogFragment) getSupportFragmentManager()
+ .findFragmentById(R.id.log_fragment);
+ msgFilter.setNext(logFragment.getLogView());
+ }
+
+ public void onBackClick(View view) {
+ getSupportFragmentManager().popBackStack();
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+
+ if (savedInstanceState == null) {
+ FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
+ RuntimePermissionsFragment fragment = new RuntimePermissionsFragment();
+ transaction.replace(R.id.sample_content_fragment, fragment);
+ transaction.commit();
+ }
+
+ // This method sets up our custom logger, which will print all log messages to the device
+ // screen, as well as to adb logcat.
+ initializeLogging();
+ }
+}
diff --git a/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/PermissionUtil.java b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/PermissionUtil.java
new file mode 100644
index 0000000..ba2370f
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/PermissionUtil.java
@@ -0,0 +1,90 @@
+/*
+* 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;
+
+import android.app.Activity;
+import android.content.pm.PackageManager;
+import android.os.Build;
+
+/**
+ * Utility class that wraps access to the runtime permissions API in M and provides basic helper
+ * methods.
+ */
+public abstract class PermissionUtil {
+
+ /**
+ * Check that all given permissions have been granted by verifying that each entry in the
+ * given array is of the value {@link PackageManager#PERMISSION_GRANTED}.
+ *
+ * @see Activity#onRequestPermissionsResult(int, String[], int[])
+ */
+ public static boolean verifyPermissions(int[] grantResults) {
+ // Verify that each required permission has been granted, otherwise return false.
+ for (int result : grantResults) {
+ if (result != PackageManager.PERMISSION_GRANTED) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns true if the Activity has access to all given permissions.
+ * Always returns true on platforms below M.
+ *
+ * @see Activity#checkSelfPermission(String)
+ */
+ public static boolean hasSelfPermission(Activity activity, String[] permissions) {
+ // Below Android M all permissions are granted at install time and are already available.
+ if (!isMNC()) {
+ return true;
+ }
+
+ // Verify that all required permissions have been granted
+ for (String permission : permissions) {
+ if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns true if the Activity has access to a given permission.
+ * Always returns true on platforms below M.
+ *
+ * @see Activity#checkSelfPermission(String)
+ */
+ public static boolean hasSelfPermission(Activity activity, String permission) {
+ // Below Android M all permissions are granted at install time and are already available.
+ if (!isMNC()) {
+ return true;
+ }
+
+ return activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
+ }
+
+ public static boolean isMNC() {
+ /*
+ TODO: In the Android M Preview release, checking if the platform is M is done through
+ the codename, not the version code. Once the API has been finalised, the following check
+ should be used: */
+ // return Build.VERSION.SDK_INT == Build.VERSION_CODES.MNC
+
+ return "MNC".equals(Build.VERSION.CODENAME);
+ }
+}
diff --git a/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/RuntimePermissionsFragment.java b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/RuntimePermissionsFragment.java
new file mode 100644
index 0000000..b35bfeb
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/RuntimePermissionsFragment.java
@@ -0,0 +1,50 @@
+/*
+* 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;
+
+import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+public class RuntimePermissionsFragment extends Fragment {
+
+ @Nullable
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View root = inflater.inflate(R.layout.fragment_main, null);
+
+ // BEGIN_INCLUDE(m_only_permission)
+ if (!PermissionUtil.isMNC()) {
+ /*
+ The contacts permissions have been declared in the AndroidManifest for Android M 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.
+ */
+ root.findViewById(R.id.button_camera).setVisibility(View.GONE);
+ }
+ // END_INCLUDE(m_only_permission)
+
+ return root;
+ }
+}
diff --git a/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreview.java b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreview.java
new file mode 100644
index 0000000..1d25b51
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreview.java
@@ -0,0 +1,142 @@
+/*
+* 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.camera;
+
+import android.content.Context;
+import android.hardware.Camera;
+import android.util.Log;
+import android.view.Surface;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+
+import java.io.IOException;
+
+/**
+ * Camera preview that displays a {@link Camera}.
+ *
+ * Handles basic lifecycle methods to display and stop the preview.
+ * <p>
+ * Implementation is based directly on the documentation at
+ * http://developer.android.com/guide/topics/media/camera.html
+ */
+public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
+
+ private static final String TAG = "CameraPreview";
+ private SurfaceHolder mHolder;
+ private Camera mCamera;
+ private Camera.CameraInfo mCameraInfo;
+ private int mDisplayOrientation;
+
+ public CameraPreview(Context context, Camera camera, Camera.CameraInfo cameraInfo,
+ int displayOrientation) {
+ super(context);
+
+ // Do not initialise if no camera has been set
+ if (camera == null || cameraInfo == null) {
+ return;
+ }
+ mCamera = camera;
+ mCameraInfo = cameraInfo;
+ mDisplayOrientation = displayOrientation;
+
+ // Install a SurfaceHolder.Callback so we get notified when the
+ // underlying surface is created and destroyed.
+ mHolder = getHolder();
+ mHolder.addCallback(this);
+ }
+
+ public void surfaceCreated(SurfaceHolder holder) {
+ // The Surface has been created, now tell the camera where to draw the preview.
+ try {
+ mCamera.setPreviewDisplay(holder);
+ mCamera.startPreview();
+ Log.d(TAG, "Camera preview started.");
+ } catch (IOException e) {
+ Log.d(TAG, "Error setting camera preview: " + e.getMessage());
+ }
+ }
+
+ public void surfaceDestroyed(SurfaceHolder holder) {
+ // empty. Take care of releasing the Camera preview in your activity.
+ }
+
+ public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
+ // 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 (mHolder.getSurface() == null) {
+ // preview surface does not exist
+ Log.d(TAG, "Preview surface does not exist");
+ return;
+ }
+
+ // stop preview before making changes
+ try {
+ mCamera.stopPreview();
+ Log.d(TAG, "Preview stopped.");
+ } catch (Exception e) {
+ // ignore: tried to stop a non-existent preview
+ Log.d(TAG, "Error starting camera preview: " + e.getMessage());
+ }
+
+ int orientation = calculatePreviewOrientation(mCameraInfo, mDisplayOrientation);
+ mCamera.setDisplayOrientation(orientation);
+
+ try {
+ mCamera.setPreviewDisplay(mHolder);
+ mCamera.startPreview();
+ Log.d(TAG, "Camera preview started.");
+ } catch (Exception e) {
+ Log.d(TAG, "Error starting camera preview: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Calculate the correct orientation for a {@link Camera} preview that is displayed on screen.
+ *
+ * Implementation is based on the sample code provided in
+ * {@link Camera#setDisplayOrientation(int)}.
+ */
+ public static int calculatePreviewOrientation(Camera.CameraInfo info, int rotation) {
+ int degrees = 0;
+
+ switch (rotation) {
+ case Surface.ROTATION_0:
+ degrees = 0;
+ break;
+ case Surface.ROTATION_90:
+ degrees = 90;
+ break;
+ case Surface.ROTATION_180:
+ degrees = 180;
+ break;
+ case Surface.ROTATION_270:
+ degrees = 270;
+ break;
+ }
+
+ int result;
+ if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
+ result = (info.orientation + degrees) % 360;
+ result = (360 - result) % 360; // compensate the mirror
+ } else { // back-facing
+ result = (info.orientation - degrees + 360) % 360;
+ }
+
+ return result;
+ }
+}
diff --git a/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreviewFragment.java b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreviewFragment.java
new file mode 100644
index 0000000..d0938f6
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/camera/CameraPreviewFragment.java
@@ -0,0 +1,112 @@
+/*
+* 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.camera;
+
+import com.example.android.common.logger.Log;
+import com.example.android.system.runtimepermissions.R;
+
+import android.hardware.Camera;
+import android.os.Bundle;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.FrameLayout;
+import android.widget.Toast;
+
+/**
+ * Displays a {@link CameraPreview} of the first {@link Camera}.
+ * An error message is displayed if the Camera is not available.
+ * <p>
+ * 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.
+ * <p>
+ * Implementation is based directly on the documentation at
+ * http://developer.android.com/guide/topics/media/camera.html
+ */
+public class CameraPreviewFragment extends Fragment {
+
+ private static final String TAG = "CameraPreview";
+
+ /**
+ * Id of the camera to access. 0 is the first camera.
+ */
+ private static final int CAMERA_ID = 0;
+
+ private CameraPreview mPreview;
+ private Camera mCamera;
+
+ public static CameraPreviewFragment newInstance() {
+ return new CameraPreviewFragment();
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+
+ // Open an instance of the first camera and retrieve its info.
+ mCamera = getCameraInstance(CAMERA_ID);
+ Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
+ Camera.getCameraInfo(CAMERA_ID, cameraInfo);
+
+ if (mCamera == null || cameraInfo == null) {
+ // Camera is not available, display error message
+ Toast.makeText(getActivity(), "Camera is not available.", Toast.LENGTH_SHORT).show();
+ return inflater.inflate(R.layout.fragment_camera_unavailable, null);
+ }
+
+ View root = inflater.inflate(R.layout.fragment_camera, null);
+
+ // Get the rotation of the screen to adjust the preview image accordingly.
+ final int displayRotation = getActivity().getWindowManager().getDefaultDisplay()
+ .getRotation();
+
+ // Create the Preview view and set it as the content of this Activity.
+ mPreview = new CameraPreview(getActivity(), mCamera, cameraInfo, displayRotation);
+ FrameLayout preview = (FrameLayout) root.findViewById(R.id.camera_preview);
+ preview.addView(mPreview);
+
+ return root;
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause();
+ // Stop camera access
+ releaseCamera();
+ }
+
+ /** A safe way to get an instance of the Camera object. */
+ public static Camera getCameraInstance(int cameraId) {
+ Camera c = null;
+ try {
+ c = Camera.open(cameraId); // attempt to get a Camera instance
+ } catch (Exception e) {
+ // Camera is not available (in use or does not exist)
+ Log.d(TAG, "Camera " + cameraId + " is not available: " + e.getMessage());
+ }
+ return c; // returns null if camera is unavailable
+ }
+
+ private void releaseCamera() {
+ if (mCamera != null) {
+ mCamera.release(); // release the camera for other applications
+ mCamera = null;
+ }
+ }
+}
diff --git a/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/contacts/ContactsFragment.java b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/contacts/ContactsFragment.java
new file mode 100644
index 0000000..19f54fb
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/java/com/example/android/system/runtimepermissions/contacts/ContactsFragment.java
@@ -0,0 +1,189 @@
+/*
+* 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 com.example.android.common.logger.Log;
+import com.example.android.system.runtimepermissions.R;
+
+import android.content.ContentProviderOperation;
+import android.content.ContentResolver;
+import android.content.OperationApplicationException;
+import android.database.Cursor;
+import android.os.Bundle;
+import android.os.RemoteException;
+import android.provider.ContactsContract;
+import android.support.annotation.Nullable;
+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 android.widget.Button;
+import android.widget.TextView;
+
+import java.util.ArrayList;
+
+/**
+ * Displays the first contact stored on the device and contains an option to add a dummy contact.
+ * <p>
+ * 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.
+ * <p>
+ * 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
+ */
+public class ContactsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
+
+ private static final String TAG = "Contacts";
+ private TextView mMessageText = null;
+
+ private static String DUMMY_CONTACT_NAME = "__DUMMY CONTACT from runtime permissions sample";
+
+ /**
+ * Projection for the content provider query includes the id and primary name of a contact.
+ */
+ private static final String[] PROJECTION = {ContactsContract.Contacts._ID,
+ ContactsContract.Contacts.DISPLAY_NAME_PRIMARY};
+ /**
+ * Sort order for the query. Sorted by primary name in ascending order.
+ */
+ private static final String ORDER = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC";
+
+
+ /**
+ * Creates a new instance of a ContactsFragment.
+ */
+ public static ContactsFragment newInstance() {
+ return new ContactsFragment();
+ }
+
+
+ @Nullable
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
+
+ mMessageText = (TextView) rootView.findViewById(R.id.contact_message);
+
+ // Register a listener to add a dummy contact when a button is clicked.
+ Button button = (Button) rootView.findViewById(R.id.contact_add);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ insertDummyContact();
+ }
+ });
+
+ // Register a listener to display the first contact when a button is clicked.
+ button = (Button) rootView.findViewById(R.id.contact_load);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ loadContact();
+ }
+ });
+ return rootView;
+ }
+
+ /**
+ * Restart the Loader to query the Contacts content provider to display the first contact.
+ */
+ private void loadContact() {
+ getLoaderManager().restartLoader(0, null, this);
+ }
+
+ /**
+ * Initialises a new {@link CursorLoader} that queries the {@link ContactsContract}.
+ */
+ @Override
+ public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
+ return new CursorLoader(getActivity(), ContactsContract.Contacts.CONTENT_URI, PROJECTION,
+ null, null, ORDER);
+ }
+
+
+ /**
+ * Dislays either the name of the first contact or a message.
+ */
+ @Override
+ public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
+
+ if (cursor != null) {
+ final int totalCount = cursor.getCount();
+ if (totalCount > 0) {
+ cursor.moveToFirst();
+ String name = cursor
+ .getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
+ mMessageText.setText(
+ getResources().getString(R.string.contacts_string, totalCount, name));
+ Log.d(TAG, "First contact loaded: " + name);
+ Log.d(TAG, "Total number of contacts: " + totalCount);
+ Log.d(TAG, "Total number of contacts: " + totalCount);
+ } else {
+ Log.d(TAG, "List of contacts is empty.");
+ mMessageText.setText(R.string.contacts_empty);
+ }
+ }
+ }
+
+ @Override
+ public void onLoaderReset(Loader<Cursor> loader) {
+ mMessageText.setText(R.string.contacts_empty);
+ }
+
+ /**
+ * Accesses the Contacts content provider directly to insert a new contact.
+ * <p>
+ * The contact is called "__DUMMY ENTRY" and only contains a name.
+ */
+ private void insertDummyContact() {
+ // Two operations are needed to insert a new contact.
+ ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(2);
+
+ // First, set up a new raw contact.
+ ContentProviderOperation.Builder op =
+ ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
+ .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
+ .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
+ operations.add(op.build());
+
+ // Next, set the name for the contact.
+ op = 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);
+ operations.add(op.build());
+
+ // Apply the operations.
+ ContentResolver resolver = getActivity().getContentResolver();
+ try {
+ resolver.applyBatch(ContactsContract.AUTHORITY, operations);
+ } catch (RemoteException e) {
+ Log.d(TAG, "Could not add a new contact: " + e.getMessage());
+ } catch (OperationApplicationException e) {
+ Log.d(TAG, "Could not add a new contact: " + e.getMessage());
+ }
+ }
+}
diff --git a/system/RuntimePermissions/Application/src/main/res/layout-w720dp/activity_main.xml b/system/RuntimePermissions/Application/src/main/res/layout-w720dp/activity_main.xml
new file mode 100644
index 0000000..c9a52f6
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/layout-w720dp/activity_main.xml
@@ -0,0 +1,73 @@
+<!--
+ Copyright 2013 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:orientation="horizontal"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:id="@+id/sample_main_layout">
+
+ <LinearLayout
+ android:id="@+id/sample_output"
+ android:layout_width="0px"
+ android:layout_height="match_parent"
+ android:layout_weight="1"
+ android:orientation="vertical">
+
+ <FrameLayout
+ style="@style/Widget.SampleMessageTile"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+
+ <TextView
+ style="@style/Widget.SampleMessage"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:paddingLeft="@dimen/margin_medium"
+ android:paddingRight="@dimen/margin_medium"
+ android:paddingTop="@dimen/margin_large"
+ android:paddingBottom="@dimen/margin_large"
+ android:text="@string/intro_message" />
+ </FrameLayout>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:background="@android:color/darker_gray" />
+
+ <fragment
+ android:name="com.example.android.common.logger.LogFragment"
+ android:id="@+id/log_fragment"
+ android:layout_width="match_parent"
+ android:layout_height="0px"
+ android:layout_weight="1" />
+
+ </LinearLayout>
+
+ <View
+ android:layout_width="1dp"
+ android:layout_height="match_parent"
+ android:background="@android:color/darker_gray" />
+
+ <FrameLayout
+ android:id="@+id/sample_content_fragment"
+ android:layout_weight="2"
+ android:layout_width="0px"
+ android:layout_height="match_parent" />
+
+</LinearLayout>
+
+
diff --git a/system/RuntimePermissions/Application/src/main/res/layout/activity_main.xml b/system/RuntimePermissions/Application/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..64e8322
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/layout/activity_main.xml
@@ -0,0 +1,65 @@
+<!--
+ 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.
+ -->
+<LinearLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:id="@+id/sample_main_layout">
+
+ <ViewAnimator
+ android:id="@+id/sample_output"
+ 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:paddingLeft="@dimen/horizontal_page_margin"
+ android:paddingRight="@dimen/horizontal_page_margin"
+ android:paddingTop="@dimen/vertical_page_margin"
+ android:paddingBottom="@dimen/vertical_page_margin"
+ android:text="@string/intro_message" />
+ </ScrollView>
+
+ <fragment
+ android:name="com.example.android.common.logger.LogFragment"
+ android:id="@+id/log_fragment"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent" />
+
+ </ViewAnimator>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:background="@android:color/darker_gray" />
+
+ <FrameLayout
+ android:id="@+id/sample_content_fragment"
+ android:layout_weight="2"
+ android:layout_width="match_parent"
+ android:layout_height="0px" />
+
+</LinearLayout>
+
diff --git a/system/RuntimePermissions/Application/src/main/res/layout/fragment_camera.xml b/system/RuntimePermissions/Application/src/main/res/layout/fragment_camera.xml
new file mode 100644
index 0000000..ecdc54a
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/layout/fragment_camera.xml
@@ -0,0 +1,33 @@
+<!--
+ 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.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/back"
+ android:onClick="onBackClick"
+ android:layout_gravity="center_horizontal"/>
+
+ <FrameLayout
+ android:id="@+id/camera_preview"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ android:layout_weight="1"
+ />
+</LinearLayout>
\ No newline at end of file
diff --git a/system/RuntimePermissions/Application/src/main/res/layout/fragment_camera_unavailable.xml b/system/RuntimePermissions/Application/src/main/res/layout/fragment_camera_unavailable.xml
new file mode 100644
index 0000000..200ebbc
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/layout/fragment_camera_unavailable.xml
@@ -0,0 +1,43 @@
+<!--
+ 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.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/back"
+ android:onClick="onBackClick"
+ android:layout_gravity="center_horizontal"/>
+
+ <ScrollView
+ android:layout_width="match_parent"
+ android:layout_height="fill_parent">
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingLeft="@dimen/horizontal_page_margin"
+ android:paddingRight="@dimen/horizontal_page_margin"
+ android:paddingTop="@dimen/vertical_page_margin"
+ android:paddingBottom="@dimen/vertical_page_margin"
+ android:text="@string/camera_unavailable"/>
+
+ </ScrollView>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/system/RuntimePermissions/Application/src/main/res/layout/fragment_contacts.xml b/system/RuntimePermissions/Application/src/main/res/layout/fragment_contacts.xml
new file mode 100644
index 0000000..8a70fe2
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/layout/fragment_contacts.xml
@@ -0,0 +1,54 @@
+<!--
+ 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.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:paddingLeft="@dimen/horizontal_page_margin"
+ android:paddingRight="@dimen/horizontal_page_margin"
+ android:paddingTop="@dimen/vertical_page_margin"
+ android:paddingBottom="@dimen/vertical_page_margin">
+
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/back"
+ android:onClick="onBackClick"
+ android:layout_gravity="center_horizontal"/>
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/contacts_intro"/>
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/contact_message"/>
+
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/add_contact"
+ android:id="@+id/contact_add"/>
+
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/show_contact"
+ android:id="@+id/contact_load"/>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/system/RuntimePermissions/Application/src/main/res/layout/fragment_main.xml b/system/RuntimePermissions/Application/src/main/res/layout/fragment_main.xml
new file mode 100644
index 0000000..f9bfd5f
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/layout/fragment_main.xml
@@ -0,0 +1,48 @@
+<!--
+ 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.
+-->
+
+<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:paddingLeft="@dimen/horizontal_page_margin"
+ android:paddingRight="@dimen/horizontal_page_margin"
+ android:paddingTop="@dimen/vertical_page_margin"
+ android:paddingBottom="@dimen/vertical_page_margin"
+ android:orientation="vertical"
+ tools:context=".MainActivityFragment">
+
+ <TextView
+ android:text="@string/main_introduction"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"/>
+
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/show_camera"
+ android:id="@+id/button_camera"
+ android:onClick="showCamera"/>
+
+
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/show_contacts"
+ android:id="@+id/button_contacts"
+ android:onClick="showContacts"/>
+
+</LinearLayout>
diff --git a/system/RuntimePermissions/Application/src/main/res/menu/main.xml b/system/RuntimePermissions/Application/src/main/res/menu/main.xml
new file mode 100644
index 0000000..b49c2c5
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/menu/main.xml
@@ -0,0 +1,21 @@
+<!--
+ Copyright 2013 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.
+ -->
+
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:id="@+id/menu_toggle_log"
+ android:showAsAction="always"
+ android:title="@string/sample_show_log" />
+</menu>
diff --git a/system/RuntimePermissions/Application/src/main/res/mipmap-hdpi/ic_launcher.png b/system/RuntimePermissions/Application/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..3279054
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/mipmap-hdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/Application/src/main/res/mipmap-mdpi/ic_launcher.png b/system/RuntimePermissions/Application/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..225fe42
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/mipmap-mdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/Application/src/main/res/mipmap-xhdpi/ic_launcher.png b/system/RuntimePermissions/Application/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..c129dbb
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/mipmap-xhdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/Application/src/main/res/mipmap-xxhdpi/ic_launcher.png b/system/RuntimePermissions/Application/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..b4ab118
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/mipmap-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/Application/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/system/RuntimePermissions/Application/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..99649fb
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Binary files differ
diff --git a/system/RuntimePermissions/Application/src/main/res/values/fragmentview_strings.xml b/system/RuntimePermissions/Application/src/main/res/values/fragmentview_strings.xml
new file mode 100644
index 0000000..7b9d9ec
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/values/fragmentview_strings.xml
@@ -0,0 +1,19 @@
+<!--
+ Copyright 2013 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="sample_show_log">Show Log</string>
+ <string name="sample_hide_log">Hide Log</string>
+</resources>
diff --git a/system/RuntimePermissions/Application/src/main/res/values/strings.xml b/system/RuntimePermissions/Application/src/main/res/values/strings.xml
new file mode 100644
index 0000000..941f059
--- /dev/null
+++ b/system/RuntimePermissions/Application/src/main/res/values/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <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>
+</resources>
\ No newline at end of file
diff --git a/system/RuntimePermissions/build.gradle b/system/RuntimePermissions/build.gradle
new file mode 100644
index 0000000..2b8d1ef
--- /dev/null
+++ b/system/RuntimePermissions/build.gradle
@@ -0,0 +1,11 @@
+
+// BEGIN_EXCLUDE
+import com.example.android.samples.build.SampleGenPlugin
+apply plugin: SampleGenPlugin
+
+samplegen {
+ pathToBuild "../../../../build"
+ pathToSamplesCommon "../../common"
+}
+apply from: "../../../../build/build.gradle"
+// END_EXCLUDE
diff --git a/system/RuntimePermissions/buildSrc/build.gradle b/system/RuntimePermissions/buildSrc/build.gradle
new file mode 100644
index 0000000..8c294c2
--- /dev/null
+++ b/system/RuntimePermissions/buildSrc/build.gradle
@@ -0,0 +1,15 @@
+repositories {
+ mavenCentral()
+}
+dependencies {
+ compile 'org.freemarker:freemarker:2.3.20'
+}
+
+sourceSets {
+ main {
+ groovy {
+ srcDir new File(rootDir, "../../../../../build/buildSrc/src/main/groovy")
+ }
+ }
+}
+
diff --git a/system/RuntimePermissions/gradle/wrapper/gradle-wrapper.jar b/system/RuntimePermissions/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..8c0fb64
--- /dev/null
+++ b/system/RuntimePermissions/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/system/RuntimePermissions/gradle/wrapper/gradle-wrapper.properties b/system/RuntimePermissions/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..8a27ebf
--- /dev/null
+++ b/system/RuntimePermissions/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Sun Dec 07 22:52:45 JST 2014
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
diff --git a/system/RuntimePermissions/gradlew b/system/RuntimePermissions/gradlew
new file mode 100755
index 0000000..91a7e26
--- /dev/null
+++ b/system/RuntimePermissions/gradlew
@@ -0,0 +1,164 @@
+#!/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
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched.
+if $cygwin ; then
+ [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+fi
+
+# 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\"`/" >&-
+APP_HOME="`pwd -P`"
+cd "$SAVED" >&-
+
+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"`
+
+ # 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/gradlew.bat b/system/RuntimePermissions/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/system/RuntimePermissions/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/screenshots/big_icon.png b/system/RuntimePermissions/screenshots/big_icon.png
new file mode 100644
index 0000000..706fc04
--- /dev/null
+++ b/system/RuntimePermissions/screenshots/big_icon.png
Binary files differ
diff --git a/system/RuntimePermissions/screenshots/screenshot-1.png b/system/RuntimePermissions/screenshots/screenshot-1.png
new file mode 100644
index 0000000..bb848d8
--- /dev/null
+++ b/system/RuntimePermissions/screenshots/screenshot-1.png
Binary files differ
diff --git a/system/RuntimePermissions/screenshots/screenshot-2.png b/system/RuntimePermissions/screenshots/screenshot-2.png
new file mode 100644
index 0000000..c98c212
--- /dev/null
+++ b/system/RuntimePermissions/screenshots/screenshot-2.png
Binary files differ
diff --git a/system/RuntimePermissions/settings.gradle b/system/RuntimePermissions/settings.gradle
new file mode 100644
index 0000000..9464a35
--- /dev/null
+++ b/system/RuntimePermissions/settings.gradle
@@ -0,0 +1 @@
+include 'Application'
diff --git a/system/RuntimePermissions/template-params.xml b/system/RuntimePermissions/template-params.xml
new file mode 100644
index 0000000..3baefc6
--- /dev/null
+++ b/system/RuntimePermissions/template-params.xml
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<sample>
+ <name>RuntimePermissions</name>
+ <group>System</group>
+ <package>com.example.android.system.runtimepermissions</package>
+
+ <minSdk>"MNC"</minSdk>
+ <targetSdkVersion>"MNC"</targetSdkVersion>
+ <compileSdkVersion>"android-MNC"</compileSdkVersion>
+
+
+ <dependency>com.android.support:appcompat-v7:21.+</dependency>
+
+ <strings>
+ <intro>
+ <![CDATA[
+ This sample shows runtime permissions available in the Android M and above.
+ Display the log to follow the execution.
+ If executed on an Android M device, an additional option to access contacts is shown.
+ ]]>
+ </intro>
+ </strings>
+
+ <template src="base"/>
+ <common src="logger"/>
+ <common src="activities"/>
+
+ <metadata>
+ <status>PUBLISHED</status>
+ <categories>System</categories>
+ <technologies>Android</technologies>
+ <languages>Java</languages>
+ <solutions>Mobile</solutions>
+ <level>BEGINNER</level>
+ <icon>screenshots/big_icon.png</icon>
+ <screenshots>
+ <img>screenshots/screenshot-1.png</img>
+ <img>screenshots/screenshot-2.png</img>
+ </screenshots>
+ <api_refs>
+ <android>android.app.Activity</android>
+ <android>android.Manifest.permission</android>
+ </api_refs>
+
+ <description>
+<![CDATA[
+This sample shows runtime permissions available in the Android M and above.
+It shows how to check and request permissions at runtime and how to declare permissions for M-devices
+only.
+]]>
+ </description>
+
+ <intro>
+<![CDATA[
+Android M introduced runtime permissions. Applications targeting M and above need to request their
+permissions at runtime.
+All permissions still need to be declared in the AndroidManifest. However, when accessing APIs that
+require a permission, the Activity or Fragment has to verify that the permission has been granted
+or request the missing permissions. Permissions are checked through
+Activity#requestPermissions(String[], int) and Fragment#requestPermissions(String[], int).
+Permission requests are sent through Activity#requestPermissions(String[]), and the response
+received in the callback Activity#onRequestPermissionsResult(int, permissions[], int[]).
+
+If an application targets an SDK below M, all permissions are granted at runtime and are available
+when the application is running. However, if permissions have been turned off in the system settings
+for an application targeting an SDK below M, the API will return empty or no data.
+]]>
+ </intro>
+ </metadata>
+</sample>