onShowFileChooser() из веб-просмотра Android работает только один раз

Мне нужно выбрать изображения с устройства и загрузить их на сервер. Впервые, когда я выбираю изображения, вызывается onShowFileChooser(), и все работает. Но когда я снова пытаюсь нажать «Загрузить», onShowFileChooser() никогда не вызывается. Но это работает для устройств, не поддерживающих lollypop. openFileChoser() вызывается всякий раз, когда я нажимаю «Загрузить». Есть ли что-то, чего мне не хватает. Вот мой код:

        //Needed for file upload feature
        vWebView.setWebChromeClient(new WebChromeClient() {

            // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method)
            public void openFileChooser(ValueCallback<Uri> filePathCallback) {
                showAttachmentDialog(filePathCallback);
            }

            // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method)
            public void openFileChooser(ValueCallback filePathCallback, String acceptType) {
                showAttachmentDialog(filePathCallback);
            }

            // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method)
            public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
                showAttachmentDialog(filePathCallback);

            }

            // file upload callback (Android 5.0 (API level 21) -- current) (public method)

            // for Lollipop, all in one
            @Override

            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    WebChromeClient.FileChooserParams fileChooserParams) {
                // Double check that we don't have any existing callbacks
                if (mFilePathCallbackArray != null) {
                    mFilePathCallbackArray.onReceiveValue(null);
                }
                mFilePathCallbackArray = filePathCallback;
                // Set up the take picture intent

                if (mTypeCap == IMAGE) {
                    Intent takePictureIntent = pictureIntentSetup();
                    return showChooserDialog(takePictureIntent);
                }
                //set up video capture intent
                else {
                    Intent takeVideoIntent = videoIntentSetUp();
                    return showChooserDialog(takeVideoIntent);
                }

            }

        });

  //For lollypop
    private Intent pictureIntentSetup() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getActivity().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("Failed", "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;
            }
        }
        return takePictureIntent;

    }

    //For lollypop
    private Intent videoIntentSetUp() {
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (takeVideoIntent.resolveActivity(getActivity().getPackageManager()) != null) {

            // create the file where the video should go
            File videoFile = null;
            try {
                videoFile = createVideoFile();
                takeVideoIntent.putExtra("PhotoPath", mCameraPhotoPath);
            } catch (IOException ex) {
                // Error occurred while creating the File
                Log.e("Failed", "Unable to create Video File", ex);
            }

            // continue only if the file was successfully created
            if (videoFile != null) {
                mCameraPhotoPath = "file:" + videoFile.getAbsolutePath();
                takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(videoFile));
            } else {
                takeVideoIntent = null;
            }
        }
        return takeVideoIntent;
    }

//For lollypop
    private boolean showChooserDialog(Intent intent) {
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        if (mTypeCap.equalsIgnoreCase(IMAGE))
            contentSelectionIntent.setType(IMAGE);
        else
            contentSelectionIntent.setType(VIDEO);

        Intent[] intentArray;
        if (intent != null) {
            intentArray = new Intent[]{intent};
        } else {
            intentArray = new Intent[0];
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        if (mTypeCap.equalsIgnoreCase(IMAGE))
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        else
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Video Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

        getActivity().startActivityForResult(chooserIntent, FILE_CHOOSER_RESULT_CODE);

        return true;
    }

OnActivityResult действия:

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
  //File upload related
            if (requestCode == NewsDetailFragment.FILE_CHOOSER_RESULT_CODE && (resultCode == RESULT_OK || resultCode == RESULT_CANCELED)) {
                Fragment fragment = getSupportFragmentManager()
                        .findFragmentById(R.id.container);
                if (fragment != null && fragment instanceof DetailFragment) {
                    Fragment currentFragment = ((DetailFragment) fragment).getCurrentFragment();
                    if (currentFragment instanceof WebDetailFragment)
                        currentFragment.onActivityResult(requestCode, resultCode, data);
                }
            }

        }
}

onActivityResult фрагмента:

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intentData) {
        super.onActivityResult(requestCode, resultCode, intentData);
        // code for all versions except of Lollipop
        if (!Utility.isLollypopAndAbove()) {
            Uri result = null;
            // check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == FILE_CHOOSER_RESULT_CODE) {
                    if (null == this.mFilePathCallback) {
                        return;
                    }
                    if (null == mFilePathCallback) return;


                    if (intentData == null) {
                        // if there is not data, then we may have taken a photo
                        if (mCameraPhotoPath != null) {
                            result = Uri.parse(mCameraPhotoPath);
                        }
                    } else {
                        String dataString = intentData.getDataString();
                        if (dataString != null) {
                            result = Uri.parse(dataString);
                        }
                    }
//                Uri result = intentData == null || resultCode != Activity.RESULT_OK ? null
//                        : intentData.getData();

                }

                //  for Lollipop only
            }
            mFilePathCallback.onReceiveValue(result);
            mFilePathCallback = null;
        }
        else  {
            Uri[] results = null;

            // check that the response is a good one
            if(resultCode==Activity.RESULT_OK) {
                if (requestCode == FILE_CHOOSER_RESULT_CODE) {
                    if (null == mFilePathCallbackArray) {
                        return;
                    }
                    if (intentData == 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 = intentData.getDataString();
                        if (dataString != null) {
                            results = new Uri[]{Uri.parse(dataString)};
                        }
                    }
                }
            }
            mFilePathCallbackArray.onReceiveValue(results);
            mFilePathCallbackArray = null;
            return;

        }
    }

person Sangeetha Pinto    schedule 16.04.2015    source источник
comment
Что такое элементы в вашем коде? поделись, хотел проверить   -  person atrebbi    schedule 19.09.2016


Ответы (8)


во-первых, извините за мой английский. вы должны вернуть пустой Uri[]{} для получения файла

mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});

мой код может выбрать фото или локальное изображение:

private static final int REQUEST_GET_THE_THUMBNAIL = 4000;
private static final long ANIMATION_DURATION = 200;
public final static int FILECHOOSER_RESULTCODE = 1;
public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;

//JS
webView.getSettings().setJavaScriptEnabled(true);

//set ChromeClient
webView.setWebChromeClient(getChromeClient());

//ChromeClinet配置
private WebChromeClient getChromeClient() {
    return new WebChromeClient() {

        //3.0++
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooserImpl(uploadMsg);
        }

        //3.0--
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooserImpl(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 5.0
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams fileChooserParams) {
            openFileChooserImplForAndroid5(uploadMsg);
            return true;
        }

    };
}

private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
    mUploadMessage = uploadMsg;
    new AlertDialog.Builder(mActivity)
            .setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (items[which].equals(items[0])) {
                        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                        i.addCategory(Intent.CATEGORY_OPENABLE);
                        i.setType("image/*");
                        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
                    } else if (items[which].equals(items[1])) {
                        dispatchTakePictureIntent();
                    }
                    dialog.dismiss();
                }
            })
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    Log.v(TAG, TAG + " # onCancel");
                    mUploadMessage = null;
                    dialog.dismiss();
            }})
            .show();
}

private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
    mUploadMessageForAndroid5 = uploadMsg;

    new AlertDialog.Builder(mActivity)
            .setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (items[which].equals(items[0])) {
                        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                        contentSelectionIntent.setType("image/*");

                        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

                        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
                    } else if (items[which].equals(items[1])) {
                        dispatchTakePictureIntent();
                    }
                    dialog.dismiss();
                }
            })
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    Log.v(TAG, TAG + " # onCancel");
                    //important to return new Uri[]{}, when nothing to do. This can slove input file wrok for once.
                    //InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
                    mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
                    mUploadMessageForAndroid5 = null;
                    dialog.dismiss();
            }}).show();
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(mActivity.getPackageManager()) != null) {
//            File file = new File(createImageFile());
        Uri imageUri = null;
        try {
            imageUri = Uri.fromFile(createImageFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //temp sd card file
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(takePictureIntent, REQUEST_GET_THE_THUMBNAIL);
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/don_test/");
    if (!storageDir.exists()) {
        storageDir.mkdirs();
    }
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    Log.v(TAG, TAG + " # onActivityResult # requestCode=" + requestCode + " # resultCode=" + resultCode);
    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage)
            return;
        Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;

    } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
        if (null == mUploadMessageForAndroid5)
            return;
        Uri result;

        if (intent == null || resultCode != Activity.RESULT_OK) {
            result = null;
        } else {
            result = intent.getData();
        }

        if (result != null) {
            Log.v(TAG, TAG + " # result.getPath()=" + result.getPath());
            mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
        } else {
            mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
        }
        mUploadMessageForAndroid5 = null;
    } else if (requestCode == REQUEST_GET_THE_THUMBNAIL) {
        if (resultCode == Activity.RESULT_OK) {
            File file = new File(mCurrentPhotoPath);
            Uri localUri = Uri.fromFile(file);
            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
            mActivity.sendBroadcast(localIntent);

            Uri result = Uri.fromFile(file);
            mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
            mUploadMessageForAndroid5 = null;
        } else {

            File file = new File(mCurrentPhotoPath);
            Log.v(TAG, TAG + " # file=" + file.exists());
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
person Don Tan Xu Dong    schedule 05.07.2016
comment
или просто верните ноль .onReceiveValue(null); - person FrozenFire; 06.07.2017
comment
Спасибо! Однако это вызывает странное поведение: если пользователь отменяет выбор файла (например, resultCode == Activity.RESULT_CANCELLED), null передается в WebView и очищает исходное выбранное изображение. Как это решить? - person Sira Lam; 30.01.2018
comment
как мне справиться с этим из фрагмента? - person Mahmoud Omara; 11.03.2021

Столкнувшись с аналогичной проблемой, я возвращал логическое значение в методе onShowFileChooser, проблема была исправлена, когда я вызывал метод суперкласса

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            //Logic to implement 
            return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
        }
person ked    schedule 01.06.2016
comment
Я не понимаю. Зачем вам переопределять метод, а затем просто вызывать его из переопределения? Разве это не то же самое, как если бы у вас не было никакого метода? - person Nateowami; 06.12.2017
comment
//Логика для реализации - реализуем логику перед вызовом суперметода - person ked; 06.12.2017
comment
Ах, извините, я пропустил это. Мои извинения. - person Nateowami; 06.12.2017
comment
@ked, ты спас мой день, приятель. Большое спасибо :) Здоровья! - person Rakesh; 07.02.2018
comment
Если вы посмотрите на исходный код `super.onShowFileChooser()` в WebChromeClient.java, он просто возвращает false. - person Udo Klimaschewski; 30.05.2018
comment
@ked Не могли бы вы взглянуть на мой вопрос - stackoverflow.com/questions/56114296/ - person newdeveloper; 13.05.2019

В методе onShowFileChooser() вы должны вернуть true, только если вы используете filePathCallback, что является лучшим способом:

private ValueCallback<Uri[]> filePathCallback;

@Override
public boolean onShowFileChooser(
        WebView webView, ValueCallback<Uri[]> filePathCallback,
        WebChromeClient.FileChooserParams fileChooserParams) {
    // do whatever you need to do, to show a file chooser/camera intent
    this.filePathCallback = filePathCallback;
    return true;
}

@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent intent) {
    // Check for your correct requestCode from your intent here
    if (resultCode == RESULT_CANCELED) {
        // this is important, call the callback with null parameter
        this.filePathCallback.onReceiveValue(null);
    } else if (resultCode == RESULT_OK) {
        // extract the uri(s) you need here
        this.filePathCallback.onReceiveValue(new Uri[]{result});
    }
}
person Udo Klimaschewski    schedule 30.05.2018
comment
result переменная неизвестна. - person CoolMind; 15.11.2018
comment
что такое переменный результат? ты не заявлял об этом - person Azlan Jamal; 03.08.2019
comment
Результат переменной имеет тип Uri, вы должны извлечь Uri выбранного файла из переданных данных Intent. Например. Результат Uri = Uri.parse(intent.getDataString()) - person Udo Klimaschewski; 05.08.2019
comment
Спасибо за этот код, он был очень полезен. Вы можете передать параметр следующим образом filePathCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent)); - person Filoména Petržlénová; 12.07.2021

Просто установите нулевое значение:

if (resultCode == Activity.RESULT_OK) {
    handleImageRequest(data)
} else {
    mValueCallbackArray?.onReceiveValue(null)
    mValueCallbackArray = null
}
person Addy    schedule 01.02.2021
comment
Что такое resultCode и где он вызывается? В onActivityResult? - person CoolMind; 03.08.2021

У меня была аналогичная проблема, что onShowFileChooser работает только один раз. После нескольких часов проб и ошибок, а затем я понял, используя простой эксперимент:

  • Отсутствие вызова ValueCallback приведет к тому, что onShowFileChooser сработает только один раз. Код ниже работает только один раз...

    override fun onShowFileChooser(
      view: WebView?,
      filePath: ValueCallback<Array<Uri>>?,
      fileChooserParams: FileChooserParams?
    ): Boolean {
      Log.i("blah", "<== onShowFileChooser ==>")
      // filePath?.onReceiveValue(null)
      return true
    }
    
  • Правильный вызов ValueCallback заставит onShowFileChooser работать каждый раз:

    override fun onShowFileChooser(
      view: WebView?,
      filePath: ValueCallback<Array<Uri>>?,
      fileChooserParams: FileChooserParams?
    ): Boolean {
      Log.i("blah", "<== onShowFileChooser ==>")
      filePath?.onReceiveValue(null)
      return true
    }
    

поэтому я просто проверяю все ветки и удостоверяюсь, что все они правильно вызывают ValueCallback, тогда веб-просмотр работает, как и ожидалось.

person wMaN    schedule 15.03.2021

У меня была точно такая же проблема, но мой вариант использования немного отличается, но мой веб-просмотр был загружен на фрагмент, как в вашем коде. в первый раз средство выбора файлов отображалось нормально как на устройствах Lollipop, так и на устройствах до Lollipop, но в следующий раз он не смог отобразить средство выбора файлов самостоятельно. Причина в том, что я не обработал onActivityResult должным образом в первый раз. Мой рабочий фрагмент кода для Lollipop выглядит следующим образом:

 @TargetApi(Build.VERSION_CODES.LOLLIPOP)

 private boolean onActivityResultLolliPop(
      int requestCode, int resultCode, Intent data) {

    if (requestCode != SurveyWebChromeClient.FILE_CHOOSER_REQUEST_CODE 
            || mFilePathCallbackL == null) {
        super.onActivityResult(requestCode, resultCode, data);
        return true;
    }

    Uri[] results = null;
    if (resultCode == Activity.RESULT_OK) {
        if (data == null) {
            if (mCameraPhotoVideoPath != null) {//if there is not data here, then we may have taken a photo/video
                results = new Uri[]{Uri.parse(mCameraPhotoVideoPath)};
            }
        } else {
            String dataString = data.getDataString();
            ClipData clipData = data.getClipData();

            if (clipData != null) {
                results = new Uri[clipData.getItemCount()];
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item item = clipData.getItemAt(i);
                    results[i] = item.getUri();
                }
            }

            if (dataString != null)
                results = new Uri[]{Uri.parse(dataString)};
        }
    }
    mFilePathCallbackL.onReceiveValue(results);
    mFilePathCallbackL = null;
    return false;
}
person MadKavi    schedule 16.04.2015
comment
Моя проблема исправлена. Причина этого заключалась в том, что веб-просмотр был приостановлен в onPause(). Следовательно, он не реагировал на нажатие кнопки - person Sangeetha Pinto; 17.04.2015
comment
@AmandaFernandez, как решить эту проблему, пожалуйста, опубликуйте свой код, спасибо - person Carl; 27.05.2015
comment
@Карл, я уже разместил свой код. В моем случае в onPause() фрагмента веб-просмотр был приостановлен и никогда не возобновлялся. Так что onShowFileChoser() не вызывался. Просто проверьте, какой код результата вы получаете в onActivityResult(). Результат должен быть передан вашей активности, которая затем передается в FilePathCallback. Может быть, результат не передается вашей активности. Проверьте мой onActivityResultCode(). - person Sangeetha Pinto; 28.05.2015
comment
@AmandaFernandez спасибо за ваш ответ. Я решил эту проблему. В моем случае проблема в onActivityResult(), я не обрабатываю результат - person Carl; 29.05.2015

Просто позвольте onShowFIleChooser() вернуть false, сработает в следующий раз

public boolean onShowFileChooser(){
... 
return **false**;
}
person 趙令文    schedule 01.08.2018
comment
Если вы установите false, вы получите исключение в onActivityResult при попытке вызвать mFilePathCallback.onReceiveValue(result);. - person CoolMind; 19.11.2018

У меня была та же проблема, проблема заключалась в том, что я ожидал OnActivityResult, но когда вы нажимали кнопку «Назад», это не срабатывало.

Решение заключалось в реализации на onResume следующего кода, чтобы сообщить обратному вызову, что ответ был пустым и иметь возможность его повторного использования:

@Override
protected void onResume() {
    super.onResume();
    if (mFilePathCallbackArray == null)
        return;

    mFilePathCallbackArray.onReceiveValue(new Uri[]{});
    mFilePathCallbackArray = null;
}
person Daniel Silva    schedule 07.10.2019