i am developing a simple WebView app in which i have a form in which i need to select or take a picture from camera. getting picture from gallery is working fine but when i take picture from camera and press done it didn't do anything at all app stays in camera if i cancel it came back in app but no image. i Assume there might be some issue with this part of my code.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != FILECHOOSER_RESULTCODE || uploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
uploadMessage.onReceiveValue(results);
uploadMessage = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
and
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
}
uploadMessage = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Please Select a Option");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
return true;
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Please Select a Option");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
And here is permissions Part of Manifest file.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.CAMERA" />
Related
I am opening the camera and file chooser in my application. It's working fine in all versions including android 11. But in google pixel 5 with android 11, it's breaking while trying to open the camera. App not breaking but camera keep closing alert is showing and below exception is happening.
java.lang.IllegalStateException: GCA not granted write permission to file:///storage/emulated/0/Pictures/JPEG_20210727_095347_634440296695227002.jpg
Java code :
/***Camera or file chooser ***/
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
if ( Build.VERSION.SDK_INT <= 29) {
file_path = filePathCallback;
Intent takePictureIntent = null;
boolean includePhoto = true;
if (includePhoto)
{
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
File photoFile = null;
try {
photoFile = create_image();
takePictureIntent.putExtra("PhotoPath", cam_file_data);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
cam_file_data = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
cam_file_data = null;
takePictureIntent = null;
}
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType(file_type);
if (multiple_files) {
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{
takePictureIntent
};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "File chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, file_req_code);
return true;
} else if ( Build.VERSION.SDK_INT >= 30) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
}
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
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);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
} else {
return false;
}
}
private File create_image() throws IOException {
#SuppressLint("SimpleDateFormat")
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_" + timeStamp + "_";
File storageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES); //getCacheDir();
return File.createTempFile(imageFileName, ".jpg", storageDir);
}
Call back
/*******Camera Request Callback******/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null)
{
super.onActivityResult(requestCode, resultCode, intent);
return;
}
Uri[] results = null;
if (resultCode == Activity.RESULT_OK) {
if (intent == null) {
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = intent.getDataString();
if (dataString != null)
{
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
Uri[] results = null;
if (resultCode == Activity.RESULT_CANCELED) {
if (requestCode == file_req_code) {
file_path.onReceiveValue(null);
return;
}
}
if (resultCode == Activity.RESULT_OK) {
if (requestCode == file_req_code) {
if (null == file_path) {
return;
}
ClipData clipData;
String stringData;
try {
clipData = intent.getClipData();
stringData = intent.getDataString();
} catch (Exception e) {
clipData = null;
stringData = null;
}
if (clipData == null && stringData == null && cam_file_data != null) {
results = new Uri[]{
Uri.parse(cam_file_data)
};
} else {
if (clipData != null) {
final int numSelectedFiles = clipData.getItemCount();
results = new Uri[numSelectedFiles];
for (int i = 0; i < clipData.getItemCount(); i++) {
results[i] = clipData.getItemAt(i).getUri();
}
} else {
results = new Uri[]{
Uri.parse(stringData)
};
}
}
}
}
file_path.onReceiveValue(results);
file_path = null;
} else {
if (requestCode == file_req_code) {
if (null == file_data)
return;
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
file_data.onReceiveValue(result);
file_data = null;
}
}
}
Android manifest file :
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.CAMERA2" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"
/>
I developed website and converted it into Android app using WebView. Saw few implementation and tried FILE upload, where I can upload image from gallery but I am not allowed to upload image which is taken from Camera. I was thrown net::ERR_ACCESS_DENIED error. Please help me to get this fixed.
MAINACTIVITY.java
public class MainActivity extends AppCompatActivity {
private WebView web;
String webUrl = "https://mywebsite.com/";
public Context context;
private static final String TAG = MainActivity.class.getSimpleName();
private static final int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web = (WebView) findViewById(R.id.myweb);
web.loadUrl(webUrl);
WebSettings mywebsettings = web.getSettings();
mywebsettings.setJavaScriptEnabled(true);
web.setWebViewClient(new WebViewClient());
web.getSettings().setLoadsImagesAutomatically(true);
web.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
web.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
web.getSettings().setAppCacheEnabled(true);
web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mywebsettings.setDomStorageEnabled(true);
mywebsettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
mywebsettings.setUseWideViewPort(true);
mywebsettings.setSavePassword(true);
mywebsettings.setSaveFormData(true);
mywebsettings.setEnableSmoothTransition(true);
web.setWebChromeClient(new WebChromeClient() {
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
Log.e(TAG, "Unable to create Image File", ex);
}
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.image_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
return true;
}
private File createImageFile() throws IOException {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
imageStorageDir = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
return imageStorageDir;
}
public void openFileChooser(ValueCallback<uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
try {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mCapturedImageURI = Uri.fromFile(file); // save to the private variable
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Intent chooserIntent = Intent.createChooser(i, getString(R.string.image_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Camera Exception:" + e, Toast.LENGTH_LONG).show();
}
}
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
public void openFileChooser(ValueCallback<uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
});
}
verride
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
if (resultCode == Activity.RESULT_OK) {
if (data == null || data.getData() == null) {
// if there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
}
}
#Override
public void onBackPressed() {
if(web.canGoBack()){
web.goBack();
}
else {
super.onBackPressed();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/web"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
using following app permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.CAMERA2"/>
strings.xml
<string name="image_chooser">File Chooser</string>
I have kept an html file on a website.
https://pinapakait.com/cam/testcam.html
It has following simple input type file code
input type="file" accept="image/*;capture=camera"
It is opening files, camera options when opened in mobile through web browser. But now opening in web view of android.
Your help is very much appreciated.
Gave following permissions
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.CAMERA"
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
uses-feature android:name="android.hardware.camera" android:required="true"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"
uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"
set following settings for web view.
setLoadsImagesAutomatically(true)
setJavaScriptEnabled(true)
setDomStorageEnabled(true)
setLoadWithOverviewMode(true)
setPluginState(WebSettings.PluginState.ON)
setMediaPlaybackRequiresUserGesture(false)
setPluginState(WebSettings.PluginState.ON)
setAppCacheEnabled(true)
setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY)
setAllowFileAccessFromFileURLs(true)
setAllowUniversalAccessFromFileURLs(true)
setJavaScriptCanOpenWindowsAutomatically(true)
setBuiltInZoomControls(true)
setPluginsEnabled(true)
setAllowFileAccess(true)
setAllowContentAccess(true)
setSupportZoom(true)
I had same problem with webview and after googling it I found this solution by extending WebChromeClient .
public class MyWebChromeClient extends WebChromeClient {
DetailsFragmentWebView context;
public ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> mUploadMessageAboveL;
public Uri mCapturedImageURI;
public MyWebChromeClient(DetailsFragmentWebView context){
this.context = context;
//this.mCapturedImageURI = mCapturedImageURI;
//this.mUploadMessage = mUploadMessage;
//this.mUploadMessageAboveL = mUploadMessageAboveL;
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, ValueCallback<Uri[]> uploadMsgAboveL, String acceptType){
// Update message
mUploadMessage = uploadMsg;
mUploadMessageAboveL = uploadMsgAboveL;
try{
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
context.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
catch(Exception e){
Toast.makeText(context.getActivity(), "Chrome Exception:"+e,
Toast.LENGTH_LONG).show();
}
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg , mUploadMessageAboveL, acceptType);
}
#Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
openFileChooser(null ,filePathCallback , "");
return true;
}
}
And set your webview to use this class :
MyWebChromeClient myChromeClient = new myChromeClient(this);
webView.webChromeClient = myChromeClient;
Also you need to add this code to your Activity :
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//super.onActivityResult(requestCode, resultCode, data)
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == myChromeClient.mUploadMessage && null == myChromeClient.mUploadMessageAboveL) return
val result = if (resultCode != RESULT_OK) null
else if (data!=null) data.data
else myChromeClient.mCapturedImageURI
if (myChromeClient.mUploadMessageAboveL != null) {
onActivityResultAboveL(requestCode, resultCode, data)
} else if (myChromeClient.mUploadMessage != null) {
myChromeClient.mUploadMessage?.onReceiveValue(result)
myChromeClient.mUploadMessage = null
}
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun onActivityResultAboveL(requestCode: Int, resultCode: Int, intent: Intent?) {
if (requestCode != FILECHOOSER_RESULTCODE || myChromeClient.mUploadMessageAboveL == null)
return
var results: Array<Uri>? = null
if (resultCode == Activity.RESULT_OK) {
if (intent != null) {
val dataString = intent.dataString
val clipData = intent.clipData
if (clipData != null) {
results = Array<Uri>(clipData.itemCount) { _->return Unit}
for (i in 0 until clipData.itemCount) {
val item = clipData.getItemAt(i)
results[i] = item.uri
}
}
if (dataString != null)
results = arrayOf(Uri.parse(dataString))
}else if (myChromeClient.mCapturedImageURI!=null)
results = arrayOf(myChromeClient.mCapturedImageURI)
}
myChromeClient.mUploadMessageAboveL?.onReceiveValue(results)
myChromeClient.mUploadMessageAboveL = null
}
I am creating an app to load an URL in web view. I have created Image chooser to start activity for choose the photo from gallery and camera.
A) Select image from gallery is working perfectly.
B) When I capture image through camera then It is showing crashed small image icon in web view.
Note : Camera photo is displaying perfectly on web view when I stay more then 5-8 seconds on Camera screen after image captured. But It should be work even I press YES button quickly after captured the image.
Here is my web view Code for set WebChromeClient
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> newFilePathCallback,
FileChooserParams fileChooserParams) {
if (filePathCallback != null) {
filePathCallback.onReceiveValue(null);
}
filePathCallback = newFilePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
Log.d("Mainn", "onShowFileChooser()");
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.d("Mainn", "onShowFileChooser().. e : " + e.getLocalizedMessage());
e.printStackTrace();
}
Log.d("Mainn", "onShowFileChooser() 4");
// Continue only if the File was successfully created
if (photoFile != null) {
Log.d("Mainn", "onShowFileChooser() 5");
cameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
Log.d("Mainn", "onShowFileChooser() 6");
takePictureIntent = null;
}
}
Log.d("Mainn", "onShowFileChooser() 7");
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
Log.d("Mainn", "onShowFileChooser() 8");
intentArray = new Intent[]{takePictureIntent};
} else {
Log.d("Mainn", "onShowFileChooser() 9");
intentArray = new Intent[0];
}
Log.d("Mainn", "onShowFileChooser() 10");
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);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
});
}
onActivityResult() Code is here
#Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode != INPUT_FILE_REQUEST_CODE || filePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (cameraPhotoPath != null) {
results = new Uri[]{Uri.parse(cameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
filePathCallback.onReceiveValue(results);
filePathCallback = null;
}
Use FileProvider instead of Uri.fromFile(). It will solve this problem.
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName(), photoFile);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
I am working on android webview. I am facing problem while uploading the image from Camera action in Nexus 5. Here, Camera get open, I click the image but then nothing happens,image is not get upload. But it works fine with like Document or Gallery. There are a lot solution and this. But I am unable to solve my problem. What can be done to solve this issue?
In my menifest file, I include :
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In my activity, i include :
private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private WebView webView;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
}
else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
For my WebChromeClient, I include :
public class MyWebChromeClient extends WebChromeClient{
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
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);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "Photo Folder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
Log.d("File", "File: " + file);
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
}
What can be done here, so that image get uploaded via Camera action ?
I solve my issue for Camera by changing following line of code in onActivityResult method :
if (resultCode == Activity.RESULT_OK) {
if (data == null || data.getDataString() == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
I add this : if (data == null || data.getDataString() == null) {...}
Add android:requestLegacyExternalStorage="true" to the application tag in manifest