DebugOpenWebView

AppCompatActivity, openWebView Debug/Test를 위한 화면

CommonWebViewController interface 를 상속받음

Handler

로딩시 보여지는 progress 바를 컨트롤 하기 위한 handler 객체

private val progressHandler : Handler by lazy {
    object: Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)

            if(msg?.what == LOADING_BAR_SHOW){
                layout_loading_bar?.visibility = View.VISIBLE
            }else if(msg?.what == LOADING_BAR_HIDE){
                layout_loading_bar?.visibility = View.GONE
            }

        }
    }
}

CommonWebViewInterface

History 관리

override var historyList: MutableList<WebHistory> = mutableListOf()//arrayList

FaceBook Login

override var facebookLogin: FaceBookLogin? = null

KaKao Login

override var kakaoLogin: KaKaoLogin? = null

Reload 관리

override var isEnabledReload: Boolean = false

LodingBar 보이기/ 숨기기

override fun showLoadingBar() {
    val msg = progressHandler.obtainMessage(LOADING_BAR_SHOW)
    progressHandler.sendMessage(msg)
}

override fun hideLoadingBar() {
    val msg = progressHandler.obtainMessage(LOADING_BAR_HIDE)
    progressHandler.sendMessage(msg)
}

뒤로가기

override fun backAction(){
    if(webview_debug_view?.canGoBack() == true){
        webview_debug_view?.goBack()
    }else{
        finishApp("종료하시겠습니까?")
    }
}

onCreate

  • Layout을 설정한다.

  • 하단 GNB 메뉴에 터치 listener를 설정한다.

  • Intent로 넘어온 URL 값을 받아와 webview에 로딩한다.

  • 권한을 체크한다.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_debug_open_web_view)

    layout_bottom_menu?.setOnTouchListener { _, _ ->
        true
    }
    layout_loading_bar?.setOnTouchListener { _, _ ->
        true
    }

    var baseUrl: String? = ""
    val bundle = intent.extras
    if (bundle != null) {
        baseUrl = bundle.getString("url")
    }
    webview_debug_view?.loadUrl(baseUrl)

    //TODO 권한체크 테스트
    //TEST 퍼미션 체크
    if(!getLocationCheckPermission() ||
        !getReadCheckPermission() ||
        !getWriteCheckPermission() ||
        !getCameraPermission() ||
        !getContactPermission() ||
        !getPhoneStatePermission()){

        requestPermission(this)
    }
}

onBackPressed

  • back 버튼을 눌렀을때 동작하는 것을 정의

  • history List가 비어있지 않고, 뒤로가기가 가능하면 이전 화면으로 이동한다.

  • history List가 비어있으면 종료 dialog를 띄운다.

override fun onBackPressed() {
    if(historyList.isNotEmpty()){
        val targetHistory: WebHistory = historyList[historyList.lastIndex]
        val url = targetHistory.url
        historyList.remove(targetHistory)
        webview_debug_view?.loadUrl(url)

    }else{
        if(webview_debug_view?.canGoBack() == true){
            webview_debug_view?.goBack()
        }else{
            finishApp("종료하시겠습니까?")
        }
    }
}

onActivityResult

  • RequestCode로 요청한 Acitivity 의 결과값을 받아 처리한다.

  • REQUEST_NEW_WEBVIEW_CALLBACK_OPEN : 화면을 이동하지 않고 로직처리 후 스크립트 호출

  • FILE_CHOOSER_REQUEST_CODE : 카메라, 갤러리에서 사진 호출

  • SNS 로그인 관련

override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
    super.onActivityResult(requestCode, resultCode, intent)

    when(requestCode){
        REQUEST_NEW_WEBVIEW_CALLBACK_OPEN ->{

            //new open webview 관련
            if(resultCode == Activity.RESULT_OK){
                val bund :Bundle? = intent?.extras
                bund?.let{
                    val func:String = bund["function"]!!.toString()
                    val param:String = bund["param"]!!.toString()
                    val jsonParam:JsonObject = Gson().fromJson(param, JsonObject::class.java)

                    val resultCallJs = "javascript:$func( ${jsonParam.toString()} )"
                    webview_debug_view?.loadUrl(resultCallJs)

                    Log.i(TAG, "resultCallJs: $resultCallJs")

                }
            }
        }
        FILE_CHOOSER_REQUEST_CODE ->{
            //camera, image pick 관련
            if (Build.VERSION.SDK_INT >= 21) {
                var results: Array<Uri?>? = null
                //Check if response is positive
                if (resultCode == Activity.RESULT_OK) {
                    if (requestCode == FILE_CHOOSER_REQUEST_CODE) {
                        if (webview_debug_view?.mUploadMessage2 == null) {
                            return
                        }
                        if (intent == null) {//카메라 캡쳐시
                            //Capture Photo if no image available
                            if (webview_debug_view?.mCM != null) {
                                results = arrayOf(Uri.parse(webview_debug_view?.mCM))
                            }
                        } else { //이미지선택시
                            val dataString = intent.dataString
                            val clipData = intent.clipData

                            //멀티선택
                            if (clipData != null) {
                                results = arrayOfNulls(clipData.itemCount)
                                for (i in 0 until clipData.itemCount) {
                                    val item = clipData.getItemAt(i)
                                    results[i] = item.uri
                                }
                            }

                            //단일선택
                            if (dataString != null) {
                                results = arrayOf(Uri.parse(dataString))
                            }

                        }
                    }
                }
                webview_debug_view?.mUploadMessage2!!.onReceiveValue(results)
                webview_debug_view?.mUploadMessage2 = null
            } else {
                if (requestCode == FILE_CHOOSER_REQUEST_CODE) {
                    if (null == webview_debug_view?.mUploadMessage) return
                    val result = if (intent == null || resultCode != Activity.RESULT_OK) null else intent.data
                    webview_debug_view?.mUploadMessage!!.onReceiveValue(result)
                    webview_debug_view?.mUploadMessage = null
                }
            }
        }else -> {
            //...
            //로그인관련
            //kakao
            if (Session.getCurrentSession().handleActivityResult(requestCode, resultCode, intent)) {
                return
            }else{ //facebook
                facebookLogin?.onActivityResult(requestCode, resultCode, intent)
            }

        }
    } //when end

}

onRequestPermissioResult

  • 권한 동의창 콜백 함수

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)

    when (requestCode) {
        PERM_REQUEST_CODE ->
        if (grantResults.isNotEmpty()) {
            //위치권한동의 여부 확인
            val locationAgree: Boolean = grantResults[0] == PackageManager.PERMISSION_GRANTED
            val fileWriteAgree: Boolean = grantResults[1] == PackageManager.PERMISSION_GRANTED
            val fileReadAgree: Boolean = grantResults[2] == PackageManager.PERMISSION_GRANTED
            //...

            if (locationAgree && fileWriteAgree && fileReadAgree) { //동의했다면
                //동의했을때 작업
            }else { // 하나라도 하지않았다면
                //TODO 거부했을때 로직 확인, 다시보지않기 등등

                //다시보지않기...거부 처리
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
                        Log.i(TAG,"ACCESS_FINE_LOCATION Permission denied - don't ask again")
                        return
                    }
                    if (!shouldShowRequestPermissionRationale(READ_EXTERNAL_STORAGE)) {
                        Log.i(TAG,"READ_EXTERNAL_STORAGE Permission denied - don't ask again")
                        return
                    }
                    if (!shouldShowRequestPermissionRationale(WRITE_EXTERNAL_STORAGE)) {
                        Log.i(TAG,"WRITE_EXTERNAL_STORAGE Permission denied - don't ask again")
                        return
                    }
                    //...
                }

                //그냥 거부했다면
                Toast.makeText(this, "권한 체크 거부", Toast.LENGTH_SHORT).show()

            }
        }
    }//when end
}

onDestory

  • 로그인 세션을 만료시킨다.

override fun onDestroy() {
    super.onDestroy()

    kakaoLogin?.Logout()
    facebookLogin?.Logout()
}

Last updated

Was this helpful?