How to enable full screen control in android webview?

0

I know the WebChromeClient has to implement OnShowCustomView and OnHideCustomView. I couldn't figure out it exactly. Here is the mainactivity.java. Note that there are html files with links to videos which are being used in webview. I have excluded routine imports in the following.

I know the WebChromeClient has to implement OnShowCustomView and OnHideCustomView.I couldn 't figure out it exactly. Here is the mainactivity.java. Note that there are html files with links to videos which are being used in webview. I have excluded routine imports in the following.

public class MainActivity extends AppCompatActivity {

    private ValueCallback < Uri > mUploadMessage;
    private Uri mCapturedImageURI = null;
    private ValueCallback < Uri[] > mFilePathCallback;
    private String mCameraPhotoPath;
    private static final int INPUT_FILE_REQUEST_CODE = 1;
    private static final int FILECHOOSER_RESULTCODE = 1;

    Toolbar toolbar;

    ListView list;

    //The main content display
    WebView webView;

    DrawerLayout drawerLayout;

    MenuItem refreshButton;

    TabLayout tabs;

    ProgressBar progressBar;

    //The actual displayed page
    static Pages actual = null;


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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        list = (ListView) findViewById(R.id.listView);
        webView = (WebView) findViewById(R.id.webView);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setMax(100);
        progressBar.setProgress(50);
        requestAppPermissions();

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);


        webSettings.setPluginState(PluginState.ON);
        webSettings.setAllowFileAccess(true);
        webSettings.setLoadWithOverviewMode(true);

        webSettings.setAppCacheEnabled(true);
        webSettings.setDomStorageEnabled(true);

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                getWindow().setTitle(title); //Set Activity tile to page title.
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                getWindow().setTitle(title); //Set Activity tile to page title.
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }


        });


        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                view.loadData(actual.error, "text/html", actual.localEncoding);
            }

        });


        webView.setDownloadListener(new DownloadListener() {
            public boolean haveStoragePermission() {
                if (Build.VERSION.SDK_INT >= 23) {
                    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                        PackageManager.PERMISSION_GRANTED) {
                        Log.e("Permission error", "You have permission");
                        return true;
                    } else {

                        Log.e("Permission error", "You have asked for permission");

                        return false;
                    }
                } else { //you dont need to worry about these stuff below api level 23
                    Log.e("Permission error", "You already have the permission");
                    return true;
                }
            }
            @Override

            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                request.setMimeType(mimeType);

                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies); -
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading file...");
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
            }
        });

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        tabs = (TabLayout) findViewById(R.id.tabs);


        hideTabs();

        //Listener to receive tab changes
        tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            //User selected new tab
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                //Find page
                for (Pages p: Pages.values()) {
                    if (p.title.equals(actual.title)) {

                        //Load URL in webview
                        if (actual.url != null)
                            actual.actualURL = p.url.split("\\|\\|")[tab.getPosition()];
                        if (actual.localPage != null)
                            actual.actualAlternativeURL = actual.localPage.split("\\|\\|")[tab.getPosition()];
                    }

                }
                if (actual.url != null) {
                    webView.loadUrl(actual.actualURL);
                } else {
                    if (actual.localPage != null)
                        webView.loadUrl("file:///android_asset/" + actual.actualAlternativeURL);
                }
            }

            //We don't need this methods
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });

        /*
         Drawer items
         */

        //Create list of all items for the drawer
        final ArrayList < Pages > pages = new ArrayList < Pages > ();
        for (Pages p: Pages.values()) {
            if (p.menu == false)
                pages.add(p);

        }

        //Set actual page to the first item
        if (actual == null) {
            actual = pages.get(0);
        }

        /*
        White design
        */
        if (actual.useWhiteFont) {
            toolbar.setTitleTextColor(0xFFFFFFFF);
            tabs.setTabTextColors(0xFFFFFFFF, 0xFFFFFFFF);
        }

        /*
         Toolbar
         */
        toolbar.setTitle(actual.title);
        setSupportActionBar(toolbar);

        /*
         Admob
         */
        AdView mAdView = (AdView) findViewById(R.id.adView);

        //Hide AdView when not needed
        if (!actual.useAds) {
            mAdView.setVisibility(View.INVISIBLE);
        } else {
            //Init AdView when needed
            AdRequest adRequest = new AdRequest.Builder().build();
            mAdView.loadAd(adRequest);
        }

        /*
         Drawer
         */
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close
        );
        drawerLayout.setDrawerListener(mDrawerToggle);
        drawerLayout.setDrawerShadow(R.drawable.shadow, Gravity.LEFT);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        mDrawerToggle.syncState();

        /*
         Pages to drawer
         */

        //Add pages to the drawer
        ListAdapter adapter = new ListAdapter(this, pages);
        list.setAdapter(adapter);
        adapter.notifyDataSetChanged();


        webView.getSettings().setJavaScriptEnabled(true);


        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int progress) {
                progressBar.setProgress(progress);
                if (progress == 100) {
                    progressBar.setVisibility(View.GONE);

                } else {
                    progressBar.setVisibility(View.VISIBLE);

                }
            }


            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if ((url.contains("http:") || url.contains("https:")) && actual.homeDomains.contains(URI.create(url).getHost())) {
                    view.loadUrl(url);
                    return false;
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                    PackageManager manager = getPackageManager();
                    List < ResolveInfo > infos = manager.queryIntentActivities(intent, 0);
                    if (infos.size() > 0) {
                        startActivity(intent);
                    }
                    return true;
                }

            }

            //Needed for correct back-button functionality

            public void onPageFinished(WebView view, String url) {
                webView.clearHistory();

            }





            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 = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES);
                File imageFile = File.createTempFile(
                    imageFileName, /* prefix */
                    ".jpg", /* suffix */
                    storageDir /* directory */
                );
                return imageFile;
            }

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

                    // 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), "AndroidExampleFolder");

                if (!imageStorageDir.exists()) {
                    // Create AndroidExampleFolder at sdcard
                    imageStorageDir.mkdirs();
                }
                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);


            }

        });

        /*
         Site listener
         */


        //Change page via drawer
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
                changePage(pages.get(position));
            }
        });

        /*
         Update
         */

        //Load actual (first) page
        changePage(actual);
    }

    /*
     Tabs
     */
    //Show the TabView
    void showTabs() {
        tabs.getLayoutParams().height = TabLayout.LayoutParams.WRAP_CONTENT;
    }

    //Hide the TabView
    void hideTabs() {
        tabs.removeAllTabs();
        tabs.getLayoutParams().height = 0;
    }


    //Change the page
    //Update Webview, Toolbar, Refresh button...
    void changePage(Pages newPage) {
        actual = newPage;

        //Handle tabs
        tabs.removeAllTabs();
        if (newPage.tabs != null && newPage.tabs.contains("||")) {
            showTabs();
            for (String s: newPage.tabs.split("\\|\\|")) {
                tabs.addTab(tabs.newTab().setText(s));
            }
            if (newPage.url != null) {
                newPage.actualURL = newPage.url.split("\\|\\|")[0];
            }
            if (newPage.localPage != null) {
                newPage.actualAlternativeURL = newPage.localPage.split("\\|\\|")[0];
            }

            //There are no tabs...
        } else {
            hideTabs();
            newPage.actualURL = newPage.url;
            newPage.actualAlternativeURL = newPage.localPage;
        }


        //Enable JS for the webview
        webView.getSettings().setJavaScriptEnabled(true);

        //Load URL to the webview...
        if (newPage.url != null) {
            webView.loadUrl(newPage.actualURL);
        } else {
            if (newPage.localPage != null) //...Or use local page
                webView.loadUrl("file:///android_asset/" + newPage.actualAlternativeURL);
        }


        //Update Toolbar and Statusbar
        toolbar.setBackgroundColor(newPage.actionBarColor.value);
        drawerLayout.setBackgroundColor(newPage.actionBarColor.value);
        drawerLayout.closeDrawers();
        toolbar.setTitle(newPage.title);

        //Show refresh button
        if (refreshButton != null) {
            if (newPage.refreshButton) {
                refreshButton.setVisible(true);
            } else {
                refreshButton.setVisible(false);
            }
        }

        actual = newPage;
    }

    //Create OptionsMenu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        //Create the menu
        getMenuInflater().inflate(R.menu.main, menu);

        //Add pages to the menu
        for (Pages p: Pages.values()) {
            if (p.menu != false)
                menu.add(p.title);
        }

        //Refresh button
        refreshButton = menu.add(R.string.refresh);
        if (actual.useWhiteFont) {
            refreshButton.setIcon(R.drawable.ic_autorenew_white_36dp);
        } else {
            refreshButton.setIcon(R.drawable.ic_autorenew_black_36dp);
        }
        refreshButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        //Share button
        if (Pages.values()[0].share) {
            MenuItem shareItem = menu.add(getString(R.string.share));
            if (actual.shareAsAction) {
                if (actual.useWhiteFont)
                    shareItem.setIcon(R.drawable.ic_share_white_36dp);
                else
                    shareItem.setIcon(R.drawable.ic_share_black_36dp);
                shareItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            }
        }

        //Show/hide refresh button for the first page
        if (actual != null) {
            if (actual.refreshButton) {
                refreshButton.setVisible(true);
            } else {
                refreshButton.setVisible(false);
            }
        }
        return true;
    }


    //Handle back-button
    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {

            new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Closing App")
                .setMessage("Are you sure you want to exit this application?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        finishAndRemoveTask();

                    }

                })
                .setNegativeButton("No", null)
                .show();


        }
    }



    //Handle menu-clicks
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        //Share
        if (item.getTitle().toString().equals(getString(R.string.share))) {
            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Pages.values()[0].shareText);
            sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
            startActivity(Intent.createChooser(sharingIntent, getString(R.string.share_using)));
            return super.onOptionsItemSelected(item);
        }

        //Refresh
        if (item.getTitle().toString().equals(getString(R.string.refresh))) {
            if (actual.url != null) {
                System.out.println(actual.url);
                webView.reload();
                webView.loadUrl(actual.url);
            }
            return super.onOptionsItemSelected(item);
        }

        //Page
        for (Pages p: Pages.values()) {
            if (p.title.equals(item.getTitle().toString())) {
                if (p.url.contains("http:") || p.url.contains("https:")) {
                    changePage(p);
                } else {

                    //Handle special Intents (e.g. for mailto: in the menu)

                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(p.url));
                    PackageManager manager = getPackageManager();
                    List < ResolveInfo > infos = manager.queryIntentActivities(intent, 0);
                    if (infos.size() > 0) {
                        startActivity(intent);
                    }


                }

            }
        }
        return super.onOptionsItemSelected(item);
        /*mycode begins*/


    }

    /*mycode ends*/
    public void rateMe(View view) {
        try {
            startActivity(new Intent(Intent.ACTION_VIEW,
                Uri.parse("market://details?id=" + this.getPackageName())));
        } catch (android.content.ActivityNotFoundException e) {
            startActivity(new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://play.google.com/store/apps/details?id=" + this.getPackageName())));
        }
    }

    public void exitMe(View view) {

        new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Closing App")
            .setMessage("Are you sure you want to exit this application?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    finishAndRemoveTask();
                    System.exit(0);
                }

            })
            .setNegativeButton("No", null)
            .show();

    }









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


}
java
android
webview
android-webview
asked on Stack Overflow May 9, 2019 by Maths89 • edited May 9, 2019 by Zoe

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0