SSL Error Handler hatası çözümü... - R10.net
  • 22-11-2020, 22:00:23
    #1
    Arkadaşlar merhaba,
    Google son sürümde böyle bir hata maili attı bana;
    Biraz araştırdım böyle bir çözüm buldum;
    https://stackoverflow.com/questions/...of-onreceiveds

    Ama nasıl uygulayacağımı bilemedim. Sanırım WebViewFragment.kt dosyasına eklenecek bu kodlar. Nasıl eklemem gerekir? Çözüm sunan dostlara şimdiden teşekkürler...

    WebViewFragment.kt dosyası;
    (İndirmek için: https://dosya.co/b80efj7q1wu4/WebViewFragment.kt.html)
    package com.sabah.deprembs.ui
    
    import android.Manifest
    import android.annotation.SuppressLint
    import android.content.ActivityNotFoundException
    import android.content.Intent
    import android.content.pm.PackageManager
    import android.graphics.Bitmap
    import android.net.http.SslError
    import android.os.Build
    import android.os.Bundle
    import android.os.Handler
    import android.view.*
    import android.webkit.SslErrorHandler
    import android.webkit.WebView
    import android.webkit.WebViewClient
    import android.widget.ProgressBar
    import android.widget.Toast
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    import androidx.fragment.app.Fragment
    import com.sabah.deprembs.R
    import com.sabah.deprembs.helpers.BitmapHelper
    import kotlinx.coroutines.runBlocking
    import kotlinx.coroutines.withTimeout
    import java.io.ByteArrayOutputStream
    import java.util.*
    
    
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private const val ARG_URL = "url"
    private const val ARG_IS_MAP = "is_map"
    private const val ARG_EARTHQUAKE_LOCATION = "earthquake_location"
    
    
    /**
     * A simple [Fragment] subclass.
     * Use the [mWebViewFragment.newInstance] factory method to
     * create an instance of this fragment.
     */
    class WebViewFragment : Fragment(), IOnBackPressed {
        // TODO: Rename and change types of parameters
        private var url: String? = null
        private var isMap: Boolean = false
        private var earthquakeLocation: String? = null
        private var REQUEST_PERMISSION: Int = 10001
        private lateinit var mWebView: WebView
        private lateinit var mProgressBar: ProgressBar
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            arguments?.let {
                url = it.getString(ARG_URL)
                isMap = it.getBoolean(ARG_IS_MAP)
                earthquakeLocation = it.getString(ARG_EARTHQUAKE_LOCATION)
    
            }
        }
    
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                                  savedInstanceState: Bundle?): View? {
            // Inflate the layout for this fragment
            val view = inflater.inflate(R.layout.fragment_web_view, container, false)
            mWebView = view.findViewById(R.id.mWebView)
            mProgressBar = view.findViewById(R.id.progressBar_cyclic)
            showLoading()
            if (isMap) setHasOptionsMenu(true)
    
            Handler().postDelayed({
                mWebView.stopLoading()
            }, 2500)
            return view
        }
    
        @SuppressLint("SetJavaScriptEnabled")
        private fun showLoading() {
            mWebView.visibility = View.INVISIBLE
            mWebView.loadUrl(url)
            mWebView.settings.javaScriptEnabled = true // enable javascript
            mWebView.settings.loadWithOverviewMode = true
            mWebView.settings.useWideViewPort = true
            mWebView.settings.builtInZoomControls = true
            mWebView.webViewClient = object : WebViewClient() {
                override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
                    Toast.makeText(context, description, Toast.LENGTH_SHORT).show()
                }
    
                override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
                    mProgressBar.visibility = View.VISIBLE
                    mWebView.visibility = View.VISIBLE
                    mProgressBar.visibility = View.GONE
                }
    
                override fun onPageFinished(view: WebView, url: String) {
                    removeHeader()
                    mProgressBar.visibility = View.GONE
                    mWebView.visibility = View.VISIBLE
    
                }
    
                override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler, er: SslError?) {
                    handler.proceed() // Ignore SSL certificate errors
                }
            }
        }
    
        private fun removeHeader() {
            mWebView.loadUrl(
                    "javascript:(function() { " +
                            "document.getElementById('deprem_liste').style.marginTop = '0px'; " +
                            "document.getElementById('map').style.marginTop = '-60px'; " +
                            "var element = document.getElementById('baslik');"
                            + "element.parentNode.removeChild(element);" +
                            "})()")
        }
    
        fun reload() {
            mWebView.reload();
        }
    
        fun canGoBack(): Boolean {
            return mWebView.canGoBack()
        }
    
        fun goBack() {
            mWebView.goBack()
        }
    
        override fun onBackPressed(): Boolean {
            TODO("Not yet implemented")
        }
    
        override fun onOptionsItemSelected(item: MenuItem): Boolean {
            if (item.itemId == R.id.action_paylas) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                        && ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                            REQUEST_PERMISSION)
    
                } else {
                    shareBitmap()
                }
            }
            return super.onOptionsItemSelected(item)
        }
    
        override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
            val item = menu.findItem(R.id.action_paylas)
            item.isVisible = isMap
            return super.onCreateOptionsMenu(menu, inflater)
        }
    
        private fun shareBitmap() {
            val i = Intent(Intent.ACTION_SEND)
            i.type = "image/*"
            val stream = ByteArrayOutputStream()
            var bitmapHelper = BitmapHelper()
    
            i.putExtra(Intent.EXTRA_STREAM, bitmapHelper.getImageUri(requireContext(), bitmapHelper.getBitmapFromView(mWebView)!!))
            i.putExtra(Intent.EXTRA_TEXT, "Deprem oldu. Yer: $earthquakeLocation")
            try {
                startActivity(Intent.createChooser(i, "Deprem Bilgisi Paylaş"))
            } catch (ex: ActivityNotFoundException) {
                ex.printStackTrace()
            }
        }
    
        override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                                grantResults: IntArray) {
            when (requestCode) {
                REQUEST_PERMISSION -> {
                    if (grantResults.isNotEmpty() && grantResults[0] ==
                            PackageManager.PERMISSION_GRANTED) {
                        if ((ContextCompat.checkSelfPermission(requireContext(),
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE) ===
                                        PackageManager.PERMISSION_GRANTED)) {
                            shareBitmap()
                        }
                    } else {
                        Toast.makeText(requireContext(), "Erişim izni reddedildi", Toast.LENGTH_SHORT).show()
                    }
                    return
                }
            }
        }
    
        companion object {
            /**
             * Use this factory method to create a new instance of
             * this fragment using the provided parameters.
             *
             * @param url Parameter 1.
    
             * @return A new instance of fragment mWebViewFragment.
             */
            // TODO: Rename and change types and number of parameters
            @JvmStatic
            fun newInstance(url: String) =
                    WebViewFragment().apply {
                        arguments = Bundle().apply {
                            putString(ARG_URL, url)
                            putBoolean(ARG_IS_MAP, false)
    
                        }
                    }
    
            @JvmStatic
            fun newInstanceMap(url: String, earthquakeLocation: String) =
                    WebViewFragment().apply {
                        arguments = Bundle().apply {
                            putString(ARG_URL, url)
                            putString(ARG_EARTHQUAKE_LOCATION, earthquakeLocation)
                            putBoolean(ARG_IS_MAP, true)
                        }
                    }
        }
    
    }
    sabahtasarim.com | bilgi@sabahtasarim.com