1

Вообщем код брал с примеров от гугла. setUpWebViewDefaults(mWebView); вызываю при старте соответственно. В нем идет настройка и установка моего WebChromeClient. Cудя по логам проблема в WebChromeClient. Окно выбора файла открывается все норм, приходит onActivityResult и все, но при этом метод onShowFileChooser не вызывается, не могу понять почему, на сколько я понимаю он должен вызываться при нажатии на поле для выбора файла - но в итоге ничего( В итоге файл так и не выгружается. Помогите решить проблему.

package ru.software.metilar.miuipro.fragments.news;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Spinner;

import com.github.johnpersano.supertoasts.library.Style;
import com.github.johnpersano.supertoasts.library.SuperActivityToast;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import ru.software.metilar.miuipro.MainActivity;
import ru.software.metilar.miuipro.R;

public class CommentsDetaliNewsFragment extends Fragment {

    private WebView dataCommentsNew;
    private CircleProgressBar pbProcess;
    private String href, comments, title;
    private View fragment;

    public static final int INPUT_FILE_REQUEST_CODE = 1;

    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        title = getArguments().getString("title");
        href = getArguments().getString("href");
        comments = getArguments().getString("sdisqus");
        MainActivity Activity = (MainActivity) getActivity();
        Activity.getSupportActionBar().setSubtitle(title);
        Activity.selectMenu(R.id.nav_news);
        Activity.setAdsVisible(true);
        Activity.findViewById(R.id.spinner_toolbar).setVisibility(Spinner.GONE);

        fragment = inflater.inflate(R.layout.fragment_news_detali_comments, null);

        pbProcess = fragment.findViewById(R.id.pbNew);
        pbProcess.setVisibility(ProgressBar.GONE);

        dataCommentsNew = fragment.findViewById(R.id.dataCommentsNew);
        dataCommentsNew.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        dataCommentsNew.getSettings().setSupportMultipleWindows(true);
        setUpWebViewDefaults(dataCommentsNew);

        if (dataCommentsNew.getUrl() == null) {
            if (href == null) dataCommentsNew.loadDataWithBaseURL(null, comments, "text/html", "ru_RU", null);
            else dataCommentsNew.loadUrl(href);
        }

        return fragment;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        Log.i(MainActivity.TAG, "CDNF - onActivityResult = " + mFilePathCallback);

        if(requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
            super.onActivityResult(requestCode, resultCode, data); return;
        }

        Uri[] results = null;
        if(resultCode == Activity.RESULT_OK) {
            if(data == null) {
                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;
        return;
    }

    @SuppressLint("SetJavaScriptEnabled")
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void setUpWebViewDefaults(WebView webView) {
        WebSettings settings = webView.getSettings();
        settings.setMixedContentMode(0);
        settings.setAllowFileAccess(true);
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setUserAgentString("Mozilla/5.0 (Linux; Android 5.1.1; Nexus 5 Build/LMY48B; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.65 Mobile Safari/537.36");
        //settings.setUserAgentString("Android");
        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptThirdPartyCookies(webView, true);
    }

    private class MyWebViewClient extends WebViewClient
    {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
            SuperActivityToast.create(getActivity(), new Style(), Style.TYPE_STANDARD)
                    .setText(getResources().getString(R.string.download_file_errors))
                    .setDuration(Style.DURATION_VERY_SHORT)
                    .setFrame(Style.FRAME_LOLLIPOP)
                    .setTextSize(Style.TEXTSIZE_MEDIUM)
                    .setGravity(Gravity.BOTTOM)
                    .setColor(Color.parseColor("#e53935"))
                    .setAnimations(Style.ANIMATIONS_FLY).show();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i(MainActivity.TAG, "shouldOverrideUrlLoading: url = " + url);
            if (url.startsWith("https://disq.us")) {
                Uri address = Uri.parse(url);
                Intent openLink = new Intent(Intent.ACTION_VIEW, address);
                startActivity(Intent.createChooser(openLink, "Browser"));
            } else view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) { pbProcess.setVisibility(ProgressBar.VISIBLE); }

        @Override
        public void onPageFinished(WebView view, String url) { pbProcess.setVisibility(ProgressBar.GONE); }
    }

    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(imageFileName,".jpg", storageDir);
        return imageFile;
    }


        private class MyWebChromeClient extends WebChromeClient {
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams){
                Log.i(MainActivity.TAG, "CDNF - onShowFileChooser");

                if(mFilePathCallback != null) mFilePathCallback.onReceiveValue(null);
                mFilePathCallback = filePathCallback;

                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                    } catch (IOException ignore) {}

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

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
            new AlertDialog.Builder(getContext())
                    .setTitle(getResources().getString(R.string.disqus_notify))
                    .setMessage(message)
                    .setPositiveButton(android.R.string.ok,
                            new AlertDialog.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    result.confirm();
                                }
                            }).setCancelable(false).create().show();

            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            new AlertDialog.Builder(getContext())
                    .setTitle(getResources().getString(R.string.disqus_cnotify))
                    .setMessage(message)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    result.confirm();
                                }
                            }).setNegativeButton(android.R.string.cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                        }
                    }).create().show();
            return true;
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {

            final WebView newWebView = new WebView(getContext());
            setUpWebViewDefaults(newWebView);
            Log.i(MainActivity.TAG, "onCreateWindow");
            newWebView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    Log.i(MainActivity.TAG, "onPageStarted: url=" + url);
                    /*if (url.startsWith("https://disqus.com/_ax/google/")) {
                        dataCommentsNew.loadUrl(url);
                        newWebView.destroy();
                    } else*/ if (url.startsWith("https://disqus.com/next/login/") || url.startsWith("https://disqus.com/_ax/facebook/")
                            || url.startsWith("https://disqus.com/_ax/twitter/") || url.startsWith("https://disqus.com/_ax/google/")) {
                        final Dialog dialog = new Dialog(getContext());
                        dialog.setContentView(newWebView);
                        dialog.show();
                        newWebView.setWebViewClient(new WebViewClient(){});
                        newWebView.setWebChromeClient(new WebChromeClient() {
                            @Override
                            public void onCloseWindow(WebView window) {
                                dialog.dismiss();
                                newWebView.destroy();
                            }
                        });
                        Log.i(MainActivity.TAG, "onPageStarted: UserAgentString = " + newWebView.getSettings().getUserAgentString());

                    } else if (url.startsWith("https://uploads.disquscdn.com/images")){
                        final Dialog dialog = new Dialog(getContext());
                        dialog.setContentView(newWebView);
                        dialog.show();
                        newWebView.getSettings().setBuiltInZoomControls(true);
                        newWebView.getSettings().setDisplayZoomControls(false);
                        newWebView.getSettings().setLoadWithOverviewMode(true);
                        newWebView.setWebViewClient(new WebViewClient(){});
                        String html = "<html><head><style>body {max-width: 100%;} img {max-width: 99%; height: auto;}</style></head><body><img src=\"" +url + "\"/></body></html>";
                        newWebView.loadDataWithBaseURL(null, html, "text/html", "ru_RU", null);
                        newWebView.setWebChromeClient(new WebChromeClient() {
                            @Override
                            public void onCloseWindow(WebView window) {
                                dialog.dismiss();
                                newWebView.destroy();
                            }
                        });
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", "Disqus");
                        bundle.putString("href", view.getUrl());
                        bundle.putString("sdisqus", "null");
                        CommentsDetaliNewsFragment CommentsDetaliNewsFragment = new CommentsDetaliNewsFragment();
                        CommentsDetaliNewsFragment.setArguments(bundle);
                        ((MainActivity) getActivity()).replaceFragment(CommentsDetaliNewsFragment, true);
                        newWebView.destroy();
                    }
                }
            });
            ((WebView.WebViewTransport)resultMsg.obj).setWebView(newWebView);
            resultMsg.sendToTarget();
            return true;

        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig){
        Log.i(MainActivity.TAG, "onConfigurationChanged");
        super.onConfigurationChanged(newConfig);}
}

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.