Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavascriptInterface annotation for JELLY_BEAN and below

Tags:

java

android

As clearly noted on official docs, usage of @JavascriptInterface is needed for API level JELLY_BEAN_MR1 and above, to access a java function from the webview side.

This means that Project Build Target must point to API 17 or above which resolves the following import:

import android.webkit.JavascriptInterface;

How does android handles this code for API 16 and below? Will I get a runtime exception or does it ignore this import on runtime?

like image 993
Serkan Arıkuşu Avatar asked Jan 13 '23 11:01

Serkan Arıkuşu


1 Answers

I'm quite surprised with these answers... they are not accurate. If you add the JavascriptInterface and another annotation lets say MyAnnotation to the same method(like I did), and then try to access the MyAnnotation instance annotation then you are in for a ClassDefNotFoundException surprise!

My solution which seems to work for now (it has been more than a year), is to add the annotation declaration to the application project:

package android.webkit;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface JavascriptInterface {}

This solved the problem on 2.3.5, and still worked on 4.3 and 4.4 and 4.2.

Hope this helps someone else!

like image 154
TacB0sS Avatar answered Jan 24 '23 08:01

TacB0sS