diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4f20f7b --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +# Built application files +*.apk +*.ap_ + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/ + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild + +# Google Services (e.g. APIs or Firebase) +google-services.json diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..2cec031 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Norsk Rikskringkasting (NRK) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..2bae8e6 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# Native Bridge Android + +The Android library is written in Kotlin. + +## Download +Add the dependency to your app level build.gradle file: +```java +dependencies { + compile 'no.nrk.nativebridge:nativebridge:1.0.0-SNAPSHOT' +} +``` + +Note that the library has a dependency on Jackson. + +## Usage +Instead of using ```android.webkit.WebView```, use ```no.nrk.NativeBridgeWebView```. If you're already extending ```WebView```, you must instead extend ```NativeBridgeWebView```. + +Create classes implementing the ```TopicData.In``` and ```TopicData.Out``` interfaces. ```TopicData.In``` corresponds to the JSON received _from_ the webview, while ```TopicData.Out``` corresponds to the data we want to pass _to_ the webview. + +Register a handler for the datatype, and you've successfully established a bridge between your app and the webview: +```java +webview.connection.addHandler("someTopic", { _ : SomeTopic.In, connection -> + connection.send("someTopic", SomeTopic.Out("data")) + } +) +``` diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..3a52685 --- /dev/null +++ b/build.gradle @@ -0,0 +1,27 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + ext.kotlin_version = '1.2.0' + repositories { + google() + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:3.0.1' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..8430bf1 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +org.gradle.jvmargs=-Xmx1536m +VERSION_NAME=1.0.0-SNAPSHOT +VERSION_CODE=1 +GROUP=no.nrk.nativebridge + +POM_DESCRIPTION=A RPC like bridge for communication between webviews and native apps +POM_URL=https://github.com/nrkno/nativebridge-android +POM_SCM_URL=https://github.com/nrkno/nativebridge-android +POM_SCM_CONNECTION=scm:git@github.com:nrkno/nativebridge-android.git +POM_SCM_DEV_CONNECTION=scm:git@github.com:nrkno/nativebridge-android.git + +POM_LICENCE_NAME=MIT License +POM_LICENCE_URL=http://opensource.org/licenses/MIT +POM_LICENCE_DIST=repo + +POM_DEVELOPER_ID=nrk +POM_DEVELOPER_NAME=Norsk Rikskringkasting (NRK) +POM_EMAIL=opensource@nrk.no \ No newline at end of file diff --git a/gradle/gradle-mvn-push.gradle b/gradle/gradle-mvn-push.gradle new file mode 100644 index 0000000..ee3cd68 --- /dev/null +++ b/gradle/gradle-mvn-push.gradle @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Chris Banes + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +apply plugin: 'maven' +apply plugin: 'signing' + +def isReleaseBuild() { + return !VERSION_NAME.contains("SNAPSHOT") +} + +def getRepositoryUsername() { + return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : "" +} + +def getRepositoryPassword() { + return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : "" +} + +afterEvaluate { project -> + uploadArchives { + repositories { + mavenDeployer { + beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } + + pom.groupId = GROUP + pom.artifactId = POM_ARTIFACT_ID + pom.version = VERSION_NAME + + repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + + pom.project { + name POM_NAME + packaging POM_PACKAGING + description POM_DESCRIPTION + url POM_URL + + scm { + url POM_SCM_URL + connection POM_SCM_CONNECTION + developerConnection POM_SCM_DEV_CONNECTION + } + + licenses { + license { + name POM_LICENCE_NAME + url POM_LICENCE_URL + distribution POM_LICENCE_DIST + } + } + + developers { + developer { + id POM_DEVELOPER_ID + name POM_DEVELOPER_NAME + } + } + } + } + } + } + + signing { + required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } + sign configurations.archives + } + + task androidSourcesJar(type: Jar) { + classifier = 'sources' + from android.sourceSets.main.java.sourceFiles + } + + artifacts { + archives androidSourcesJar + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..13372ae Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c35ba4b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Nov 10 15:05:43 CET 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..9d82f78 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..8a0b282 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/native-bridge-sample/.gitignore b/native-bridge-sample/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/native-bridge-sample/.gitignore @@ -0,0 +1 @@ +/build diff --git a/native-bridge-sample/build.gradle b/native-bridge-sample/build.gradle new file mode 100644 index 0000000..ddcffc6 --- /dev/null +++ b/native-bridge-sample/build.gradle @@ -0,0 +1,28 @@ +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' + +android { + compileSdkVersion 27 + + defaultConfig { + applicationId "no.nrk.nativebridge.sample" + minSdkVersion 17 + targetSdkVersion 27 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + + } +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" + implementation 'com.android.support:appcompat-v7:27.0.2' + implementation 'com.android.support.constraint:constraint-layout:1.0.2' + implementation project(':native-bridge') + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.1' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' +} diff --git a/native-bridge-sample/lint.xml b/native-bridge-sample/lint.xml new file mode 100644 index 0000000..3116230 --- /dev/null +++ b/native-bridge-sample/lint.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/native-bridge-sample/proguard-rules.pro b/native-bridge-sample/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/native-bridge-sample/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/native-bridge-sample/src/androidTest/java/no/nrk/nativebridge/sample/WebViewConnectionTest.kt b/native-bridge-sample/src/androidTest/java/no/nrk/nativebridge/sample/WebViewConnectionTest.kt new file mode 100644 index 0000000..a03a983 --- /dev/null +++ b/native-bridge-sample/src/androidTest/java/no/nrk/nativebridge/sample/WebViewConnectionTest.kt @@ -0,0 +1,160 @@ +package no.nrk.nativebridge.sample; + +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.module.kotlin.KotlinModule +import no.nrk.nativebridge.* +import no.nrk.nativebridge.sample.topicdata.TestTopicData +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class WebViewConnectionTest { + + private val mapper = ObjectMapper().registerModule(KotlinModule())!! + + /** + * Tests that sending valid data from webview to native works as expected + */ + @Test + fun testSendSuccessful(){ + val javascript = getJavaScript("testTopic", TestTopicData.Out("someText")) + + val connection = WebViewConnection(mapper, object: JavascriptExecutor{ + override fun executeJavascript(script: String) { + assertEquals(javascript, script) + } + }) + + connection.send("testTopic", TestTopicData.Out("someText")) + } + + /** + * Tests that receiving valid data from webview works as expected + */ + @Test + fun testReceiveSuccessful(){ + val connection = WebViewConnection(mapper, object: JavascriptExecutor{ + override fun executeJavascript(script: String) { + /** no-op */ + } + }) + + val javascript = """{"topic":"testTopic","data":{"text":"someText"}}""".trimIndent() + + connection.addHandler("testTopic", { data: TestTopicData.In, _ -> + assertEquals("someText", data.text) + }) + + connection.receive(javascript) + } + + /** + * Tests that error is returned when payload doesn't contain "topic" object + */ + @Test + fun testMissingFieldTopicShouldReturnError(){ + val javascript = """{"data":{"key":"value"}}""".trimIndent() + + val connection = WebViewConnection(mapper, object: JavascriptExecutor{ + override fun executeJavascript(script: String) { + assertTrue(script.contains(WebViewConnectionError.MissingFieldTopic().message)) + } + }) + + connection.receive(javascript) + } + + + /** + * Tests that error is returned when payload doesn't contain "data" object + */ + @Test + fun testMissingFieldDataShouldReturnError(){ + val javascript = """{"topic":"testTopic"}""".trimIndent() + + val connection = WebViewConnection(mapper, object: JavascriptExecutor{ + override fun executeJavascript(script: String) { + assertTrue(script.contains(WebViewConnectionError.MissingFieldData().message)) + } + }) + + connection.receive(javascript) + } + + /** + * Tests that error is returned when payload isn't valid JSON + */ + @Test + fun testIllegalPayloadResultsInError(){ + val javascript = """abc""".trimIndent() + + val connection = WebViewConnection(mapper, object: JavascriptExecutor{ + override fun executeJavascript(script: String) { + assertTrue(script.contains(WebViewConnectionError.IllegalPayloadFormat().message)) + } + }) + + connection.receive(javascript) + } + + /** + * Tests that error is returned when a topic handler for specified "topic" hasn't been added + */ + @Test + fun testMissingTopicHandlerShouldReturnError(){ + val javascript = """{"topic":"invalid","data":{"key":"value"}}""".trimIndent() + + val connection = WebViewConnection(mapper, object: JavascriptExecutor{ + override fun executeJavascript(script: String) { + assertTrue(script.contains(""""topic":"invalid""") && script.contains(WebViewConnectionError.MissingTopicHandler().message)) + } + }) + + connection.receive(javascript) + } + + /** + * Tests that error is returned when payload contains data that is unrecognizable. This will happen + * if the data object has @JsonProperty(required = true) field annotations that isn't satisfied. + */ + @Test + fun testInvalidDataForHandlerShouldReturnError(){ + val connection = WebViewConnection(mapper, object: JavascriptExecutor{ + override fun executeJavascript(script: String) { + assertTrue(script.contains(""""topic":"testTopic"""") + && script.contains(WebViewConnectionError.InvalidDataForTopicHandler("testTopic").message)) + } + }) + + val javascript = """{"topic":"testTopic","data":{"texttt":"someTextForInvalidKey"}}""".trimIndent() + + connection.addHandler("testTopic", { _: TestTopicData.In, _ -> + /** no-op */ + }) + + connection.receive(javascript) + } + + private fun getJavaScript(topic: String, expectedTopicData: TopicData.Out) : String { + val json = JSONObject() + + val jsonData = mapper.writeValueAsString(expectedTopicData) + val jsonDataObject = JSONObject(jsonData) + + json.put("topic", topic) + json.put("data", jsonDataObject) + + val javascript = + """ + javascript:window.dispatchEvent( + new CustomEvent("nativebridge", { + "detail": $json + } + ) + ) + """.trimIndent() + + return javascript + } +} diff --git a/native-bridge-sample/src/main/AndroidManifest.xml b/native-bridge-sample/src/main/AndroidManifest.xml new file mode 100644 index 0000000..dba0f83 --- /dev/null +++ b/native-bridge-sample/src/main/AndroidManifest.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/native-bridge-sample/src/main/java/no/nrk/nativebridge/sample/WebViewActivity.kt b/native-bridge-sample/src/main/java/no/nrk/nativebridge/sample/WebViewActivity.kt new file mode 100644 index 0000000..3b5ea31 --- /dev/null +++ b/native-bridge-sample/src/main/java/no/nrk/nativebridge/sample/WebViewActivity.kt @@ -0,0 +1,47 @@ +package no.nrk.nativebridge.sample + +import android.content.SharedPreferences +import android.os.Build +import android.support.v7.app.AppCompatActivity +import android.os.Bundle +import android.webkit.WebView.setWebContentsDebuggingEnabled +import android.webkit.WebViewClient +import kotlinx.android.synthetic.main.activity_main.* +import no.nrk.nativebridge.sample.topicdata.GaConfTopicData + + +class WebViewActivity : AppCompatActivity() { + + lateinit private var prefs: SharedPreferences + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + prefs = getPreferences(android.content.Context.MODE_PRIVATE) + + val url = prefs.getString("url", "http://10.0.2.2:8080") + etUrl.setText(url) + + webview?.apply { + connection.addHandler("gaConf", { _ : GaConfTopicData.In, connection -> + val gaConf = GaConfTopicData.Out("35009a79-1a05-49d7-b876-2b884d0f825b") + connection.send("gaConf", gaConf) + } + ) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + setWebContentsDebuggingEnabled(true) + } + + webViewClient = WebViewClient() + loadUrl(url) + } + + btnSetUrl.setOnClickListener { + val etUrl = etUrl.text.toString() + prefs.edit().putString("url", etUrl).apply() + + webview.loadUrl(etUrl) + } + } +} diff --git a/native-bridge-sample/src/main/java/no/nrk/nativebridge/sample/topicdata/GaConfTopicData.kt b/native-bridge-sample/src/main/java/no/nrk/nativebridge/sample/topicdata/GaConfTopicData.kt new file mode 100644 index 0000000..1441563 --- /dev/null +++ b/native-bridge-sample/src/main/java/no/nrk/nativebridge/sample/topicdata/GaConfTopicData.kt @@ -0,0 +1,8 @@ +package no.nrk.nativebridge.sample.topicdata + +import no.nrk.nativebridge.TopicData + +class GaConfTopicData { + class In : TopicData.In + class Out(val cid: String) : TopicData.Out +} \ No newline at end of file diff --git a/native-bridge-sample/src/main/java/no/nrk/nativebridge/sample/topicdata/TestTopicData.kt b/native-bridge-sample/src/main/java/no/nrk/nativebridge/sample/topicdata/TestTopicData.kt new file mode 100644 index 0000000..7bc0741 --- /dev/null +++ b/native-bridge-sample/src/main/java/no/nrk/nativebridge/sample/topicdata/TestTopicData.kt @@ -0,0 +1,10 @@ +package no.nrk.nativebridge.sample.topicdata; + +import com.fasterxml.jackson.annotation.JsonProperty +import no.nrk.nativebridge.TopicData + +class TestTopicData { + class In(@JsonProperty(required = true) val text: String) : TopicData.In + class Out(val value: String) : TopicData.Out +} + diff --git a/native-bridge-sample/src/main/res/drawable-v24/ic_launcher_foreground.xml b/native-bridge-sample/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..c7bd21d --- /dev/null +++ b/native-bridge-sample/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/native-bridge-sample/src/main/res/drawable/ic_launcher_background.xml b/native-bridge-sample/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..d5fccc5 --- /dev/null +++ b/native-bridge-sample/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/native-bridge-sample/src/main/res/layout/activity_main.xml b/native-bridge-sample/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..0ebd5f6 --- /dev/null +++ b/native-bridge-sample/src/main/res/layout/activity_main.xml @@ -0,0 +1,49 @@ + + + + + + + +