Skip to content Skip to sidebar Skip to footer

Webview App Permission For Capturing Images Using Camera And Uploading Images From Gallery

which code I have to put for allowing to take pictures using camera and uploading images from gallery in android webview app and where should I put it.

Solution 1:

Add in Manifest.xml:

<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />

For android versions higher than M you have to ask for permissions, I'm referring to this question:

Link

Solution 2:

In webview you don't need any permission.

publicclassMainActivityextendsAppCompatActivity {

    privatestaticfinalintINPUT_FILE_REQUEST_CODE=1;
    privatestaticfinalintFILECHOOSER_RESULTCODE=1;
    privatestaticfinalStringTAG= MainActivity.class.getSimpleName();
    Context context;
    WebView webView;
    private WebSettings webSettings;
    private ValueCallback<Uri> mUploadMessage;
    privateUrimCapturedImageURI=null;
    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;

    @OverridepublicvoidonActivityResult(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 oneif (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photoif (mCameraPhotoPath != null) {
                        results = newUri[]{Uri.parse(mCameraPhotoPath)};
                    }
                } else {
                    StringdataString= data.getDataString();
                    if (dataString != null) {
                        results = newUri[]{Uri.parse(dataString)};
                    }
                }
            }
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
        } elseif (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;
                }
                Uriresult=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;
    }

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        webView = (WebView) findViewById(R.id.salonid);
        WebSettingssettings= webView.getSettings();
        settings.setJavaScriptEnabled(true);
        webView.loadUrl("Paste_your_url");
        webView.setWebChromeClient(newChromeClient());
        webView.setWebViewClient(newWebViewClient() {

            @OverridepublicvoidonPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                Log.w("----------", "pageee finish : " + url);
            }

            publicvoidonReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
                try {
                    webView.stopLoading();
                } catch (Exception e) {
                }
                if (webView.canGoBack()) {
                    webView.goBack();
                }
                webView.loadUrl("about:blank");
                AlertDialogalertDialog=newAlertDialog.Builder(context).create();
                alertDialog.setTitle("Error");
                alertDialog.setCancelable(false);
                alertDialog.setMessage("Check your internet connection and try again.");
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", newDialogInterface.OnClickListener() {
                    publicvoidonClick(DialogInterface dialog, int which) {
                        startActivity(getIntent());
                        finish();
                    }
                });
                alertDialog.show();
                super.onReceivedError(webView, errorCode, description, failingUrl);
            }
        });
    }

    private File createImageFile()throws IOException {
        // Create an image file nameStringtimeStamp=newSimpleDateFormat("yyyyMMdd_HHmmss").format(newDate());
        StringimageFileName="JPEG_" + timeStamp + "_";
        FilestorageDir= Environment.getExternalStoragePublicDirectory(
                Environment.getExternalStorageState());
        FileimageFile= File.createTempFile(
                imageFileName,  /* prefix */".jpg",         /* suffix */
                storageDir      /* directory */
        );
        return imageFile;
    }

    publicbooleanonKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's historyif ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            returntrue;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default// system behavior (probably exit the activity)returnsuper.onKeyDown(keyCode, event);
    }

    @OverridepublicvoidonBackPressed() {
        super.onBackPressed();
    }

    publicclassChromeClientextendsWebChromeClient {
        // For Android 5.0publicbooleanonShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
            // Double check that we don't have any existing callbacksif (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePath;
            IntenttakePictureIntent=newIntent(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;
                }
            }
*/IntentcontentSelectionIntent=newIntent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);

            contentSelectionIntent.setType("image/*");
            contentSelectionIntent.setType("*/*");
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = newIntent[]{takePictureIntent};
            } else {
                intentArray = newIntent[0];
            }
            IntentchooserIntent=newIntent(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);
            returntrue;
        }

        // openFileChooser for Android 3.0+publicvoidopenFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            // Create AndroidExampleFolder at sdcard// Create AndroidExampleFolder at sdcardFileimageStorageDir=newFile(
                    Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_DOCUMENTS)
                    , "AndroidExampleFolder");
            if (!imageStorageDir.exists()) {
                // Create AndroidExampleFolder at sdcard
                imageStorageDir.mkdirs();
            }
            // Create camera captured image file path and nameFilefile=newFile(
                    imageStorageDir + File.separator + "IMG_"
                            + String.valueOf(System.currentTimeMillis())
                            + ".jpg");
            mCapturedImageURI = Uri.fromFile(file);
            // Camera capture image intentfinalIntentcaptureIntent=newIntent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
            Intenti=newIntent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("text/*");
            // Create file chooser intentIntentchooserIntent= Intent.createChooser(i, "Image Chooser");
            // Set camera intent to file chooser
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
                    , newParcelable[]{captureIntent});
            // On select image call onActivityResult method of activity
            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
        }

        // openFileChooser for Android < 3.0publicvoidopenFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        //openFileChooser for other Android versionspublicvoidopenFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType,
                                    String capture) {
            openFileChooser(uploadMsg, acceptType);
        }
    }
}

Post a Comment for "Webview App Permission For Capturing Images Using Camera And Uploading Images From Gallery"