diff options
author | Yuichi Araki <yaraki@google.com> | 2014-10-22 18:14:06 +0900 |
---|---|---|
committer | Yuichi Araki <yaraki@google.com> | 2014-12-09 18:32:08 +0900 |
commit | 55f3d28ef0f825546843314adcca0f8b31377c54 (patch) | |
tree | 979ae794072d51ea6af8feafa52fcebd276aa872 /content/webview | |
parent | 40f9736fee53d12dfbe2bf89d98b3be8b0482324 (diff) | |
download | android-55f3d28ef0f825546843314adcca0f8b31377c54.tar.gz |
PermissionRequest: A new sample
Demonstrates how to handle PermissionRequest in WebView.
Change-Id: I1fbff5610241f34cabcc5bcb4a153871740ce28a
Diffstat (limited to 'content/webview')
29 files changed, 1396 insertions, 0 deletions
diff --git a/content/webview/PermissionRequest/Application/.gitignore b/content/webview/PermissionRequest/Application/.gitignore new file mode 100644 index 00000000..6eb878d4 --- /dev/null +++ b/content/webview/PermissionRequest/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/content/webview/PermissionRequest/Application/README-fragmentview.txt b/content/webview/PermissionRequest/Application/README-fragmentview.txt new file mode 100644 index 00000000..38d903f0 --- /dev/null +++ b/content/webview/PermissionRequest/Application/README-fragmentview.txt @@ -0,0 +1,37 @@ +<!-- + 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. +--> + +Steps to implement FragmentView template: +-in template-params.xml.ftl: + -add the following line to common imports + <common src="activities"/> + +-Add a Fragment to show behavior. In your MainActivity.java class, it will reference a Fragment + called (yourProjectName)Fragment.java. Create that file in your project, using the "main" source + folder instead of "common" or "templates". + For instance, if your package name is com.example.foo, create the file + src/main/java/com/example/foo/FooFragment.java + + +-Within this fragment, make sure that the onCreate method has the line + "setHasOptionsMenu(true);", to enable the fragment to handle menu events. + +-In order to override menu events, override onOptionsItemSelected. + +-refer to sampleSamples/fragmentViewSample for a reference implementation of a +project built on this template. + + diff --git a/content/webview/PermissionRequest/Application/README-singleview.txt b/content/webview/PermissionRequest/Application/README-singleview.txt new file mode 100644 index 00000000..0cacd467 --- /dev/null +++ b/content/webview/PermissionRequest/Application/README-singleview.txt @@ -0,0 +1,47 @@ +<#-- + 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. +--> + +Steps to implement SingleView template: +-in template-params.xml.ftl: + -add the following line to common imports + <common src="activities"/> + + -add a string for the action button's text using the element name "sample_action". + This element should be a child of <strings>: + <strings> + ... + <sample_action>ButtonText</sample_action> + ... + </strings> + + + +-Add a Fragment to handle behavior. In your MainActivity.java class, it will reference a Fragment + called (yourProjectName)Fragment.java. Create that file in your project, using the "main" source + folder instead of "common" or "templates". + For instance, if your package name is com.example.foo, create the file + src/main/java/com/example/foo/FooFragment.java + + +-Within this fragment, make sure that the onCreate method has the line + "setHasOptionsMenu(true);", to enable the fragment to handle menu events. + +-In order to override menu events, override onOptionsItemSelected. + +-refer to sampleSamples/singleViewSample for a reference implementation of a +project built on this template. + + diff --git a/content/webview/PermissionRequest/Application/proguard-project.txt b/content/webview/PermissionRequest/Application/proguard-project.txt new file mode 100644 index 00000000..0d8f171d --- /dev/null +++ b/content/webview/PermissionRequest/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/content/webview/PermissionRequest/Application/src/main/AndroidManifest.xml b/content/webview/PermissionRequest/Application/src/main/AndroidManifest.xml new file mode 100644 index 00000000..f8fd050c --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/AndroidManifest.xml @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright 2014 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.permissionrequest" + android:versionCode="1" + android:versionName="1.0"> + + <uses-permission android:name="android.permission.INTERNET"/> + <uses-permission android:name="android.permission.CAMERA"/> + + <application android:allowBackup="true" + android:label="@string/app_name" + android:icon="@drawable/ic_launcher" + 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/content/webview/PermissionRequest/Application/src/main/assets/sample.css b/content/webview/PermissionRequest/Application/src/main/assets/sample.css new file mode 100644 index 00000000..9d1364ce --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/assets/sample.css @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2014 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. + */ + +body { + text-align: center; +} + +div { + margin-bottom: 8px; +} + +button { + height: 48px; + width: 80px; + font-weight: bold; + font-size: 14pt; +} + +video { + width: 240px; + height: 180px; + transform: scaleX(-1); /* Mirror */ +} diff --git a/content/webview/PermissionRequest/Application/src/main/assets/sample.html b/content/webview/PermissionRequest/Application/src/main/assets/sample.html new file mode 100644 index 00000000..a9729a33 --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/assets/sample.html @@ -0,0 +1,31 @@ +<!DOCTYPE html> +<!-- + Copyright 2014 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. +--> +<html> +<head> + <title>sample</title> + <link rel="stylesheet" href="sample.css"> +</head> +<body> + +<div> + <button id="toggle">Start</button> +</div> +<video id="video" autoplay></video> + +<script src="sample.js"></script> +</body> +</html> diff --git a/content/webview/PermissionRequest/Application/src/main/assets/sample.js b/content/webview/PermissionRequest/Application/src/main/assets/sample.js new file mode 100644 index 00000000..e2806a0d --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/assets/sample.js @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2014 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. + */ + +(function () { + "use strict"; + + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia; + window.URL = window.URL || window.webkitURL; + + window.onload = function () { + + var video = document.querySelector('#video'), + toggle = document.querySelector('#toggle'), + stream = null; + + if (!navigator.getUserMedia) { + console.error('getUserMedia not supported'); + } + + toggle.addEventListener('click', function () { + if (null === stream) { + // This call to "getUserMedia" initiates a PermissionRequest in the WebView. + navigator.getUserMedia({ video: true }, function (s) { + stream = s; + video.src = window.URL.createObjectURL(stream); + toggle.innerText = 'Stop'; + console.log('Started'); + }, function (error) { + console.error('Error starting camera. Denied.'); + }); + } else { + stream.stop(); + stream = null; + toggle.innerText = 'Start'; + console.log('Stopped'); + } + }); + + console.log('Page loaded'); + + }; + +})(); diff --git a/content/webview/PermissionRequest/Application/src/main/java/com/example/android/permissionrequest/ConfirmationDialogFragment.java b/content/webview/PermissionRequest/Application/src/main/java/com/example/android/permissionrequest/ConfirmationDialogFragment.java new file mode 100644 index 00000000..7dae56ef --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/java/com/example/android/permissionrequest/ConfirmationDialogFragment.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2014 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.permissionrequest; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.DialogInterface; +import android.os.Bundle; +import android.support.v4.app.DialogFragment; +import android.text.TextUtils; + +/** + * Prompts the user to confirm permission request. + */ +public class ConfirmationDialogFragment extends DialogFragment { + + private static final String ARG_RESOURCES = "resources"; + + /** + * Creates a new instance of ConfirmationDialogFragment. + * + * @param resources The list of resources requested by PermissionRequeste. + * @return A new instance. + */ + public static ConfirmationDialogFragment newInstance(String[] resources) { + ConfirmationDialogFragment fragment = new ConfirmationDialogFragment(); + Bundle args = new Bundle(); + args.putStringArray(ARG_RESOURCES, resources); + fragment.setArguments(args); + return fragment; + } + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + String[] resources = getArguments().getStringArray(ARG_RESOURCES); + return new AlertDialog.Builder(getActivity()) + .setMessage(getString(R.string.confirmation, TextUtils.join("\n", resources))) + .setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + ((Listener) getParentFragment()).onConfirmation(false); + } + }) + .setPositiveButton(R.string.allow, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + ((Listener) getParentFragment()).onConfirmation(true); + } + }) + .create(); + } + + /** + * Callback for the user's response. + */ + public interface Listener { + + /** + * Called when the PermissoinRequest is allowed or denied by the user. + * + * @param allowed True if the user allowed the request. + */ + public void onConfirmation(boolean allowed); + } + +} diff --git a/content/webview/PermissionRequest/Application/src/main/java/com/example/android/permissionrequest/PermissionRequestFragment.java b/content/webview/PermissionRequest/Application/src/main/java/com/example/android/permissionrequest/PermissionRequestFragment.java new file mode 100644 index 00000000..44f1d6ec --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/java/com/example/android/permissionrequest/PermissionRequestFragment.java @@ -0,0 +1,180 @@ +/* + * Copyright (C) 2014 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.permissionrequest; + +import android.annotation.SuppressLint; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v4.app.DialogFragment; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.ConsoleMessage; +import android.webkit.PermissionRequest; +import android.webkit.WebChromeClient; +import android.webkit.WebSettings; +import android.webkit.WebView; + +import com.example.android.common.logger.Log; + +/** + * This fragment shows a {@link WebView} and loads a web app from the {@link SimpleWebServer}. + */ +public class PermissionRequestFragment extends Fragment + implements ConfirmationDialogFragment.Listener { + + private static final String TAG = PermissionRequestFragment.class.getSimpleName(); + + private static final String FRAGMENT_DIALOG = "dialog"; + + /** + * We use this web server to serve HTML files in the assets folder. This is because we cannot + * use the JavaScript method "getUserMedia" from "file:///android_assets/..." URLs. + */ + private SimpleWebServer mWebServer; + + /** + * A reference to the {@link WebView}. + */ + private WebView mWebView; + + /** + * This field stores the {@link PermissionRequest} from the web application until it is allowed + * or denied by user. + */ + private PermissionRequest mPermissionRequest; + + /** + * For testing. + */ + private ConsoleMonitor mConsoleMonitor; + + @Override + public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, + @Nullable Bundle savedInstanceState) { + return inflater.inflate(R.layout.fragment_permission_request, container, false); + } + + @Override + public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { + mWebView = (WebView) view.findViewById(R.id.web_view); + // Here, we use #mWebChromeClient with implementation for handling PermissionRequests. + mWebView.setWebChromeClient(mWebChromeClient); + configureWebSettings(mWebView.getSettings()); + } + + @Override + public void onResume() { + super.onResume(); + final int port = 8080; + mWebServer = new SimpleWebServer(port, getResources().getAssets()); + mWebServer.start(); + mWebView.loadUrl("http://localhost:" + port + "/sample.html"); + } + + @Override + public void onPause() { + mWebServer.stop(); + super.onPause(); + } + + @SuppressLint("SetJavaScriptEnabled") + private static void configureWebSettings(WebSettings settings) { + settings.setJavaScriptEnabled(true); + } + + /** + * This {@link WebChromeClient} has implementation for handling {@link PermissionRequest}. + */ + private WebChromeClient mWebChromeClient = new WebChromeClient() { + + // This method is called when the web content is requesting permission to access some + // resources. + @Override + public void onPermissionRequest(PermissionRequest request) { + Log.i(TAG, "onPermissionRequest"); + mPermissionRequest = request; + ConfirmationDialogFragment.newInstance(request.getResources()) + .show(getChildFragmentManager(), FRAGMENT_DIALOG); + } + + // This method is called when the permission request is canceled by the web content. + @Override + public void onPermissionRequestCanceled(PermissionRequest request) { + Log.i(TAG, "onPermissionRequestCanceled"); + // We dismiss the prompt UI here as the request is no longer valid. + mPermissionRequest = null; + DialogFragment fragment = (DialogFragment) getChildFragmentManager() + .findFragmentByTag(FRAGMENT_DIALOG); + if (null != fragment) { + fragment.dismiss(); + } + } + + @Override + public boolean onConsoleMessage(@NonNull ConsoleMessage message) { + switch (message.messageLevel()) { + case TIP: + Log.v(TAG, message.message()); + break; + case LOG: + Log.i(TAG, message.message()); + break; + case WARNING: + Log.w(TAG, message.message()); + break; + case ERROR: + Log.e(TAG, message.message()); + break; + case DEBUG: + Log.d(TAG, message.message()); + break; + } + if (null != mConsoleMonitor) { + mConsoleMonitor.onConsoleMessage(message); + } + return true; + } + + }; + + @Override + public void onConfirmation(boolean allowed) { + if (allowed) { + mPermissionRequest.grant(mPermissionRequest.getResources()); + Log.d(TAG, "Permission granted."); + } else { + mPermissionRequest.deny(); + Log.d(TAG, "Permission request denied."); + } + mPermissionRequest = null; + } + + public void setConsoleMonitor(ConsoleMonitor monitor) { + mConsoleMonitor = monitor; + } + + /** + * For testing. + */ + public interface ConsoleMonitor { + public void onConsoleMessage(ConsoleMessage message); + } + +} diff --git a/content/webview/PermissionRequest/Application/src/main/java/com/example/android/permissionrequest/SimpleWebServer.java b/content/webview/PermissionRequest/Application/src/main/java/com/example/android/permissionrequest/SimpleWebServer.java new file mode 100644 index 00000000..36b7c469 --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/java/com/example/android/permissionrequest/SimpleWebServer.java @@ -0,0 +1,222 @@ +/* + * Copyright (C) 2014 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.permissionrequest; + +import android.content.res.AssetManager; +import android.text.TextUtils; +import android.util.Log; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; + +/** + * Implementation of a very basic HTTP server. The contents are loaded from the assets folder. This + * server handles one request at a time. It only supports GET method. + */ +public class SimpleWebServer implements Runnable { + + private static final String TAG = "SimpleWebServer"; + + /** + * The port number we listen to + */ + private final int mPort; + + /** + * {@link android.content.res.AssetManager} for loading files to serve. + */ + private final AssetManager mAssets; + + /** + * True if the server is running. + */ + private boolean mIsRunning; + + /** + * The {@link java.net.ServerSocket} that we listen to. + */ + private ServerSocket mServerSocket; + + /** + * WebServer constructor. + */ + public SimpleWebServer(int port, AssetManager assets) { + mPort = port; + mAssets = assets; + } + + /** + * This method starts the web server listening to the specified port. + */ + public void start() { + mIsRunning = true; + new Thread(this).start(); + } + + /** + * This method stops the web server + */ + public void stop() { + try { + mIsRunning = false; + if (null != mServerSocket) { + mServerSocket.close(); + mServerSocket = null; + } + } catch (IOException e) { + Log.e(TAG, "Error closing the server socket.", e); + } + } + + @Override + public void run() { + try { + mServerSocket = new ServerSocket(mPort); + while (mIsRunning) { + Socket socket = mServerSocket.accept(); + handle(socket); + socket.close(); + } + } catch (SocketException e) { + // The server was stopped; ignore. + } catch (IOException e) { + Log.e(TAG, "Web server error.", e); + } + } + + /** + * Respond to a request from a client. + * + * @param socket The client socket. + * @throws IOException + */ + private void handle(Socket socket) throws IOException { + BufferedReader reader = null; + PrintStream output = null; + try { + String route = null; + + // Read HTTP headers and parse out the route. + reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); + String line; + while (!TextUtils.isEmpty(line = reader.readLine())) { + if (line.startsWith("GET /")) { + int start = line.indexOf('/') + 1; + int end = line.indexOf(' ', start); + route = line.substring(start, end); + break; + } + } + + // Output stream that we send the response to + output = new PrintStream(socket.getOutputStream()); + + // Prepare the content to send. + if (null == route) { + writeServerError(output); + return; + } + byte[] bytes = loadContent(route); + if (null == bytes) { + writeServerError(output); + return; + } + + // Send out the content. + output.println("HTTP/1.0 200 OK"); + output.println("Content-Type: " + detectMimeType(route)); + output.println("Content-Length: " + bytes.length); + output.println(); + output.write(bytes); + output.flush(); + } finally { + if (null != output) { + output.close(); + } + if (null != reader) { + reader.close(); + } + } + } + + /** + * Writes a server error response (HTTP/1.0 500) to the given output stream. + * + * @param output The output stream. + */ + private void writeServerError(PrintStream output) { + output.println("HTTP/1.0 500 Internal Server Error"); + output.flush(); + } + + /** + * Loads all the content of {@code fileName}. + * + * @param fileName The name of the file. + * @return The content of the file. + * @throws IOException + */ + private byte[] loadContent(String fileName) throws IOException { + InputStream input = null; + try { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + input = mAssets.open(fileName); + byte[] buffer = new byte[1024]; + int size; + while (-1 != (size = input.read(buffer))) { + output.write(buffer, 0, size); + } + output.flush(); + return output.toByteArray(); + } catch (FileNotFoundException e) { + return null; + } finally { + if (null != input) { + input.close(); + } + } + } + + /** + * Detects the MIME type from the {@code fileName}. + * + * @param fileName The name of the file. + * @return A MIME type. + */ + private String detectMimeType(String fileName) { + if (TextUtils.isEmpty(fileName)) { + return null; + } else if (fileName.endsWith(".html")) { + return "text/html"; + } else if (fileName.endsWith(".js")) { + return "application/javascript"; + } else if (fileName.endsWith(".css")) { + return "text/css"; + } else { + return "application/octet-stream"; + } + } + +} diff --git a/content/webview/PermissionRequest/Application/src/main/res/drawable-hdpi/ic_launcher.png b/content/webview/PermissionRequest/Application/src/main/res/drawable-hdpi/ic_launcher.png Binary files differnew file mode 100644 index 00000000..4dae25b0 --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/res/drawable-hdpi/ic_launcher.png diff --git a/content/webview/PermissionRequest/Application/src/main/res/drawable-mdpi/ic_launcher.png b/content/webview/PermissionRequest/Application/src/main/res/drawable-mdpi/ic_launcher.png Binary files differnew file mode 100644 index 00000000..e896d49b --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/res/drawable-mdpi/ic_launcher.png diff --git a/content/webview/PermissionRequest/Application/src/main/res/drawable-xhdpi/ic_launcher.png b/content/webview/PermissionRequest/Application/src/main/res/drawable-xhdpi/ic_launcher.png Binary files differnew file mode 100644 index 00000000..5309f55e --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/res/drawable-xhdpi/ic_launcher.png diff --git a/content/webview/PermissionRequest/Application/src/main/res/drawable-xxhdpi/ic_launcher.png b/content/webview/PermissionRequest/Application/src/main/res/drawable-xxhdpi/ic_launcher.png Binary files differnew file mode 100644 index 00000000..61b137b8 --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/res/drawable-xxhdpi/ic_launcher.png diff --git a/content/webview/PermissionRequest/Application/src/main/res/layout/fragment_permission_request.xml b/content/webview/PermissionRequest/Application/src/main/res/layout/fragment_permission_request.xml new file mode 100644 index 00000000..2e97a0ae --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/res/layout/fragment_permission_request.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2014 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"> + + <WebView + android:id="@+id/web_view" + android:layout_width="match_parent" + android:layout_height="match_parent"/> + +</LinearLayout> diff --git a/content/webview/PermissionRequest/Application/src/main/res/values/strings.xml b/content/webview/PermissionRequest/Application/src/main/res/values/strings.xml new file mode 100644 index 00000000..c3e5574d --- /dev/null +++ b/content/webview/PermissionRequest/Application/src/main/res/values/strings.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2014 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="confirmation">This web page wants to use following resources:\n\n%s</string> + <string name="allow">Allow</string> + <string name="deny">Deny</string> +</resources> diff --git a/content/webview/PermissionRequest/Application/tests/src/com/example/android/permissionrequest/test/SampleTests.java b/content/webview/PermissionRequest/Application/tests/src/com/example/android/permissionrequest/test/SampleTests.java new file mode 100644 index 00000000..a88589b3 --- /dev/null +++ b/content/webview/PermissionRequest/Application/tests/src/com/example/android/permissionrequest/test/SampleTests.java @@ -0,0 +1,196 @@ +/* +* Copyright (C) 2014 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.permissionrequest.test; + +import android.graphics.Rect; +import android.os.SystemClock; +import android.test.ActivityInstrumentationTestCase2; +import android.view.MotionEvent; +import android.view.View; +import android.webkit.ConsoleMessage; +import android.webkit.WebView; + +import com.example.android.permissionrequest.ConfirmationDialogFragment; +import com.example.android.permissionrequest.MainActivity; +import com.example.android.permissionrequest.PermissionRequestFragment; +import com.example.android.permissionrequest.R; + +import java.util.concurrent.ConcurrentLinkedQueue; + +/** + * Tests for PermissionRequest sample. + */ +public class SampleTests extends ActivityInstrumentationTestCase2<MainActivity> { + + private MainActivity mTestActivity; + private PermissionRequestFragment mTestFragment; + + public SampleTests() { + super(MainActivity.class); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + mTestActivity = getActivity(); + mTestFragment = (PermissionRequestFragment) + mTestActivity.getSupportFragmentManager().getFragments().get(1); + } + + /** + * Test if the test fixture has been set up correctly. + */ + public void testPreconditions() { + assertNotNull("mTestActivity is null", mTestActivity); + assertNotNull("mTestFragment is null", mTestFragment); + } + + public void testWebView_grantPermissionRequest() throws Throwable { + View view = mTestFragment.getView(); + assertNotNull(view); + final WebView webView = (WebView) view.findViewById(R.id.web_view); + assertNotNull(webView); + + final ConsoleMonitor monitor = new ConsoleMonitor(); + mTestFragment.setConsoleMonitor(monitor); + + // Click the "Start" button + assertTrue(monitor.waitForKeyword("Page loaded", 2000)); + clickToggle(webView); + + // Wait for the dialog + ConfirmationDialogFragment dialogFragment = waitForDialog(); + assertNotNull(dialogFragment); + + // Click "Allow" + monitor.reset(); + clickDialogButton(dialogFragment, android.R.id.button1); + + assertTrue(monitor.waitForKeyword("Started", 2000)); + + // Click the "Stop" button + monitor.reset(); + clickToggle(webView); + assertTrue(monitor.waitForKeyword("Stopped", 2000)); + + // Click the "Start" button + monitor.reset(); + clickToggle(webView); + + // Wait for the dialog + dialogFragment = waitForDialog(); + assertNotNull(dialogFragment); + + // Click "Deny" + monitor.reset(); + clickDialogButton(dialogFragment, android.R.id.button2); + assertTrue(monitor.waitForKeyword("Denied", 2000)); + } + + /** + * Click the Start/Stop button. + * + * @param webView The {@link WebView}. + * @throws Throwable + */ + private void clickToggle(final WebView webView) throws Throwable { + runTestOnUiThread(new Runnable() { + @Override + public void run() { + Rect rect = new Rect(); + webView.getHitRect(rect); + int x = rect.width() / 2; + int y = 100; + MotionEvent event = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_DOWN, x, y, 0); + webView.dispatchTouchEvent(event); + event = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_UP, x, y, 0); + webView.dispatchTouchEvent(event); + } + }); + } + + /** + * Wait for the dialog for 2 seconds (100 ms * 20 trials). + * + * @return The dialog. + * @throws InterruptedException + */ + private ConfirmationDialogFragment waitForDialog() throws InterruptedException { + int count = 20; + ConfirmationDialogFragment dialog = null; + while (0 < count) { + dialog = (ConfirmationDialogFragment) mTestFragment.getChildFragmentManager() + .findFragmentByTag("dialog"); + if (null != dialog) { + break; + } + Thread.sleep(100); + --count; + } + return dialog; + } + + /** + * Press the specified button on the dialog. + * + * @param dialogFragment The dialog. + * @param buttonId The resource ID of the button to press. + * @throws Throwable + */ + private void clickDialogButton(final ConfirmationDialogFragment dialogFragment, + final int buttonId) throws Throwable { + runTestOnUiThread(new Runnable() { + @Override + public void run() { + dialogFragment.getDialog().findViewById(buttonId).performClick(); + assertFalse(dialogFragment.isVisible()); + } + }); + } + + private class ConsoleMonitor implements PermissionRequestFragment.ConsoleMonitor { + + private final ConcurrentLinkedQueue<String> mMessages = new ConcurrentLinkedQueue<String>(); + + @Override + public void onConsoleMessage(ConsoleMessage message) { + mMessages.offer(message.message()); + } + + public boolean waitForKeyword(String keyword, long timeoutMs) throws InterruptedException { + long time = 0; + while (time < timeoutMs) { + String message; + while (null != (message = mMessages.poll())) { + if (message.contains(keyword)) { + return true; + } + } + Thread.sleep(100); + time += 100; + } + return false; + } + + public void reset() { + mMessages.clear(); + } + + } + +} diff --git a/content/webview/PermissionRequest/build.gradle b/content/webview/PermissionRequest/build.gradle new file mode 100644 index 00000000..18f393f9 --- /dev/null +++ b/content/webview/PermissionRequest/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/content/webview/PermissionRequest/buildSrc/build.gradle b/content/webview/PermissionRequest/buildSrc/build.gradle new file mode 100644 index 00000000..7cebf71c --- /dev/null +++ b/content/webview/PermissionRequest/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/content/webview/PermissionRequest/gradle/wrapper/gradle-wrapper.jar b/content/webview/PermissionRequest/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 00000000..8c0fb64a --- /dev/null +++ b/content/webview/PermissionRequest/gradle/wrapper/gradle-wrapper.jar diff --git a/content/webview/PermissionRequest/gradle/wrapper/gradle-wrapper.properties b/content/webview/PermissionRequest/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..4eda7c51 --- /dev/null +++ b/content/webview/PermissionRequest/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Dec 09 18:05:08 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/content/webview/PermissionRequest/gradlew b/content/webview/PermissionRequest/gradlew new file mode 100755 index 00000000..91a7e269 --- /dev/null +++ b/content/webview/PermissionRequest/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/content/webview/PermissionRequest/gradlew.bat b/content/webview/PermissionRequest/gradlew.bat new file mode 100644 index 00000000..aec99730 --- /dev/null +++ b/content/webview/PermissionRequest/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/content/webview/PermissionRequest/screenshots/icon_web.png b/content/webview/PermissionRequest/screenshots/icon_web.png Binary files differnew file mode 100644 index 00000000..4a8c2f10 --- /dev/null +++ b/content/webview/PermissionRequest/screenshots/icon_web.png diff --git a/content/webview/PermissionRequest/screenshots/image1.png b/content/webview/PermissionRequest/screenshots/image1.png Binary files differnew file mode 100644 index 00000000..9ce9fc85 --- /dev/null +++ b/content/webview/PermissionRequest/screenshots/image1.png diff --git a/content/webview/PermissionRequest/screenshots/image2.png b/content/webview/PermissionRequest/screenshots/image2.png Binary files differnew file mode 100644 index 00000000..e919bd1a --- /dev/null +++ b/content/webview/PermissionRequest/screenshots/image2.png diff --git a/content/webview/PermissionRequest/settings.gradle b/content/webview/PermissionRequest/settings.gradle new file mode 100644 index 00000000..9464a359 --- /dev/null +++ b/content/webview/PermissionRequest/settings.gradle @@ -0,0 +1 @@ +include 'Application' diff --git a/content/webview/PermissionRequest/template-params.xml b/content/webview/PermissionRequest/template-params.xml new file mode 100644 index 00000000..04022703 --- /dev/null +++ b/content/webview/PermissionRequest/template-params.xml @@ -0,0 +1,102 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright 2014 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>PermissionRequest</name> + <group>Content</group> + <package>com.example.android.permissionrequest</package> + + <minSdk>21</minSdk> + + <strings> + <intro> + <![CDATA[ + This sample shows how to handle PermissionRequest coming from web apps inside of a + WebView. + ]]> + </intro> + </strings> + + <template src="base"/> + <template src="FragmentView"/> + <common src="logger"/> + <common src="activities"/> + + <metadata> + <status>PUBLISHED</status> + <categories>Content</categories> + <technologies>Android</technologies> + <languages>Java</languages> + <solutions>Mobile</solutions> + <level>INTERMEDIATE</level> + <icon>screenshots/icon_web.png</icon> + <screenshots> + <img>screenshots/main.png</img> + </screenshots> + <api_refs> + <android>android.webkit.PermissionRequest</android> + <android>android.webkit.WebView</android> + <android>android.webkit.WebChromeClient</android> + </api_refs> + + <description> +<![CDATA[ +This sample demonstrates how to use the PermissionRequest API to +securely provide access to restricted system features (such as a +camera or microphone) from within a WebView. In this example, a dialog +is created to allow users to explicitly approve or reject each +request. +]]> + </description> + + <intro> +<![CDATA[ +PermissionRequest can be used by setting up a custom WebChromeClient. + +```java +mWebView.setWebChromeClient(mWebChromeClient); +``` + +In you WebChromeClient implementation, you need to override +[onPermissionRequest][1]. This method is called when the web content +is requesting permission to access some resources, providing an +opportunity to approve or reject the request. In this implementation, +we display a dialog to allow the user to approve or reject any +request. In other applications, you may want to implement a whitelist +of allowed APIs. Also, override [onPermissionRequestCanceled][2] for +handling cancellation of the PermissionRequest by the web content. + +When the user confirms or denies the request, you can respond back to +the web content by [grant][3] or [deny][4] respectively. + +```java +mPermissionRequest.grant(mPermissionRequest.getResources()); +``` + +This sample provides the web content from the assets folder in the +app. Since WebView is not allowed to use getUserMedia from a "file://" +URL, the app uses the SimpleWebServer class to provide the content via +"http://localhost". + +[1]: http://developer.android.com/reference/android/webkit/WebChromeClient.html#onPermissionRequest(android.webkit.PermissionRequest) +[2]: http://developer.android.com/reference/android/webkit/WebChromeClient.html#onPermissionRequestCanceled(android.webkit.PermissionRequest) +[3]: http://developer.android.com/reference/android/webkit/PermissionRequest.html#grant(java.lang.String[]) +[4]: http://developer.android.com/reference/android/webkit/PermissionRequest.html#deny() +]]> + </intro> + </metadata> + +</sample> |