How to handle Print Job event in Android?

Viewed 254

I am printing HTML document using WebViewClient. Doc

enter image description here

When this view opens, I want to handle onBackPress() (when user cancels the printing job). I tried to access printJob.isCancelled value to perform my operation but It's not working.

private fun createWebPrintJob(webView: WebView) {
    (this.getSystemService(Context.PRINT_SERVICE) as? PrintManager)?.let { printManager ->
        val jobName = "${getString(R.string.app_name)} Document"
        val printAdapter = webView.createPrintDocumentAdapter(jobName)
        printManager.print(
            jobName,
            printAdapter,
            PrintAttributes.Builder().build()
        ).also { printJob ->
            printAdapter.onFinish()
             if (printJob.isCancelled){
                 Toast.makeText(this,"Cancelled",Toast.LENGTH_SHORT).show()
                 startActivity(Intent(this,MainActivity::class.java))
            }
        }
    }
}

I am just calling webView() in onCreate

    fun webView() {
    val webView = WebView(this)
    webView.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ) = false
        override fun onPageFinished(view: WebView?, url: String?) {
            createWebPrintJob(view!!)
            mWebView = null
        }
    }
    val htmlDocument = HtmlString.pdfStr
    webView.loadDataWithBaseURL(null, htmlDocument, "text/HTML", "UTF-8", null)
    mWebView = webView
}
0 Answers
Related