From 3731ef5f52af23b9f95a8afbf8102f13a0382b94 Mon Sep 17 00:00:00 2001 From: Lorenzo Pichilli Date: Sat, 23 May 2020 19:33:54 +0200 Subject: [PATCH] updated README.md, fix #275, fix #353 --- CHANGELOG.md | 3 +- README.md | 33 ++ .../InAppBrowser/InAppBrowserActivity.java | 4 + .../InAppWebView/FlutterWebView.java | 7 + .../InAppWebViewChromeClient.java | 424 ++++++++++++++---- .../InAppWebViewFlutterPlugin.java | 6 +- android/src/main/res/xml/provider_paths.xml | 4 + example/.flutter-plugins-dependencies | 2 +- .../android/app/src/main/AndroidManifest.xml | 10 + .../flutterwebviewexample/MainActivity.java | 8 +- example/lib/main.dart | 4 +- example/pubspec.yaml | 2 +- lib/src/headless_in_app_webview.dart | 8 + lib/src/in_app_browser.dart | 6 + lib/src/in_app_webview.dart | 8 + lib/src/in_app_webview_controller.dart | 14 + lib/src/webview.dart | 8 + 17 files changed, 461 insertions(+), 90 deletions(-) create mode 100644 android/src/main/res/xml/provider_paths.xml diff --git a/CHANGELOG.md b/CHANGELOG.md index 92d091208..8206624c6 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ - Updated Android context menu workaround - Calling `onCreateContextMenu` event on iOS also when the context menu is disabled in order to have the same effect as Android - Added Android keyboard workaround to hide the keyboard when clicking other HTML elements, losing the focus on the previous input -- Added `onEnterFullscreen`, `onExitFullscreen` webview events +- Added `onEnterFullscreen`, `onExitFullscreen` webview events [#275](https://github.com/pichillilorenzo/flutter_inappwebview/issues/275) +- Added Android support to use camera on HTML inputs that requires it, such as `` [#353](https://github.com/pichillilorenzo/flutter_inappwebview/issues/353) - Fixed `Print preview is not working? java.lang.IllegalStateException: Can print only from an activity` [#128](https://github.com/pichillilorenzo/flutter_inappwebview/issues/128) - Fixed `onJsAlert`, `onJsConfirm`, `onJsPrompt` for `InAppBrowser` on Android - Fixed `InAppBrowser.openWithSystemBrowser crash on iOS` [#358](https://github.com/pichillilorenzo/flutter_inappwebview/issues/358) diff --git a/README.md b/README.md index 5bc64d16b..914678d47 100755 --- a/README.md +++ b/README.md @@ -121,6 +121,37 @@ Other useful `Info.plist` properties are: * `NSAllowsLocalNetworking`: A Boolean value indicating whether to allow loading of local resources ([Official wiki](https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsallowslocalnetworking)); * `NSAllowsArbitraryLoadsInWebContent`: A Boolean value indicating whether all App Transport Security restrictions are disabled for requests made from web views ([Official wiki](https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsallowsarbitraryloadsinwebcontent)). +### How to enable the usage of camera for HTML inputs such as `` + +In order to be able to use camera, for example, for taking images through `` HTML tag, you need to ask camera permission. +To ask camera permission, you can simply use the [permission_handler](https://pub.dev/packages/permission_handler) plugin! + +Example: +```dart +import 'package:permission_handler/permission_handler.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await Permission.camera.request(); + + runApp(MyApp()); +} +``` + +On **Android**, you need to add some additional configurations. +Add the following codes inside the `` tag of your `android/app/src/main/AndroidManifest.xml`: +```xml + + + +``` + ## Getting Started For help getting started with Flutter, view our online @@ -566,6 +597,8 @@ Event names that starts with `android` or `ios` are events platform-specific. * `shouldInterceptFetchRequest`: Event fired when a request is sent to a server through [Fetch API](https://developer.mozilla.org/it/docs/Web/API/Fetch_API) (to use this event, the `useShouldInterceptFetchRequest` option must be `true`). * `onPrint`: Event fired when `window.print()` is called from JavaScript side. * `onLongPressHitTestResult`: Event fired when an HTML element of the webview has been clicked and held. +* `onEnterFullscreen`: Event fired when the current page has entered full screen mode. +* `onExitFullscreen`: Event fired when the current page has exited full screen mode. * `androidOnSafeBrowsingHit`: Event fired when the webview notifies that a loading URL has been flagged by Safe Browsing (available only on Android). * `androidOnPermissionRequest`: Event fired when the webview is requesting permission to access the specified resources and the permission currently isn't granted or denied (available only on Android). * `androidOnGeolocationPermissionsShowPrompt`: Event that notifies the host application that web content from the specified origin is attempting to use the Geolocation API, but no permission state is currently set for that origin (available only on Android). diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserActivity.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserActivity.java index 4f7a78075..c4639daa1 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserActivity.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserActivity.java @@ -57,6 +57,10 @@ public class InAppBrowserActivity extends AppCompatActivity implements MethodCha protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + if (savedInstanceState != null) { + return; + } + Bundle b = getIntent().getExtras(); uuid = b.getString("uuid"); diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/FlutterWebView.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/FlutterWebView.java index 6cb537c34..91cb1a144 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/FlutterWebView.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/FlutterWebView.java @@ -54,6 +54,13 @@ public FlutterWebView(BinaryMessenger messenger, final Context context, Object i InAppWebViewOptions options = new InAppWebViewOptions(); options.parse(initialOptions); + if (Shared.activity == null) { + Log.e(LOG_TAG, "\n\n\nERROR: Shared.activity is null!!!\n\n" + + "You need to upgrade your Flutter project to use the new Java Embedding API:\n\n" + + "- Take a look at the \"IMPORTANT Note for Android\" section here: https://github.com/pichillilorenzo/flutter_inappwebview#important-note-for-android\n" + + "- See the official wiki here: https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects\n\n\n"); + } + webView = new InAppWebView(Shared.activity, this, id, options, contextMenu, containerView); displayListenerProxy.onPostWebViewInitialization(displayManager); diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebViewChromeClient.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebViewChromeClient.java index c1f2c5aa7..a3d8eb5fa 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebViewChromeClient.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebViewChromeClient.java @@ -1,20 +1,21 @@ package com.pichillilorenzo.flutter_inappwebview.InAppWebView; -import android.annotation.SuppressLint; +import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; -import android.content.pm.ActivityInfo; +import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Build; -import android.os.Handler; -import android.os.Looper; +import android.os.Environment; import android.os.Message; +import android.os.Parcelable; +import android.provider.MediaStore; import android.util.Log; import android.view.Gravity; import android.view.View; @@ -24,6 +25,7 @@ import android.webkit.GeolocationPermissions; import android.webkit.JsPromptResult; import android.webkit.JsResult; +import android.webkit.MimeTypeMap; import android.webkit.PermissionRequest; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; @@ -33,13 +35,18 @@ import android.widget.FrameLayout; import android.widget.LinearLayout; +import androidx.annotation.RequiresApi; import androidx.appcompat.app.AlertDialog; +import androidx.core.content.ContextCompat; +import androidx.core.content.FileProvider; import com.pichillilorenzo.flutter_inappwebview.InAppBrowser.InAppBrowserActivity; import com.pichillilorenzo.flutter_inappwebview.InAppWebViewFlutterPlugin; import com.pichillilorenzo.flutter_inappwebview.R; import com.pichillilorenzo.flutter_inappwebview.Shared; +import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -49,7 +56,6 @@ import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.PluginRegistry; -import static android.app.Activity.RESULT_CANCELED; import static android.app.Activity.RESULT_OK; public class InAppWebViewChromeClient extends WebChromeClient implements PluginRegistry.ActivityResultListener { @@ -58,8 +64,31 @@ public class InAppWebViewChromeClient extends WebChromeClient implements PluginR private FlutterWebView flutterWebView; private InAppBrowserActivity inAppBrowserActivity; public MethodChannel channel; - private ValueCallback mUploadMessage; - private final static int FILECHOOSER_RESULTCODE = 1; + + private static final String fileProviderAuthorityExtension = "flutter_inappwebview.fileprovider"; + + private static final int PICKER = 1; + private static final int PICKER_LEGACY = 3; + final String DEFAULT_MIME_TYPES = "*/*"; + private Uri outputFileUri; + + protected static final FrameLayout.LayoutParams FULLSCREEN_LAYOUT_PARAMS = new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER); + + @RequiresApi(api = Build.VERSION_CODES.KITKAT) + protected static final int FULLSCREEN_SYSTEM_UI_VISIBILITY_KITKAT = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_LAYOUT_STABLE | + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_FULLSCREEN | + View.SYSTEM_UI_FLAG_IMMERSIVE | + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; + + protected static final int FULLSCREEN_SYSTEM_UI_VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_LAYOUT_STABLE | + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_FULLSCREEN; private View mCustomView; private WebChromeClient.CustomViewCallback mCustomViewCallback; @@ -91,13 +120,15 @@ public Bitmap getDefaultVideoPoster() { @Override public void onHideCustomView() { Activity activity = inAppBrowserActivity != null ? inAppBrowserActivity : Shared.activity; - View decorView = activity.getWindow().getDecorView(); + + View decorView = getRootView(); ((FrameLayout) decorView).removeView(this.mCustomView); this.mCustomView = null; decorView.setSystemUiVisibility(this.mOriginalSystemUiVisibility); activity.setRequestedOrientation(this.mOriginalOrientation); this.mCustomViewCallback.onCustomViewHidden(); this.mCustomViewCallback = null; + activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); Map obj = new HashMap<>(); if (inAppBrowserActivity != null) @@ -113,35 +144,21 @@ public void onShowCustomView(final View paramView, final CustomViewCallback para } Activity activity = inAppBrowserActivity != null ? inAppBrowserActivity : Shared.activity; - final View decorView = activity.getWindow().getDecorView(); + + View decorView = getRootView(); this.mCustomView = paramView; this.mOriginalSystemUiVisibility = decorView.getSystemUiVisibility(); this.mOriginalOrientation = activity.getRequestedOrientation(); this.mCustomViewCallback = paramCustomViewCallback; - this.mCustomView.setBackgroundColor(Color.parseColor("#000000")); - ((FrameLayout) decorView).addView(this.mCustomView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + this.mCustomView.setBackgroundColor(Color.BLACK); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - decorView.setSystemUiVisibility( - View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY - // Set the content to appear under the system bars so that the - // content doesn't resize when the system bars hide and show. - | View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - // Hide the nav bar and status bar - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN); + decorView.setSystemUiVisibility(FULLSCREEN_SYSTEM_UI_VISIBILITY_KITKAT); } else { - decorView.setSystemUiVisibility( - // Set the content to appear under the system bars so that the - // content doesn't resize when the system bars hide and show. - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - // Hide the nav bar and status bar - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN); + decorView.setSystemUiVisibility(FULLSCREEN_SYSTEM_UI_VISIBILITY); } + activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); + ((FrameLayout) decorView).addView(this.mCustomView, FULLSCREEN_LAYOUT_PARAMS); Map obj = new HashMap<>(); if (inAppBrowserActivity != null) @@ -577,68 +594,321 @@ public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } - // For Android 3.0+ - public void openFileChooser(ValueCallback uploadMsg) { - mUploadMessage = uploadMsg; - Intent i = new Intent(Intent.ACTION_GET_CONTENT); - i.addCategory(Intent.CATEGORY_OPENABLE); - i.setType("image/*"); + protected ViewGroup getRootView() { Activity activity = inAppBrowserActivity != null ? inAppBrowserActivity : Shared.activity; - activity.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE); + return (ViewGroup) activity.findViewById(android.R.id.content); } - // For Android 3.0+ - public void openFileChooser(ValueCallback uploadMsg, String acceptType) { - mUploadMessage = uploadMsg; - Intent i = new Intent(Intent.ACTION_GET_CONTENT); - i.addCategory(Intent.CATEGORY_OPENABLE); - i.setType("*/*"); + protected void openFileChooser(ValueCallback filePathCallback, String acceptType) { + startPhotoPickerIntent(filePathCallback, acceptType); + } + + protected void openFileChooser(ValueCallback filePathCallback) { + startPhotoPickerIntent(filePathCallback, ""); + } + + protected void openFileChooser(ValueCallback filePathCallback, String acceptType, String capture) { + startPhotoPickerIntent(filePathCallback, acceptType); + } + + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + @Override + public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) { + String[] acceptTypes = fileChooserParams.getAcceptTypes(); + boolean allowMultiple = fileChooserParams.getMode() == WebChromeClient.FileChooserParams.MODE_OPEN_MULTIPLE; + Intent intent = fileChooserParams.createIntent(); + return startPhotoPickerIntent(filePathCallback, intent, acceptTypes, allowMultiple); + } + + @Override + public boolean onActivityResult(int requestCode, int resultCode, Intent data) { + if (InAppWebViewFlutterPlugin.filePathCallback == null && InAppWebViewFlutterPlugin.filePathCallbackLegacy == null) { + return true; + } + + // based off of which button was pressed, we get an activity result and a file + // the camera activity doesn't properly return the filename* (I think?) so we use + // this filename instead + switch (requestCode) { + case PICKER: + if (resultCode != RESULT_OK) { + if (InAppWebViewFlutterPlugin.filePathCallback != null) { + InAppWebViewFlutterPlugin.filePathCallback.onReceiveValue(null); + } + } else { + Uri result[] = this.getSelectedFiles(data, resultCode); + if (result != null) { + InAppWebViewFlutterPlugin.filePathCallback.onReceiveValue(result); + } else { + InAppWebViewFlutterPlugin.filePathCallback.onReceiveValue(new Uri[]{outputFileUri}); + } + } + break; + case PICKER_LEGACY: + Uri result = resultCode != Activity.RESULT_OK ? null : data == null ? outputFileUri : data.getData(); + InAppWebViewFlutterPlugin.filePathCallbackLegacy.onReceiveValue(result); + break; + + } + InAppWebViewFlutterPlugin.filePathCallback = null; + InAppWebViewFlutterPlugin.filePathCallbackLegacy = null; + outputFileUri = null; + + return true; + } + + private Uri[] getSelectedFiles(Intent data, int resultCode) { + if (data == null) { + return null; + } + + // we have one file selected + if (data.getData() != null) { + if (resultCode == RESULT_OK && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + return WebChromeClient.FileChooserParams.parseResult(resultCode, data); + } else { + return null; + } + } + + // we have multiple files selected + if (data.getClipData() != null) { + final int numSelectedFiles = data.getClipData().getItemCount(); + Uri[] result = new Uri[numSelectedFiles]; + for (int i = 0; i < numSelectedFiles; i++) { + result[i] = data.getClipData().getItemAt(i).getUri(); + } + return result; + } + return null; + } + + public void startPhotoPickerIntent(ValueCallback filePathCallback, String acceptType) { + InAppWebViewFlutterPlugin.filePathCallbackLegacy = filePathCallback; + + Intent fileChooserIntent = getFileChooserIntent(acceptType); + Intent chooserIntent = Intent.createChooser(fileChooserIntent, ""); + + ArrayList extraIntents = new ArrayList<>(); + if (acceptsImages(acceptType)) { + extraIntents.add(getPhotoIntent()); + } + if (acceptsVideo(acceptType)) { + extraIntents.add(getVideoIntent()); + } + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents.toArray(new Parcelable[]{})); + + Activity activity = inAppBrowserActivity != null ? inAppBrowserActivity : Shared.activity; + if (chooserIntent.resolveActivity(activity.getPackageManager()) != null) { + activity.startActivityForResult(chooserIntent, PICKER_LEGACY); + } else { + Log.d(LOG_TAG, "there is no Activity to handle this Intent"); + } + } + + @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) + public boolean startPhotoPickerIntent(final ValueCallback callback, final Intent intent, final String[] acceptTypes, final boolean allowMultiple) { + InAppWebViewFlutterPlugin.filePathCallback = callback; + + ArrayList extraIntents = new ArrayList<>(); + if (!needsCameraPermission()) { + if (acceptsImages(acceptTypes)) { + extraIntents.add(getPhotoIntent()); + } + if (acceptsVideo(acceptTypes)) { + extraIntents.add(getVideoIntent()); + } + } + + Intent fileSelectionIntent = getFileChooserIntent(acceptTypes, allowMultiple); + + Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); + chooserIntent.putExtra(Intent.EXTRA_INTENT, fileSelectionIntent); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents.toArray(new Parcelable[]{})); + Activity activity = inAppBrowserActivity != null ? inAppBrowserActivity : Shared.activity; - activity.startActivityForResult( - Intent.createChooser(i, "File Browser"), - FILECHOOSER_RESULTCODE); + if (chooserIntent.resolveActivity(activity.getPackageManager()) != null) { + activity.startActivityForResult(chooserIntent, PICKER); + } else { + Log.d(LOG_TAG, "there is no Activity to handle this Intent"); + } + + return true; } - // For Android 4.1 - public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) { - mUploadMessage = uploadMsg; - Intent i = new Intent(Intent.ACTION_GET_CONTENT); - i.addCategory(Intent.CATEGORY_OPENABLE); - i.setType("image/*"); + protected boolean needsCameraPermission() { + boolean needed = false; + Activity activity = inAppBrowserActivity != null ? inAppBrowserActivity : Shared.activity; - activity.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE); + PackageManager packageManager = activity.getPackageManager(); + try { + String[] requestedPermissions = packageManager.getPackageInfo(activity.getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS).requestedPermissions; + if (Arrays.asList(requestedPermissions).contains(Manifest.permission.CAMERA) + && ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { + needed = true; + } + } catch (PackageManager.NameNotFoundException e) { + needed = true; + } + + return needed; } - // For Android 5.0+ - public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) { - InAppWebViewFlutterPlugin.uploadMessageArray = filePathCallback; + private Intent getPhotoIntent() { + Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); + outputFileUri = getOutputUri(MediaStore.ACTION_IMAGE_CAPTURE); + intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); + return intent; + } + + private Intent getVideoIntent() { + Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); + outputFileUri = getOutputUri(MediaStore.ACTION_VIDEO_CAPTURE); + intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); + return intent; + } + + private Intent getFileChooserIntent(String acceptTypes) { + String _acceptTypes = acceptTypes; + if (acceptTypes.isEmpty()) { + _acceptTypes = DEFAULT_MIME_TYPES; + } + if (acceptTypes.matches("\\.\\w+")) { + _acceptTypes = getMimeTypeFromExtension(acceptTypes.replace(".", "")); + } + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType(_acceptTypes); + return intent; + } + + @RequiresApi(api = Build.VERSION_CODES.KITKAT) + private Intent getFileChooserIntent(String[] acceptTypes, boolean allowMultiple) { + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType("*/*"); + intent.putExtra(Intent.EXTRA_MIME_TYPES, getAcceptedMimeType(acceptTypes)); + intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, allowMultiple); + return intent; + } + + private Boolean acceptsImages(String types) { + String mimeType = types; + if (types.matches("\\.\\w+")) { + mimeType = getMimeTypeFromExtension(types.replace(".", "")); + } + return mimeType.isEmpty() || mimeType.toLowerCase().contains("image"); + } + + private Boolean acceptsImages(String[] types) { + String[] mimeTypes = getAcceptedMimeType(types); + return isArrayEmpty(mimeTypes) || arrayContainsString(mimeTypes, "image"); + } + + private Boolean acceptsVideo(String types) { + String mimeType = types; + if (types.matches("\\.\\w+")) { + mimeType = getMimeTypeFromExtension(types.replace(".", "")); + } + return mimeType.isEmpty() || mimeType.toLowerCase().contains("video"); + } + + private Boolean acceptsVideo(String[] types) { + String[] mimeTypes = getAcceptedMimeType(types); + return isArrayEmpty(mimeTypes) || arrayContainsString(mimeTypes, "video"); + } + + private Boolean arrayContainsString(String[] array, String pattern) { + for (String content : array) { + if (content.contains(pattern)) { + return true; + } + } + return false; + } + + private String[] getAcceptedMimeType(String[] types) { + if (isArrayEmpty(types)) { + return new String[]{DEFAULT_MIME_TYPES}; + } + String[] mimeTypes = new String[types.length]; + for (int i = 0; i < types.length; i++) { + String t = types[i]; + // convert file extensions to mime types + if (t.matches("\\.\\w+")) { + String mimeType = getMimeTypeFromExtension(t.replace(".", "")); + mimeTypes[i] = mimeType; + } else { + mimeTypes[i] = t; + } + } + return mimeTypes; + } + + private String getMimeTypeFromExtension(String extension) { + String type = null; + if (extension != null) { + type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); + } + return type; + } + + private Uri getOutputUri(String intentType) { + File capturedFile = null; try { - Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); - contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); - contentSelectionIntent.setType("*/*"); - Intent[] intentArray; - intentArray = new Intent[0]; - - Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); - chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); - chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); - Activity activity = inAppBrowserActivity != null ? inAppBrowserActivity : Shared.activity; - activity.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE); - } catch (ActivityNotFoundException e) { + capturedFile = getCapturedFile(intentType); + } catch (IOException e) { + Log.e(LOG_TAG, "Error occurred while creating the File", e); e.printStackTrace(); - return false; } - return true; + + // for versions below 6.0 (23) we use the old File creation & permissions model + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { + return Uri.fromFile(capturedFile); + } + + Activity activity = inAppBrowserActivity != null ? inAppBrowserActivity : Shared.activity; + // for versions 6.0+ (23) we use the FileProvider to avoid runtime permissions + String packageName = activity.getApplicationContext().getPackageName(); + return FileProvider.getUriForFile(activity.getApplicationContext(), packageName + "." + fileProviderAuthorityExtension, capturedFile); } - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - @Override - public boolean onActivityResult(int requestCode, int resultCode, Intent data) { - if (requestCode == FILECHOOSER_RESULTCODE && (resultCode == RESULT_OK || resultCode == RESULT_CANCELED)) { - InAppWebViewFlutterPlugin.uploadMessageArray.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data)); + private File getCapturedFile(String intentType) throws IOException { + String prefix = ""; + String suffix = ""; + String dir = ""; + String filename = ""; + + if (intentType.equals(MediaStore.ACTION_IMAGE_CAPTURE)) { + prefix = "image-"; + suffix = ".jpg"; + dir = Environment.DIRECTORY_PICTURES; + } else if (intentType.equals(MediaStore.ACTION_VIDEO_CAPTURE)) { + prefix = "video-"; + suffix = ".mp4"; + dir = Environment.DIRECTORY_MOVIES; } - return true; + + filename = prefix + String.valueOf(System.currentTimeMillis()) + suffix; + + // for versions below 6.0 (23) we use the old File creation & permissions model + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { + // only this Directory works on all tested Android versions + // ctx.getExternalFilesDir(dir) was failing on Android 5.0 (sdk 21) + File storageDir = Environment.getExternalStoragePublicDirectory(dir); + return new File(storageDir, filename); + } + + Activity activity = inAppBrowserActivity != null ? inAppBrowserActivity : Shared.activity; + File storageDir = activity.getApplicationContext().getExternalFilesDir(null); + return File.createTempFile(filename, suffix, storageDir); + } + + private Boolean isArrayEmpty(String[] arr) { + // when our array returned from getAcceptTypes() has no values set from the webview + // i.e. , without any "accept" attr + // will be an array with one empty string element, afaik + return arr.length == 0 || (arr.length == 1 && arr[0].length() == 0); } @Override diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebViewFlutterPlugin.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebViewFlutterPlugin.java index 2a13a35c4..6708e625e 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebViewFlutterPlugin.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebViewFlutterPlugin.java @@ -28,7 +28,8 @@ public class InAppWebViewFlutterPlugin implements FlutterPlugin, ActivityAware { public static MyCookieManager myCookieManager; public static CredentialDatabaseHandler credentialDatabaseHandler; public static MyWebStorage myWebStorage; - public static ValueCallback uploadMessageArray; + public static ValueCallback filePathCallbackLegacy; + public static ValueCallback filePathCallback; public InAppWebViewFlutterPlugin() {} @@ -95,7 +96,8 @@ public void onDetachedFromEngine(FlutterPluginBinding binding) { inAppWebViewStatic.dispose(); inAppWebViewStatic = null; } - uploadMessageArray = null; + filePathCallbackLegacy = null; + filePathCallback = null; } @Override diff --git a/android/src/main/res/xml/provider_paths.xml b/android/src/main/res/xml/provider_paths.xml new file mode 100644 index 000000000..ffa74ab56 --- /dev/null +++ b/android/src/main/res/xml/provider_paths.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/example/.flutter-plugins-dependencies b/example/.flutter-plugins-dependencies index d8ce85ed7..342e43aee 100755 --- a/example/.flutter-plugins-dependencies +++ b/example/.flutter-plugins-dependencies @@ -1 +1 @@ -{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"e2e","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/e2e-0.2.4+4/","dependencies":[]},{"name":"flutter_inappwebview","path":"/Users/lorenzopichilli/Desktop/flutter_inappwebview/","dependencies":[]}],"android":[{"name":"e2e","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/e2e-0.2.4+4/","dependencies":[]},{"name":"flutter_inappwebview","path":"/Users/lorenzopichilli/Desktop/flutter_inappwebview/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"e2e","dependencies":[]},{"name":"flutter_inappwebview","dependencies":[]}],"date_created":"2020-05-23 12:13:45.779062","version":"1.17.1"} \ No newline at end of file +{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"e2e","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/e2e-0.2.4+4/","dependencies":[]},{"name":"flutter_inappwebview","path":"/Users/lorenzopichilli/Desktop/flutter_inappwebview/","dependencies":[]},{"name":"permission_handler","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-5.0.0+hotfix.6/","dependencies":[]}],"android":[{"name":"e2e","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/e2e-0.2.4+4/","dependencies":[]},{"name":"flutter_inappwebview","path":"/Users/lorenzopichilli/Desktop/flutter_inappwebview/","dependencies":[]},{"name":"permission_handler","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-5.0.0+hotfix.6/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"e2e","dependencies":[]},{"name":"flutter_inappwebview","dependencies":[]},{"name":"permission_handler","dependencies":[]}],"date_created":"2020-05-23 18:32:59.790460","version":"1.17.1"} \ No newline at end of file diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml index da52e7dbb..7907dd038 100755 --- a/example/android/app/src/main/AndroidManifest.xml +++ b/example/android/app/src/main/AndroidManifest.xml @@ -65,6 +65,16 @@ + + + + diff --git a/example/android/app/src/main/java/com/pichillilorenzo/flutterwebviewexample/MainActivity.java b/example/android/app/src/main/java/com/pichillilorenzo/flutterwebviewexample/MainActivity.java index ee8a96cb9..253cc9119 100755 --- a/example/android/app/src/main/java/com/pichillilorenzo/flutterwebviewexample/MainActivity.java +++ b/example/android/app/src/main/java/com/pichillilorenzo/flutterwebviewexample/MainActivity.java @@ -1,13 +1,7 @@ package com.pichillilorenzo.flutterwebviewexample; -import com.pichillilorenzo.flutter_inappwebview.InAppWebViewFlutterPlugin; - import io.flutter.embedding.android.FlutterActivity; -import io.flutter.embedding.engine.FlutterEngine; public class MainActivity extends FlutterActivity { - @Override - public void configureFlutterEngine(FlutterEngine flutterEngine) { - flutterEngine.getPlugins().add(new InAppWebViewFlutterPlugin()); - } + } \ No newline at end of file diff --git a/example/lib/main.dart b/example/lib/main.dart index b2a35d8fa..72cb852cc 100755 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -6,13 +6,15 @@ import 'package:flutter_inappwebview_example/chrome_safari_browser_example.scree import 'package:flutter_inappwebview_example/headless_in_app_webview.screen.dart'; import 'package:flutter_inappwebview_example/in_app_webiew_example.screen.dart'; import 'package:flutter_inappwebview_example/in_app_browser_example.screen.dart'; +import 'package:permission_handler/permission_handler.dart'; // InAppLocalhostServer localhostServer = new InAppLocalhostServer(); Future main() async { WidgetsFlutterBinding.ensureInitialized(); + // await Permission.camera.request(); // await localhostServer.start(); - runApp(new MyApp()); + runApp(MyApp()); } Drawer myDrawer({@required BuildContext context}) { diff --git a/example/pubspec.yaml b/example/pubspec.yaml index ebde6ff94..948f10cfd 100755 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -22,7 +22,7 @@ dependencies: cupertino_icons: ^0.1.2 # flutter_downloader: ^1.3.2 # path_provider: ^1.4.0 - # permission_handler: ^3.3.0 + permission_handler: ^5.0.0+hotfix.6 # connectivity: ^0.4.5+6 flutter_inappwebview: path: ../ diff --git a/lib/src/headless_in_app_webview.dart b/lib/src/headless_in_app_webview.dart index c518068f7..c6eb54663 100644 --- a/lib/src/headless_in_app_webview.dart +++ b/lib/src/headless_in_app_webview.dart @@ -45,6 +45,8 @@ class HeadlessInAppWebView implements WebView { this.onUpdateVisitedHistory, this.onPrint, this.onLongPressHitTestResult, + this.onEnterFullscreen, + this.onExitFullscreen, this.androidOnSafeBrowsingHit, this.androidOnPermissionRequest, this.androidOnGeolocationPermissionsShowPrompt, @@ -268,4 +270,10 @@ class HeadlessInAppWebView implements WebView { InAppWebViewController controller, ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) shouldOverrideUrlLoading; + + @override + final void Function(InAppWebViewController controller) onEnterFullscreen; + + @override + final void Function(InAppWebViewController controller) onExitFullscreen; } \ No newline at end of file diff --git a/lib/src/in_app_browser.dart b/lib/src/in_app_browser.dart index 26ce9fb6a..d0dd96c20 100755 --- a/lib/src/in_app_browser.dart +++ b/lib/src/in_app_browser.dart @@ -440,6 +440,12 @@ class InAppBrowser { ///[hitTestResult] represents the hit result for hitting an HTML elements. void onLongPressHitTestResult(InAppWebViewHitTestResult hitTestResult) {} + ///Event fired when the current page has entered full screen mode. + void onEnterFullscreen() {} + + ///Event fired when the current page has exited full screen mode. + void onExitFullscreen() {} + ///Event fired when the WebView notifies that a loading URL has been flagged by Safe Browsing. ///The default behavior is to show an interstitial to the user, with the reporting checkbox visible. /// diff --git a/lib/src/in_app_webview.dart b/lib/src/in_app_webview.dart index 9b930a499..9c0388d29 100755 --- a/lib/src/in_app_webview.dart +++ b/lib/src/in_app_webview.dart @@ -68,6 +68,8 @@ class InAppWebView extends StatefulWidget implements WebView { this.onUpdateVisitedHistory, this.onPrint, this.onLongPressHitTestResult, + this.onEnterFullscreen, + this.onExitFullscreen, this.androidOnSafeBrowsingHit, this.androidOnPermissionRequest, this.androidOnGeolocationPermissionsShowPrompt, @@ -246,6 +248,12 @@ class InAppWebView extends StatefulWidget implements WebView { InAppWebViewController controller, ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) shouldOverrideUrlLoading; + + @override + final void Function(InAppWebViewController controller) onEnterFullscreen; + + @override + final void Function(InAppWebViewController controller) onExitFullscreen; } class _InAppWebViewState extends State { diff --git a/lib/src/in_app_webview_controller.dart b/lib/src/in_app_webview_controller.dart index 958da8d41..3e63f917f 100644 --- a/lib/src/in_app_webview_controller.dart +++ b/lib/src/in_app_webview_controller.dart @@ -433,6 +433,20 @@ class InAppWebViewController { } } break; + case "onEnterFullscreen": + if (_webview != null && + _webview.onEnterFullscreen != null) + _webview.onEnterFullscreen(this); + else if (_inAppBrowser != null) + _inAppBrowser.onEnterFullscreen(); + break; + case "onExitFullscreen": + if (_webview != null && + _webview.onExitFullscreen != null) + _webview.onExitFullscreen(this); + else if (_inAppBrowser != null) + _inAppBrowser.onExitFullscreen(); + break; case "onCallJsHandler": String handlerName = call.arguments["handlerName"]; // decode args to json diff --git a/lib/src/webview.dart b/lib/src/webview.dart index 5ca301e4f..09a82ccbc 100644 --- a/lib/src/webview.dart +++ b/lib/src/webview.dart @@ -237,6 +237,12 @@ abstract class WebView { final void Function(InAppWebViewController controller, InAppWebViewHitTestResult hitTestResult) onLongPressHitTestResult; + ///Event fired when the current page has entered full screen mode. + final void Function(InAppWebViewController controller) onEnterFullscreen; + + ///Event fired when the current page has exited full screen mode. + final void Function(InAppWebViewController controller) onExitFullscreen; + ///Event fired when the webview notifies that a loading URL has been flagged by Safe Browsing. ///The default behavior is to show an interstitial to the user, with the reporting checkbox visible. /// @@ -341,6 +347,8 @@ abstract class WebView { this.onUpdateVisitedHistory, this.onPrint, this.onLongPressHitTestResult, + this.onEnterFullscreen, + this.onExitFullscreen, this.androidOnSafeBrowsingHit, this.androidOnPermissionRequest, this.androidOnGeolocationPermissionsShowPrompt,