9

I a newbie in android. I am creating a small app to take photo and upload it to server. I am using Webview and html form do that. In browser (chrome) camera is opening. But in webview, camera is not opened when "choose file" is clicked. Anyone know a solution? Below is the code i used....

HTML Code

<html>
<body>
<form>
<input type="file" accept="image/*;capture=camera"/>
<input type="submit"/>
</form>
</body>
</html>

Java code used in Android (eclipse)

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebViewClient(new WebViewClient());
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl("http://www.inforge.in/thejus/test.html");
}       


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

6
  • What version of android are you targeting? It matters Commented Mar 27, 2015 at 0:15
  • 4.2.1 Will it not work in other version? Commented Mar 27, 2015 at 0:16
  • It only works in android 3+. It should work for you. Commented Mar 27, 2015 at 0:23
  • no, its not working. On browser its working, but in webview its working Commented Mar 27, 2015 at 0:32
  • try this stackoverflow.com/a/41570241/3518278 Commented Jan 10, 2017 at 14:43

4 Answers 4

7

try this:

webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginState(WebSettings.PluginState.ON);
webview.getSettings().setMediaPlaybackRequiresUserGesture(false);

webview.setWebChromeClient(new WebChromeClient(){
    // Need to accept permissions to use the camera
    @Override
    public void onPermissionRequest(final PermissionRequest request) {
        Log.d("onPermissionRequest");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            request.grant(request.getResources());
        }
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain "L.d" here?
it's just Log.d(). logging
1

You can go through the following open source project to find how others solved this problem. This can help you to improve/fix your code. A direct link to a code snippet of interest: Getting camera permission in SmartWebView.

Android Smart WebView. Open Source Project to upload files, get GPS locations and more advanced features

Also, your codes don't have any image capture intent or any file chooser method, you need them to use the camera and also file creation method to write a new image to the device. And, in your Manifest, you need to have WRITE_EXTERNAL_STORAGE permission to write new files to the device for upload.

Hope it helps.

Comments

0

It looks like your input tag might be mal-formatted.

Try this. It's for the new HTML Media Capture spec

<input type="file" name="file" accept="image/*" capture>

Or try this older version

<input type="file" name="file" accept="image/*" capture="camera">

Edit...

Or better yet, use an intent.

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

source: http://developer.android.com/training/camera/photobasics.html#TaskCaptureIntent

7 Comments

its working in browser. But on webview, its not opening
Why don't you use a regular intent to open the camera? When the image comes back, you can feed it back into the webview.
i don't much in java coding. Thats why i choose webview. Can you help me in that regular intent?
I don't have much experience in java, either. Check the link at the bottom of the answer.
what i need is take a photo, upload to server, then show a webview
|
0

Complete code here.

public class ShowWebView extends Activity {

//private Button button;
private WebView webView;
final Activity activity = this;
public Uri imageUri;

private static final int FILECHOOSER_RESULTCODE   = 2888;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;


public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.show_web_view);

    //Get webview 
    webView = (WebView) findViewById(R.id.webView1);

    // Define url that will open in webview 
    String webViewUrl = "http://www.androidexample.com/media/webview/details.html";



    // Javascript inabled on webview  
    webView.getSettings().setJavaScriptEnabled(true);

    // Other webview options
    webView.getSettings().setLoadWithOverviewMode(true);

    //webView.getSettings().setUseWideViewPort(true);

    //Other webview settings
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setPluginState(PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setSupportZoom(true); 

    //Load url in webview
    webView.loadUrl(webViewUrl);

    // Define Webview manage classes
    startWebView(); 

} 

private void startWebView() {



    // Create new webview Client to show progress dialog
    // Called When opening a url or click on link
    // You can create external class extends with WebViewClient 
    // Taking WebViewClient as inner class

    webView.setWebViewClient(new WebViewClient() {      
        ProgressDialog progressDialog;

        //If you will not use this method url links are open in new brower not in webview
        public boolean shouldOverrideUrlLoading(WebView view, String url) {              

            // Check if Url contains ExternalLinks string in url 
            // then open url in new browser
            // else all webview links will open in webview browser
            if(url.contains("google")){ 

                // Could be cleverer and use a regex
                //Open links in new browser
                view.getContext().startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                // Here we can open new activity

                return true;

            } else {

                // Stay within this webview and load url
                view.loadUrl(url); 
                return true;
            }

        }



        //Show loader on url load
        public void onLoadResource (WebView view, String url) {

            // if url contains string androidexample
            // Then show progress  Dialog
            if (progressDialog == null && url.contains("androidexample") 
                    ) {

                // in standard case YourActivity.this
                progressDialog = new ProgressDialog(ShowWebView.this);
                progressDialog.setMessage("Loading...");
                progressDialog.show();
            }
        }

        // Called when all page resources loaded
        public void onPageFinished(WebView view, String url) {

            try{
                // Close progressDialog
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
            }catch(Exception exception){
                exception.printStackTrace();
            }
        }

    }); 


    // You can create external class extends with WebChromeClient 
    // Taking WebViewClient as inner class
    // we will define openFileChooser for select file from camera or sdcard

    webView.setWebChromeClient(new WebChromeClient() {

        // openFileChooser for Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){  

            // Update message
            mUploadMessage = uploadMsg;

            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
                startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

              }
             catch(Exception e){
                 Toast.makeText(getBaseContext(), "Exception:"+e, 
                            Toast.LENGTH_LONG).show();
             }

        }

        // 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);
        }



        // The webPage has 2 filechoosers and will send a 
        // console message informing what action to perform, 
        // taking a photo or updating the file

        public boolean onConsoleMessage(ConsoleMessage cm) {  

            onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
            return true;
        }

        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
            //Log.d("androidruntime", "Show console messages, Used for debugging: " + message);

        }
    });   // End setWebChromeClient

}



// Return here when file selected from camera or from SDcard

@Override 
protected void onActivityResult(int requestCode, int resultCode,  
                                   Intent intent) { 

 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 = intent == null ? mCapturedImageURI : intent.getData(); 
            } 
        }
        catch(Exception e)
        {
            Toast.makeText(getApplicationContext(), "activity :"+e,
             Toast.LENGTH_LONG).show();
        }

        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;

 }

}

// Open previous opened link from history on webview when back button pressed

@Override
// Detect when the back button is pressed
public void onBackPressed() {

    if(webView.canGoBack()) {

        webView.goBack();

    } else {
        // Let the system handle the back button
        super.onBackPressed();
    }
}

}

5 Comments

bro, i am new in android. Can you pls edit my code with this. Because when i pasted it, it gives a lot of errors. I tried importing. But still errors. Pls help me
declare the web view xml as : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <WebView android:id="@+id/webView1" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
have you created xml and then loaded the web view in it as mentioned in the code.
i am getting same issue but it can't working is there any solution ?
@MaxGreen Above soln is not working with Android 9.0.pie. Evrything works fine till mUploadMessage.onReceiveValue(result);. but after that nothing is working. also in logs seen this error "failed to create image decoder with message 'unimplemented'".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.