Search code examples
androidkotlinwebview

Problem to get the context of activity in WebAppInterface class


I have an Android app in Kotlin with a Webview. Now i want to communicate from the website to the native app via Javascript.

What i want to achieve is to manipulate the brightness of the Tablet. My Code is (shorten):

public class FullscreenActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val webView = findViewById<WebView>(R.id.webView)
        webView.addJavascriptInterface(WebAppInterface(this), "Android")
    }

    public fun jsmessage() {
        val lp = this.window.attributes
        lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF
        this.window.attributes = lp
    }
}
public class WebAppInterface(mContext: Context) {
    @JavascriptInterface
    public fun message(data: String) {
        Log.d("TAG", data)
        ((FullscreenActivity)mContext).jsmessage() <-- Here is the error
    }
}

But i'll get the error 'Unresolved reference: mContext'. Can someone explain me how i can achieve what i want?

Thanks.


Solution

  • (context as MainActivity).brightness(data.toInt())
    

    I've asked Copilot and this seems to be the solution which worked for me.