Commit fadee507 by 王一诺

webClient 使用jni 改写

parents
Showing with 3088 additions and 0 deletions
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
# Default ignored files
/shelf/
/workspace.xml
WebViewDemo
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AndroidProjectSystem">
<option name="providerId" value="com.android.tools.idea.GradleProjectSystem" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="21" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetSelector">
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
<SelectionState runConfigName="libwebview">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
<SelectionState runConfigName="sdk">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
</selectionStates>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="CHOOSE_PER_TEST" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/libwebview" />
<option value="$PROJECT_DIR$/sdk" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectMigrations">
<option name="MigrateToGradleLocalJavaHome">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="com.intellij.execution.junit.AbstractAllInDirectoryConfigurationProducer" />
<option value="com.intellij.execution.junit.AllInPackageConfigurationProducer" />
<option value="com.intellij.execution.junit.PatternConfigurationProducer" />
<option value="com.intellij.execution.junit.TestInClassConfigurationProducer" />
<option value="com.intellij.execution.junit.UniqueIdConfigurationProducer" />
<option value="com.intellij.execution.junit.testDiscovery.JUnitTestDiscoveryConfigurationProducer" />
<option value="org.jetbrains.kotlin.idea.junit.KotlinJUnitRunConfigurationProducer" />
<option value="org.jetbrains.kotlin.idea.junit.KotlinPatternConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
/build
\ No newline at end of file
plugins {
alias(libs.plugins.android.application)
}
android {
namespace 'com.coolook.webview.demo'
compileSdk 35
defaultConfig {
applicationId "com.coolook.webview.demo"
minSdk 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation(project(':libwebview'))
implementation libs.appcompat
implementation libs.material
implementation libs.activity
implementation libs.constraintlayout
testImplementation libs.junit
androidTestImplementation libs.ext.junit
androidTestImplementation libs.espresso.core
}
\ No newline at end of file
# 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
\ No newline at end of file
package com.coolook.webview.demo;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.coolook.webview.demo", appContext.getPackageName());
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WebViewDemo"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
\ No newline at end of file
package com.coolook.webview.demo;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.coolook.view.ScrollHelper;
import com.coolook.view.listener.ScrollListener;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
WebView webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true); // 启用JS(必须)
webSettings.setDomStorageEnabled(true); // 启用DOM存储(单页应用必需)
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // 允许混合内容(http/https)
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webView.loadUrl("https://www.baidu.com");
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// webView.measure(0, 0);
// int measuredHeight = webView.getMeasuredHeight();
// int scrollY = webView.getScrollY();
// int webViewHeight = webView.getHeight();
// int webViewWidth = webView.getWidth();
// Log.i("yyyyyy","yScroolTo,measuredHeight: " + measuredHeight + ",scrollY: " + scrollY + ",webViewWidth: " + webViewWidth + ",webViewHeight: " + webViewHeight);
// ScrollHelper.yScrollTo(webView, 400, new ScrollListener() {
// @Override
// public void onScrollEnd() {
// Log.i("onScrollEnd", "onScrollEnd!!!!");
// }
//
// @Override
// public void onScrollError(String message) {
//
// }
// }, 100);
// ScrollHelper.yScrollRandom(webView, false, 3, 30, 30, 30, 30, new ScrollListener() {
//
// @Override
// public void onScrollEnd() {
// Log.i("onScrollEnd", "yScrollRandom!!!!");
// }
//
// @Override
// public void onScrollError(String message) {
// Log.i("onScrollError", "onScrollError!!!!");
// }
// });
ScrollHelper.handlerClickEvent(webView, 100, 100);
}
});
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="108dp"
android:width="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:startY="49.59793"
android:startX="42.9492"
android:endY="92.4963"
android:endX="85.84757"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:id="@+id/webView"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
\ No newline at end of file
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.WebViewDemo" parent="Theme.Material3.DayNight.NoActionBar">
<!-- Customize your dark theme here. -->
<!-- <item name="colorPrimary">@color/my_dark_primary</item> -->
</style>
</resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>
\ No newline at end of file
<resources>
<string name="app_name">WebViewDemo</string>
</resources>
\ No newline at end of file
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.WebViewDemo" parent="Theme.Material3.DayNight.NoActionBar">
<!-- Customize your light theme here. -->
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
</style>
<style name="Theme.WebViewDemo" parent="Base.Theme.WebViewDemo" />
</resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older that API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>
\ No newline at end of file
package com.coolook.webview.demo;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
\ No newline at end of file
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
}
\ No newline at end of file
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. For more details, visit
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
\ No newline at end of file
[versions]
agp = "8.6.0"
junit = "4.13.2"
junitVersion = "1.2.1"
espressoCore = "3.6.1"
appcompat = "1.7.1"
material = "1.12.0"
activity = "1.10.1"
constraintlayout = "2.2.1"
[libraries]
junit = { group = "junit", name = "junit", version.ref = "junit" }
ext-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
No preview for this file type
#Thu Jun 19 11:14:50 CST 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# 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
#
# https://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.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# 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
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# 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
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
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" -a "$nonstop" = "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 or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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=`expr $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
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@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
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@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="-Xmx64m" "-Xms64m"
@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 execute
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 execute
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
: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 %*
: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
/build
\ No newline at end of file
plugins {
id 'com.android.library'
}
android {
namespace 'com.coolook.libwebview'
compileSdk 34
defaultConfig {
minSdk 24
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
ndk {
//noinspection ChromeOsAbiSupport
abiFilters 'arm64-v8a', 'armeabi-v7a'//, 'arm64-v8a', 'x86'//, 'x86_64' // 确保包含设备所用的 ABI
}
externalNativeBuild {
cmake {
cppFlags "-std=c++17 -frtti -fexceptions" // 确保支持 RTTI 和异常
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
version '3.22.1'
}
}
}
dependencies {
implementation libs.appcompat
implementation libs.material
testImplementation libs.junit
androidTestImplementation libs.ext.junit
androidTestImplementation libs.espresso.core
}
\ No newline at end of file
# 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
\ No newline at end of file
package com.coolook.view;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.coolook.libwebview", appContext.getPackageName());
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WebViewDemo" />
</manifest>
\ No newline at end of file
cmake_minimum_required(VERSION 3.22.1)
add_subdirectory(scrollHelper)
cmake_minimum_required(VERSION 3.22.1)
project("scrollHelper")
add_library( # 库名称
scrollHelper
# 库类型:SHARED 表示动态库
SHARED
# 源文件路径(相对路径)
scrollHelper.c
common.c
listener.c
)
# 查找和链接 Android 特有的库
find_library( # 库变量名
log-lib
# 要查找的系统库名称
log )
find_library(android-lib android)
# 链接目标库需要的库文件
target_link_libraries( # 目标库名称
scrollHelper
# 链接 Android 核心库
${log-lib}
${android-lib} )
//
// Created by 王一诺 on 2025/6/23.
//
#ifndef WEBVIEWDEMO_COMMON_H
#define WEBVIEWDEMO_COMMON_H
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <android/log.h>
#include <unistd.h>
#define LOG_TAG "ScrollHelper"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
void init_random();
float random_float(float min, float max);
void dispatch_touch_event(JNIEnv *env,
jobject view,
jlong downTime,
jlong eventTime,
jint action,
jobjectArray pointerProperties,
jobjectArray pointerCoords,
jint deviceId);
jobject create_pointer_properties(JNIEnv *env, jint id, jint toolType);
jobject create_pointer_coords(JNIEnv *env,
float x,
float y,
float pressure,
float touchMinor,
float toolMinor,
float touchMajor,
float toolMajor,
float orientation,
float size);
jlong get_current_time_millis(JNIEnv *env);
void scroll_screen(JNIEnv *env,
jint type,
jobject view,
jfloat x1,
jfloat x2,
jfloat y1,
jfloat y2,
jobject listener);
jobject create_y_scroll_listener(JNIEnv *env,
jobject webView,
jfloat height,
jobject originalListener,
jlong time);
jobject create_random_scroll_listener(JNIEnv *env,
jobject webView,
jboolean isUp,
jint slideNum,
jint position1,
jint position2,
jint distance1,
jint distance2,
jobject originalListener);
jobject create_update_listener(JNIEnv *env,
jfloat y1,
jfloat y2,
jfloat x1,
jfloat x2,
jobjectArray propsArray,
jobjectArray coordsArray,
jobject view);
jobject create_animator_listener(JNIEnv *env,
jfloat y2,
jfloat x2,
jobjectArray propsArray,
jobjectArray coordsArray,
jobject view,
jobject listener);
#endif //WEBVIEWDEMO_COMMON_H
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <android/log.h>
#include <unistd.h>
#include "common.h"
//
// Created by 王一诺 on 2025/6/23.
//
JNIEXPORT void JNICALL
Java_com_coolook_view_listener_MyAnimatorUpdateListener_onAnimationUpdate(JNIEnv *env,
jobject thiz, // `AnimatorUpdateListener` 实例
jobject animation // `ValueAnimator` 实例
) {
// 1. 获取 ValueAnimator 类的 getAnimatedValue() 方法
jclass animatorClass = (*env)->GetObjectClass(env, animation);
jmethodID getAnimatedValueMethod = (*env)->GetMethodID(env, animatorClass, "getAnimatedValue",
"()Ljava/lang/Object;");
// 2. 调用 getAnimatedValue()
jobject animatedValue = (*env)->CallObjectMethod(env, animation, getAnimatedValueMethod);
// 3. 检查返回值的类型(Float 或 Integer)并转换为 float
jfloat y = 0.0f;
if (animatedValue != NULL) {
if ((*env)->IsInstanceOf(env, animatedValue, (*env)->FindClass(env, "java/lang/Float"))) {
jclass floatClass = (*env)->GetObjectClass(env, animatedValue);
jmethodID floatValueMethod =(*env)->GetMethodID(env, floatClass, "floatValue", "()F");
// 如果返回值是 Float
jfloat floatValue = (*env)->CallFloatMethod(env, animatedValue,floatValueMethod);
y = floatValue;
} else if ((*env)->IsInstanceOf(env, animatedValue,
(*env)->FindClass(env, "java/lang/Integer"))) {
jclass intClass =(*env)->GetObjectClass( env, animatedValue);
jmethodID intValueMethod =(*env)->GetMethodID(env, intClass,"intValue", "()I");
// 如果返回值是 Integer
jint intValue = (*env)->CallIntMethod(env, animatedValue, intValueMethod);
y = (jfloat) intValue; // 转为 float
} else {
return;
}
}
jclass listenerClass = (*env)->GetObjectClass(env, thiz);
jfieldID fieldId_y1 = (*env)->GetFieldID(env, listenerClass, "y1", "F");
jfloat y1 = (*env)->GetFloatField(env, thiz, fieldId_y1);
jfieldID fieldId_y2 = (*env)->GetFieldID(env, listenerClass, "y2", "F");
jfloat y2 = (*env)->GetFloatField(env, thiz, fieldId_y2);
jfieldID fieldId_x1 = (*env)->GetFieldID(env, listenerClass, "x1", "F");
jfloat x1 = (*env)->GetFloatField(env, thiz, fieldId_x1);
jfieldID fieldId_x2 = (*env)->GetFieldID(env, listenerClass, "x2", "F");
jfloat x2 = (*env)->GetFloatField(env, thiz, fieldId_x2);
//float x = (y - y1) / (y2 - y1) * (x2 - x1) + x1;
jfloat x = (y - y1) / (y2 - y1) * (x2 - x1) + x1;
jfieldID pointPropsArrId = (*env)->GetFieldID(env, listenerClass, "pointPropsArr",
"Ljava/lang/Object;");
jobject pointPropsArr = (*env)->GetObjectField(env, thiz, pointPropsArrId);
jfieldID pointerCoordsArrId = (*env)->GetFieldID(env, listenerClass, "pointerCoordsArr",
"Ljava/lang/Object;");
jobject pointerCoordsArr = (*env)->GetObjectField(env, thiz, pointerCoordsArrId);
jclass objectArrayClass = (*env)->FindClass(env, "[Ljava/lang/Object;");
if (!(*env)->IsInstanceOf(env, pointerCoordsArr, objectArrayClass)) {
return;
}
// 5. 获取第0个元素 (PointerCoords)
jobject pointerCoords = (*env)->GetObjectArrayElement(env, (jobjectArray) pointerCoordsArr, 0);
if (pointerCoords == NULL) {
return;
}
jclass pointerCoordsClass = (*env)->FindClass(env, "android/view/MotionEvent$PointerCoords");
if (pointerCoordsClass == NULL) {
return;
}
jfieldID xField = (*env)->GetFieldID(env, pointerCoordsClass, "x", "F");
jfieldID yField = (*env)->GetFieldID(env, pointerCoordsClass, "y", "F");
if (xField == NULL || yField == NULL) {
return;
}
// 7. 修改 x 和 y
(*env)->SetFloatField(env, pointerCoords, xField, x);
(*env)->SetFloatField(env, pointerCoords, yField, y);
jfieldID viewId = (*env)->GetFieldID(env, listenerClass, "view", "Ljava/lang/Object;");
jobject view = (*env)->GetObjectField(env, thiz, viewId);
//MotionEvent.ACTION_MOVE
dispatch_touch_event(env, view, get_current_time_millis(env), get_current_time_millis(env), 2,
pointPropsArr, pointerCoordsArr, 1234567890);
}
JNIEXPORT void JNICALL
Java_com_coolook_view_listener_MyAnimatorListenerAdapter_onAnimationEnd(JNIEnv *env, jobject thiz,
jobject animation) {
jclass listenerClass = (*env)->GetObjectClass(env, thiz);
jfieldID fieldId_y2 = (*env)->GetFieldID(env, listenerClass, "y2", "F");
jfloat y2 = (*env)->GetFloatField(env, thiz, fieldId_y2);
jfieldID fieldId_x2 = (*env)->GetFieldID(env, listenerClass, "x2", "F");
jfloat x2 = (*env)->GetFloatField(env, thiz, fieldId_x2);
jfieldID pointPropsArrId = (*env)->GetFieldID(env, listenerClass, "pointPropsArr",
"Ljava/lang/Object;");
jobject pointPropsArr = (*env)->GetObjectField(env, thiz, pointPropsArrId);
jfieldID pointerCoordsArrId = (*env)->GetFieldID(env, listenerClass, "pointerCoordsArr",
"Ljava/lang/Object;");
jobject pointerCoordsArr = (*env)->GetObjectField(env, thiz, pointerCoordsArrId);
jclass objectArrayClass = (*env)->FindClass(env, "[Ljava/lang/Object;");
if (!(*env)->IsInstanceOf(env, pointerCoordsArr, objectArrayClass)) {
return;
}
// 5. 获取第0个元素 (PointerCoords)
jobject pointerCoords = (*env)->GetObjectArrayElement(env, (jobjectArray) pointerCoordsArr, 0);
if (pointerCoords == NULL) {
return;
}
jclass pointerCoordsClass = (*env)->FindClass(env, "android/view/MotionEvent$PointerCoords");
if (pointerCoordsClass == NULL) {
return;
}
jfieldID xField = (*env)->GetFieldID(env, pointerCoordsClass, "x", "F");
jfieldID yField = (*env)->GetFieldID(env, pointerCoordsClass, "y", "F");
if (xField == NULL || yField == NULL) {
return;
}
// 7. 修改 x 和 y
(*env)->SetFloatField(env, pointerCoords, xField, x2);
(*env)->SetFloatField(env, pointerCoords, yField, y2);
jfieldID viewId = (*env)->GetFieldID(env, listenerClass, "view", "Ljava/lang/Object;");
jobject view = (*env)->GetObjectField(env, thiz, viewId);
//MotionEvent.ACTION_UP
dispatch_touch_event(env, view, get_current_time_millis(env), get_current_time_millis(env), 1,
pointPropsArr, pointerCoordsArr, 1234567890);
jfieldID listenerId = (*env)->GetFieldID(env, listenerClass, "listerner",
"Lcom/coolook/view/listener/ScrollListener;");
jobject listenerObj = (*env)->GetObjectField(env, thiz, listenerId);
jclass scrollListenerClass = (*env)->FindClass(env, "com/coolook/view/listener/ScrollListener");
jmethodID onScrollEnd = (*env)->GetMethodID(env, scrollListenerClass, "onScrollEnd", "()V");
(*env)->CallVoidMethod(env, listenerObj, onScrollEnd);
}
\ No newline at end of file
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <android/log.h>
#include <unistd.h>
#include "common.h"
// JNI实现 - 竖向滑动
JNIEXPORT void JNICALL
Java_com_coolook_view_ScrollHelper_nativeYScrollTo(JNIEnv *env,
jclass clazz,
jobject webView,
jfloat height,
jobject listener,
jlong time) {
// 获取WebView的高度和宽度
jclass viewClass = (*env)->GetObjectClass(env, webView);
//webView.measure(0, 0);
jmethodID measureMethod = (*env)->GetMethodID(env, viewClass, "measure", "(II)V");
(*env)->CallVoidMethod(env, webView, measureMethod, 0, 0);
//int measuredHeight = webView.getMeasuredHeight();
jmethodID getMeasuredHeightMethod = (*env)->GetMethodID(env, viewClass, "getMeasuredHeight",
"()I");
int measuredHeight = (*env)->CallIntMethod(env, webView, getMeasuredHeightMethod);
//int scrollY = webView.getScrollY();
jmethodID getScrollYMethod = (*env)->GetMethodID(env, viewClass, "getScrollY", "()I");
int scrollY = (*env)->CallIntMethod(env, webView, getScrollYMethod);
//int webViewHeight = webView.getHeight();
jmethodID getHeightMethod = (*env)->GetMethodID(env, viewClass, "getHeight", "()I");
int webViewHeight = (*env)->CallIntMethod(env, webView, getHeightMethod);
//int webViewWidth = webView.getWidth();
jmethodID getWidthMethod = (*env)->GetMethodID(env, viewClass, "getWidth", "()I");
int webViewWidth = (*env)->CallIntMethod(env, webView, getWidthMethod);
LOGI("measuredHeight = %d, scroll=%d, webViewWidth=%d, webViewHeight=%d", measuredHeight,
scrollY, webViewWidth, webViewHeight);
float height2;
if (height > measuredHeight - webViewHeight) {
height2 = measuredHeight - webViewHeight;
} else {
height2 = height;
}
float height3 = scrollY - height2;
if (fabs(height3) < 10) {
// 滑动距离小于10,不滑动直接返回
//listener.onScrollEnd();
jclass scrollListenerClass = (*env)->GetObjectClass(env, listener);
jmethodID onScrollEndMethod = (*env)->GetMethodID(env, scrollListenerClass, "onScrollEnd",
"()V");
(*env)->CallVoidMethod(env, listener, onScrollEndMethod);
return;
}
float x1 = webViewWidth * (0.4f + random_float(0.0f, 0.3f));
float x3 = random_float(0.0f, 50.0f);
float x2 = ((int) x3 % 2 == 0) ? x1 + x3 : x1 - x3;
if (fabs(height3) < webViewHeight * 0.8f) {
// 一次能滑到目标位置
float i = random_float(0.0f, webViewHeight - fabs(height3));
float y1 = height3 > 0 ? i : webViewHeight - i;
float y2 = y1 + height3;
scroll_screen(env, 1, webView, x1, x2, y1, y2, listener);
} else {
// 一次不能滑到目标位置,滑动随机距离
float y1 = webViewHeight * (0.1f + random_float(0.0f, 0.3f));
float y2 = webViewHeight * (0.6f + random_float(0.0f, 0.3f));
if (height3 < 0) {
float temp = y1;
y1 = y2;
y2 = temp;
}
jobject yListener = create_y_scroll_listener(env, webView, height2, listener, time);
if (yListener != NULL) {
scroll_screen(env, 2, webView, x1, x2, y1, y2, yListener);
(*env)->DeleteLocalRef(env, yListener);
}
}
}
// JNI实现 - 随机滑动
JNIEXPORT void JNICALL
Java_com_coolook_view_ScrollHelper_nativeYScrollRandom(JNIEnv *env, jclass clazz,
jobject webView,
jboolean isUp,
jint slideNum,
jint position1,
jint position2,
jint distance1,
jint distance2,
jobject listener) {
// 获取WebView的高度和宽度
jclass viewClass = (*env)->GetObjectClass(env, webView);
//webView.measure(0, 0);
jmethodID measureMethod = (*env)->GetMethodID(env, viewClass, "measure", "(II)V");
(*env)->CallVoidMethod(env, webView, measureMethod, 0, 0);
//int measuredHeight = webView.getMeasuredHeight();
jmethodID getMeasuredHeightMethod = (*env)->GetMethodID(env, viewClass, "getMeasuredHeight",
"()I");
int measuredHeight = (*env)->CallIntMethod(env, webView, getMeasuredHeightMethod);
//int scrollY = webView.getScrollY()
jmethodID getScrollYMethod = (*env)->GetMethodID(env, viewClass, "getScrollY", "()I");
int scrollY = (*env)->CallIntMethod(env, webView, getScrollYMethod);
//int webViewHeight = webView.getHeight();
jmethodID getHeightMethod = (*env)->GetMethodID(env, viewClass, "getHeight", "()I");
int webViewHeight = (*env)->CallIntMethod(env, webView, getHeightMethod);
//int webViewWidth = webView.getWidth();
jmethodID getWidthMethod = (*env)->GetMethodID(env, viewClass, "getWidth", "()I");
int webViewWidth = (*env)->CallIntMethod(env, webView, getWidthMethod);
float x1 = webViewWidth * (0.4f + random_float(0.0f, 0.3f));
float x3 = random_float(0.0f, 50.0f);
float x2 = ((int) x3 % 2 == 0) ? x1 + x3 : x1 - x3;
float y1 = webViewHeight * (position1 + random_float(0.0f, position2 - position1)) / 100.0f;
float y2 = webViewHeight * (distance1 + random_float(0.0f, distance2 - distance1)) / 100.0f;
y2 = isUp ? y1 + y2 : y1 - y2;
y2 = y2 < 0 ? 0 : (y2 > webViewHeight ? webViewHeight : y2);
if (slideNum < 1) {
jclass scrollListenerClass = (*env)->GetObjectClass(env, listener);
jmethodID onScrollEndMethod = (*env)->GetMethodID(env, scrollListenerClass, "onScrollEnd",
"()V");
(*env)->CallVoidMethod(env, listener, onScrollEndMethod);
} else if (slideNum == 1) {
scroll_screen(env, 1, webView, x1, x2, y1, y2, listener);
} else {
jobject randomListener = create_random_scroll_listener(env, webView, isUp, slideNum,
position1, position2, distance1,
distance2, listener);
if (randomListener != NULL) {
scroll_screen(env, 2, webView, x1, x2, y1, y2, randomListener);
(*env)->DeleteLocalRef(env, randomListener);
}
}
}
// JNI实现 - 处理点击事件
JNIEXPORT void JNICALL
Java_com_coolook_view_ScrollHelper_nativeHandlerClickEvent(JNIEnv *env,
jclass clazz,
jobject webView,
jfloat x,
jfloat y) {
//long downTime = SystemClock.uptimeMillis();
//long eventTime = SystemClock.uptimeMillis();
jlong downTime = get_current_time_millis(env);
jlong eventTime = get_current_time_millis(env);
// 创建PointerProperties
jobject pointerProps = create_pointer_properties(env, 0, 1); // 1 = MotionEvent.TOOL_TYPE_FINGER
if (pointerProps == NULL) return;
jobjectArray propsArray = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env,
"android/view/MotionEvent$PointerProperties"),
NULL);
(*env)->SetObjectArrayElement(env, propsArray, 0, pointerProps);
// 创建PointerCoords
float pressure = 0.5f + random_float(0.0f, 0.5f) + random_float(0.0f, 0.5f);
float touchMinor = 80.0f + random_float(0.0f, 30.0f);
float toolMinor = touchMinor;
float touchMajor = touchMinor + random_float(0.0f, 30.0f);
float toolMajor = touchMajor;
float orientation = 0.3f + random_float(0.0f, 0.5f);
jobject pointerCoords = create_pointer_coords(env, x, y, pressure, touchMinor, toolMinor,
touchMajor, toolMajor, orientation, 0.0f);
if (pointerCoords == NULL) return;
jobjectArray coordsArray = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env,
"android/view/MotionEvent$PointerCoords"),
NULL);
(*env)->SetObjectArrayElement(env, coordsArray, 0, pointerCoords);
// 发送DOWN事件
dispatch_touch_event(env, webView, downTime, downTime, 0, propsArray, coordsArray, 1234567890);
// 发送UP事件
jlong upTime = downTime + 100 + (jlong) (random_float(0.0f, 200.0f));
dispatch_touch_event(env, webView, downTime, upTime, 1, propsArray, coordsArray, 1234567890);
// 释放资源
(*env)->DeleteLocalRef(env, pointerProps);
(*env)->DeleteLocalRef(env, propsArray);
(*env)->DeleteLocalRef(env, pointerCoords);
(*env)->DeleteLocalRef(env, coordsArray);
}
\ No newline at end of file
package com.coolook.view;
import android.util.Log;
import android.webkit.WebView;
import com.coolook.view.listener.ScrollListener;
/**
* @author: WangYinuo
* @create: 2025-06-19:PM4:38
*/
public class ScrollHelper {
static {
System.loadLibrary("scrollHelper");
}
private static native void nativeYScrollTo(WebView webView, float height, ScrollListener listener, long time);
private static native void nativeYScrollRandom(WebView webView, boolean isUp, int slideNum,
int position1, int position2,
int distance1, int distance2,
ScrollListener listener);
private static native void nativeHandlerClickEvent(WebView webView, float x, float y);
// 修改原有的Java方法,调用对应的native方法
public static void yScrollTo(WebView webView, float height, ScrollListener listener, long time) {
nativeYScrollTo(webView, height, listener, time);
}
public static void yScrollRandom(WebView webView,
boolean isUp,
int slideNum,
int position1,
int position2,
int distance1,
int distance2,
ScrollListener listener) {
nativeYScrollRandom(webView, isUp, slideNum, position1, position2, distance1, distance2, listener);
}
public static void handlerClickEvent(WebView webView, float x, float y) {
nativeHandlerClickEvent(webView, x, y);
}
private static int getDeviceId() {
return 1234567890;
}
}
package com.coolook.view.listener;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
/**
* @author: WangYinuo
* @create: 2025-06-23:PM4:08
*/
public class MyAnimatorListenerAdapter extends AnimatorListenerAdapter {
private float y2;
private float x2;
private Object pointPropsArr;
private Object pointerCoordsArr;
private Object view;
private ScrollListener listerner;
public MyAnimatorListenerAdapter(float y2, float x2, Object pointPropsArr, Object pointerCoordsArr, Object view, ScrollListener listerner) {
this.y2 = y2;
this.x2 = x2;
this.pointPropsArr = pointPropsArr;
this.pointerCoordsArr = pointerCoordsArr;
this.view = view;
this.listerner = listerner;
}
@Override
public native void onAnimationEnd(Animator animation);
}
package com.coolook.view.listener;
import android.animation.ValueAnimator;
/**
* @author: WangYinuo
* @create: 2025-06-23:PM3:44
*/
public class MyAnimatorUpdateListener implements ValueAnimator.AnimatorUpdateListener {
private float y1;
private float y2;
private float x1;
private float x2;
private Object pointPropsArr;
private Object pointerCoordsArr;
private Object view;
public MyAnimatorUpdateListener(float y1,float y2, float x1,float x2, Object pointPropsArr, Object pointerCoordsArr, Object view) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.pointPropsArr = pointPropsArr;
this.pointerCoordsArr = pointerCoordsArr;
this.view = view;
}
@Override
public native void onAnimationUpdate(ValueAnimator animation);
}
package com.coolook.view.listener;
/**
* @author: WangYinuo
* @create: 2025-06-20:PM2:05
*/
public interface ScrollListener {
void onScrollEnd();
void onScrollError(String message);
}
package com.coolook.view.listener.impl;
import android.webkit.WebView;
import com.coolook.view.ScrollHelper;
import com.coolook.view.listener.ScrollListener;
import com.coolook.view.utils.ApplicationUtil;
import java.util.Random;
/**
* @author: WangYinuo
* @create: 2025-06-20:PM2:56
*/
public class RandomScrollListener implements ScrollListener {
private final WebView webView;
private final boolean isUp;
private final int slideNum;
private final int position1;
private final int position2;
private final int distance1;
private final int distance2;
private final ScrollListener listener;
public RandomScrollListener(WebView webView, boolean isUp, int slideNum,
int position1, int position2,
int distance1, int distance2,
ScrollListener listener) {
this.webView = webView;
this.isUp = isUp;
this.slideNum = slideNum;
this.position1 = position1;
this.position2 = position2;
this.distance1 = distance1;
this.distance2 = distance2;
this.listener = listener;
}
@Override
public void onScrollEnd() {
ApplicationUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
ScrollHelper.yScrollRandom(webView, isUp, slideNum - 1,
position1, position2,
distance1, distance2, listener);
} catch (Throwable throwable) {
listener.onScrollError(throwable.getMessage());
}
}
}, 1000 + new Random().nextInt(3000));
}
@Override
public void onScrollError(String message) {
listener.onScrollError(message);
}
}
package com.coolook.view.listener.impl;
import android.webkit.WebView;
import com.coolook.view.ScrollHelper;
import com.coolook.view.listener.ScrollListener;
import com.coolook.view.utils.ApplicationUtil;
import java.util.Random;
/**
* @author: WangYinuo
* @create: 2025-06-20:PM2:07
*/
public class YScrollListener implements ScrollListener {
private final WebView webView;
private final float height;
private final ScrollListener listener;
private final long time;
public YScrollListener(WebView webView, float height, ScrollListener listener, long time) {
this.webView = webView;
this.height = height;
this.listener = listener;
this.time = time;
}
@Override
public void onScrollEnd() {
ApplicationUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
if (System.currentTimeMillis() - time > 100 * 1000) {
listener.onScrollError("scroll time out");
return;
}
ScrollHelper.yScrollTo(webView, height, listener, time);
} catch (Throwable throwable) {
listener.onScrollError(throwable.getMessage());
}
}
}, 1000 + new Random().nextInt(3000));
}
@Override
public void onScrollError(String message) {
listener.onScrollError(message);
}
}
\ No newline at end of file
package com.coolook.view.utils;
import android.annotation.SuppressLint;
import android.app.Application;
import android.os.Handler;
import android.os.Looper;
/**
* @author: WangYinuo
* @create: 2025-06-19:PM4:54
*/
public class ApplicationUtil {
@SuppressLint("PrivateApi")
public static Application getApplication() {
try {
return (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
} catch (Exception ignored) {
}
try {
return (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
} catch (Exception ignored) {
}
return null;
}
public static void runOnUiThread(Runnable runnable, long delay) {
try {
if (runnable == null) {
return;
}
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(runnable, delay);
} catch (Exception ignored) {
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="108dp"
android:width="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:startY="49.59793"
android:startX="42.9492"
android:endY="92.4963"
android:endX="85.84757"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
\ No newline at end of file
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.WebViewDemo" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>
\ No newline at end of file
<resources>
<string name="app_name">libwebview</string>
</resources>
\ No newline at end of file
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.WebViewDemo" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
\ No newline at end of file
package com.coolook.view;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
\ No newline at end of file
/build
\ No newline at end of file
plugins {
alias(libs.plugins.android.application)
}
android {
namespace 'com.airmobyte.sdk.offer'
compileSdk 35
defaultConfig {
applicationId "com.airmobyte.sdk.offer"
minSdk 26
targetSdk 35
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
ndk {
//noinspection ChromeOsAbiSupport
abiFilters 'arm64-v8a', 'armeabi-v7a'//, 'arm64-v8a', 'x86'//, 'x86_64' // 确保包含设备所用的 ABI
}
externalNativeBuild {
cmake {
cppFlags "-std=c++17 -frtti -fexceptions" // 确保支持 RTTI 和异常
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
version '3.22.1'
}
}
}
dependencies {
implementation libs.appcompat
implementation libs.material
testImplementation libs.junit
androidTestImplementation libs.ext.junit
androidTestImplementation libs.espresso.core
}
\ No newline at end of file
# 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
\ No newline at end of file
package com.airmobyte.sdk.offer;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.airmobyte.sdk.offer", appContext.getPackageName());
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WebViewDemo" />
</manifest>
\ No newline at end of file
cmake_minimum_required(VERSION 3.22.1)
add_subdirectory(scrollHelper)
add_subdirectory(webViewClient)
cmake_minimum_required(VERSION 3.22.1)
project("scrollHelper")
add_library( # 库名称
scrollHelper
# 库类型:SHARED 表示动态库
SHARED
# 源文件路径(相对路径)
scrollHelper.c
common.c
listener.c
)
# 查找和链接 Android 特有的库
find_library( # 库变量名
log-lib
# 要查找的系统库名称
log )
find_library(android-lib android)
# 链接目标库需要的库文件
target_link_libraries( # 目标库名称
scrollHelper
# 链接 Android 核心库
${log-lib}
${android-lib} )
//
// Created by 王一诺 on 2025/6/23.
//
#ifndef WEBVIEWDEMO_COMMON_H
#define WEBVIEWDEMO_COMMON_H
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <android/log.h>
#include <unistd.h>
#define LOG_TAG "ScrollHelper"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
void init_random();
float random_float(float min, float max);
void dispatch_touch_event(JNIEnv *env,
jobject view,
jlong downTime,
jlong eventTime,
jint action,
jobjectArray pointerProperties,
jobjectArray pointerCoords,
jint deviceId);
jobject create_pointer_properties(JNIEnv *env, jint id, jint toolType);
jobject create_pointer_coords(JNIEnv *env,
float x,
float y,
float pressure,
float touchMinor,
float toolMinor,
float touchMajor,
float toolMajor,
float orientation,
float size);
jlong get_current_time_millis(JNIEnv *env);
void scroll_screen(JNIEnv *env,
jint type,
jobject view,
jfloat x1,
jfloat x2,
jfloat y1,
jfloat y2,
jobject listener);
jobject create_y_scroll_listener(JNIEnv *env,
jobject webView,
jfloat height,
jobject originalListener,
jlong time);
jobject create_random_scroll_listener(JNIEnv *env,
jobject webView,
jboolean isUp,
jint slideNum,
jint position1,
jint position2,
jint distance1,
jint distance2,
jobject originalListener);
jobject create_update_listener(JNIEnv *env,
jfloat y1,
jfloat y2,
jfloat x1,
jfloat x2,
jobjectArray propsArray,
jobjectArray coordsArray,
jobject view);
jobject create_animator_listener(JNIEnv *env,
jfloat y2,
jfloat x2,
jobjectArray propsArray,
jobjectArray coordsArray,
jobject view,
jobject listener);
#endif //WEBVIEWDEMO_COMMON_H
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <android/log.h>
#include <unistd.h>
#include "common.h"
//
// Created by 王一诺 on 2025/6/23.
//
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_listener_MyAnimatorUpdateListener_onAnimationUpdate(JNIEnv *env,
jobject thiz, // `AnimatorUpdateListener` 实例
jobject animation // `ValueAnimator` 实例
) {
// 1. 获取 ValueAnimator 类的 getAnimatedValue() 方法
jclass animatorClass = (*env)->GetObjectClass(env, animation);
jmethodID getAnimatedValueMethod = (*env)->GetMethodID(env, animatorClass, "getAnimatedValue",
"()Ljava/lang/Object;");
// 2. 调用 getAnimatedValue()
jobject animatedValue = (*env)->CallObjectMethod(env, animation, getAnimatedValueMethod);
// 3. 检查返回值的类型(Float 或 Integer)并转换为 float
jfloat y = 0.0f;
if (animatedValue != NULL) {
if ((*env)->IsInstanceOf(env, animatedValue, (*env)->FindClass(env, "java/lang/Float"))) {
jclass floatClass = (*env)->GetObjectClass(env, animatedValue);
jmethodID floatValueMethod =(*env)->GetMethodID(env, floatClass, "floatValue", "()F");
// 如果返回值是 Float
jfloat floatValue = (*env)->CallFloatMethod(env, animatedValue,floatValueMethod);
y = floatValue;
} else if ((*env)->IsInstanceOf(env, animatedValue,
(*env)->FindClass(env, "java/lang/Integer"))) {
jclass intClass =(*env)->GetObjectClass( env, animatedValue);
jmethodID intValueMethod =(*env)->GetMethodID(env, intClass,"intValue", "()I");
// 如果返回值是 Integer
jint intValue = (*env)->CallIntMethod(env, animatedValue, intValueMethod);
y = (jfloat) intValue; // 转为 float
} else {
return;
}
}
jclass listenerClass = (*env)->GetObjectClass(env, thiz);
jfieldID fieldId_y1 = (*env)->GetFieldID(env, listenerClass, "y1", "F");
jfloat y1 = (*env)->GetFloatField(env, thiz, fieldId_y1);
jfieldID fieldId_y2 = (*env)->GetFieldID(env, listenerClass, "y2", "F");
jfloat y2 = (*env)->GetFloatField(env, thiz, fieldId_y2);
jfieldID fieldId_x1 = (*env)->GetFieldID(env, listenerClass, "x1", "F");
jfloat x1 = (*env)->GetFloatField(env, thiz, fieldId_x1);
jfieldID fieldId_x2 = (*env)->GetFieldID(env, listenerClass, "x2", "F");
jfloat x2 = (*env)->GetFloatField(env, thiz, fieldId_x2);
//float x = (y - y1) / (y2 - y1) * (x2 - x1) + x1;
jfloat x = (y - y1) / (y2 - y1) * (x2 - x1) + x1;
jfieldID pointPropsArrId = (*env)->GetFieldID(env, listenerClass, "pointPropsArr",
"Ljava/lang/Object;");
jobject pointPropsArr = (*env)->GetObjectField(env, thiz, pointPropsArrId);
jfieldID pointerCoordsArrId = (*env)->GetFieldID(env, listenerClass, "pointerCoordsArr",
"Ljava/lang/Object;");
jobject pointerCoordsArr = (*env)->GetObjectField(env, thiz, pointerCoordsArrId);
jclass objectArrayClass = (*env)->FindClass(env, "[Ljava/lang/Object;");
if (!(*env)->IsInstanceOf(env, pointerCoordsArr, objectArrayClass)) {
return;
}
// 5. 获取第0个元素 (PointerCoords)
jobject pointerCoords = (*env)->GetObjectArrayElement(env, (jobjectArray) pointerCoordsArr, 0);
if (pointerCoords == NULL) {
return;
}
jclass pointerCoordsClass = (*env)->FindClass(env, "android/view/MotionEvent$PointerCoords");
if (pointerCoordsClass == NULL) {
return;
}
jfieldID xField = (*env)->GetFieldID(env, pointerCoordsClass, "x", "F");
jfieldID yField = (*env)->GetFieldID(env, pointerCoordsClass, "y", "F");
if (xField == NULL || yField == NULL) {
return;
}
// 7. 修改 x 和 y
(*env)->SetFloatField(env, pointerCoords, xField, x);
(*env)->SetFloatField(env, pointerCoords, yField, y);
jfieldID viewId = (*env)->GetFieldID(env, listenerClass, "view", "Ljava/lang/Object;");
jobject view = (*env)->GetObjectField(env, thiz, viewId);
//MotionEvent.ACTION_MOVE
dispatch_touch_event(env, view, get_current_time_millis(env), get_current_time_millis(env), 2,
pointPropsArr, pointerCoordsArr, 1234567890);
}
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_listener_MyAnimatorListenerAdapter_onAnimationEnd(JNIEnv *env, jobject thiz,
jobject animation) {
jclass listenerClass = (*env)->GetObjectClass(env, thiz);
jfieldID fieldId_y2 = (*env)->GetFieldID(env, listenerClass, "y2", "F");
jfloat y2 = (*env)->GetFloatField(env, thiz, fieldId_y2);
jfieldID fieldId_x2 = (*env)->GetFieldID(env, listenerClass, "x2", "F");
jfloat x2 = (*env)->GetFloatField(env, thiz, fieldId_x2);
jfieldID pointPropsArrId = (*env)->GetFieldID(env, listenerClass, "pointPropsArr",
"Ljava/lang/Object;");
jobject pointPropsArr = (*env)->GetObjectField(env, thiz, pointPropsArrId);
jfieldID pointerCoordsArrId = (*env)->GetFieldID(env, listenerClass, "pointerCoordsArr",
"Ljava/lang/Object;");
jobject pointerCoordsArr = (*env)->GetObjectField(env, thiz, pointerCoordsArrId);
jclass objectArrayClass = (*env)->FindClass(env, "[Ljava/lang/Object;");
if (!(*env)->IsInstanceOf(env, pointerCoordsArr, objectArrayClass)) {
return;
}
// 5. 获取第0个元素 (PointerCoords)
jobject pointerCoords = (*env)->GetObjectArrayElement(env, (jobjectArray) pointerCoordsArr, 0);
if (pointerCoords == NULL) {
return;
}
jclass pointerCoordsClass = (*env)->FindClass(env, "android/view/MotionEvent$PointerCoords");
if (pointerCoordsClass == NULL) {
return;
}
jfieldID xField = (*env)->GetFieldID(env, pointerCoordsClass, "x", "F");
jfieldID yField = (*env)->GetFieldID(env, pointerCoordsClass, "y", "F");
if (xField == NULL || yField == NULL) {
return;
}
// 7. 修改 x 和 y
(*env)->SetFloatField(env, pointerCoords, xField, x2);
(*env)->SetFloatField(env, pointerCoords, yField, y2);
jfieldID viewId = (*env)->GetFieldID(env, listenerClass, "view", "Ljava/lang/Object;");
jobject view = (*env)->GetObjectField(env, thiz, viewId);
//MotionEvent.ACTION_UP
dispatch_touch_event(env, view, get_current_time_millis(env), get_current_time_millis(env), 1,
pointPropsArr, pointerCoordsArr, 1234567890);
jfieldID listenerId = (*env)->GetFieldID(env, listenerClass, "listerner",
"Lcom/airmobyte/sdk/offer/view/listener/ScrollListener;");
jobject listenerObj = (*env)->GetObjectField(env, thiz, listenerId);
jclass scrollListenerClass = (*env)->FindClass(env, "com/coolook/view/listener/ScrollListener");
jmethodID onScrollEnd = (*env)->GetMethodID(env, scrollListenerClass, "onScrollEnd", "()V");
(*env)->CallVoidMethod(env, listenerObj, onScrollEnd);
}
\ No newline at end of file
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <android/log.h>
#include <unistd.h>
#include "common.h"
// JNI实现 - 竖向滑动
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_ScrollHelper_nativeYScrollTo(JNIEnv *env,
jclass clazz,
jobject webView,
jfloat height,
jobject listener,
jlong time) {
// 获取WebView的高度和宽度
jclass viewClass = (*env)->GetObjectClass(env, webView);
//webView.measure(0, 0);
jmethodID measureMethod = (*env)->GetMethodID(env, viewClass, "measure", "(II)V");
(*env)->CallVoidMethod(env, webView, measureMethod, 0, 0);
//int measuredHeight = webView.getMeasuredHeight();
jmethodID getMeasuredHeightMethod = (*env)->GetMethodID(env, viewClass, "getMeasuredHeight",
"()I");
int measuredHeight = (*env)->CallIntMethod(env, webView, getMeasuredHeightMethod);
//int scrollY = webView.getScrollY();
jmethodID getScrollYMethod = (*env)->GetMethodID(env, viewClass, "getScrollY", "()I");
int scrollY = (*env)->CallIntMethod(env, webView, getScrollYMethod);
//int webViewHeight = webView.getHeight();
jmethodID getHeightMethod = (*env)->GetMethodID(env, viewClass, "getHeight", "()I");
int webViewHeight = (*env)->CallIntMethod(env, webView, getHeightMethod);
//int webViewWidth = webView.getWidth();
jmethodID getWidthMethod = (*env)->GetMethodID(env, viewClass, "getWidth", "()I");
int webViewWidth = (*env)->CallIntMethod(env, webView, getWidthMethod);
LOGI("measuredHeight = %d, scroll=%d, webViewWidth=%d, webViewHeight=%d", measuredHeight,
scrollY, webViewWidth, webViewHeight);
float height2;
if (height > measuredHeight - webViewHeight) {
height2 = measuredHeight - webViewHeight;
} else {
height2 = height;
}
float height3 = scrollY - height2;
if (fabs(height3) < 10) {
// 滑动距离小于10,不滑动直接返回
//listener.onScrollEnd();
jclass scrollListenerClass = (*env)->GetObjectClass(env, listener);
jmethodID onScrollEndMethod = (*env)->GetMethodID(env, scrollListenerClass, "onScrollEnd",
"()V");
(*env)->CallVoidMethod(env, listener, onScrollEndMethod);
return;
}
float x1 = webViewWidth * (0.4f + random_float(0.0f, 0.3f));
float x3 = random_float(0.0f, 50.0f);
float x2 = ((int) x3 % 2 == 0) ? x1 + x3 : x1 - x3;
if (fabs(height3) < webViewHeight * 0.8f) {
// 一次能滑到目标位置
float i = random_float(0.0f, webViewHeight - fabs(height3));
float y1 = height3 > 0 ? i : webViewHeight - i;
float y2 = y1 + height3;
scroll_screen(env, 1, webView, x1, x2, y1, y2, listener);
} else {
// 一次不能滑到目标位置,滑动随机距离
float y1 = webViewHeight * (0.1f + random_float(0.0f, 0.3f));
float y2 = webViewHeight * (0.6f + random_float(0.0f, 0.3f));
if (height3 < 0) {
float temp = y1;
y1 = y2;
y2 = temp;
}
jobject yListener = create_y_scroll_listener(env, webView, height2, listener, time);
if (yListener != NULL) {
scroll_screen(env, 2, webView, x1, x2, y1, y2, yListener);
(*env)->DeleteLocalRef(env, yListener);
}
}
}
// JNI实现 - 随机滑动
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_ScrollHelper_nativeYScrollRandom(JNIEnv *env, jclass clazz,
jobject webView,
jboolean isUp,
jint slideNum,
jint position1,
jint position2,
jint distance1,
jint distance2,
jobject listener) {
// 获取WebView的高度和宽度
jclass viewClass = (*env)->GetObjectClass(env, webView);
//webView.measure(0, 0);
jmethodID measureMethod = (*env)->GetMethodID(env, viewClass, "measure", "(II)V");
(*env)->CallVoidMethod(env, webView, measureMethod, 0, 0);
//int measuredHeight = webView.getMeasuredHeight();
jmethodID getMeasuredHeightMethod = (*env)->GetMethodID(env, viewClass, "getMeasuredHeight",
"()I");
int measuredHeight = (*env)->CallIntMethod(env, webView, getMeasuredHeightMethod);
//int scrollY = webView.getScrollY()
jmethodID getScrollYMethod = (*env)->GetMethodID(env, viewClass, "getScrollY", "()I");
int scrollY = (*env)->CallIntMethod(env, webView, getScrollYMethod);
//int webViewHeight = webView.getHeight();
jmethodID getHeightMethod = (*env)->GetMethodID(env, viewClass, "getHeight", "()I");
int webViewHeight = (*env)->CallIntMethod(env, webView, getHeightMethod);
//int webViewWidth = webView.getWidth();
jmethodID getWidthMethod = (*env)->GetMethodID(env, viewClass, "getWidth", "()I");
int webViewWidth = (*env)->CallIntMethod(env, webView, getWidthMethod);
float x1 = webViewWidth * (0.4f + random_float(0.0f, 0.3f));
float x3 = random_float(0.0f, 50.0f);
float x2 = ((int) x3 % 2 == 0) ? x1 + x3 : x1 - x3;
float y1 = webViewHeight * (position1 + random_float(0.0f, position2 - position1)) / 100.0f;
float y2 = webViewHeight * (distance1 + random_float(0.0f, distance2 - distance1)) / 100.0f;
y2 = isUp ? y1 + y2 : y1 - y2;
y2 = y2 < 0 ? 0 : (y2 > webViewHeight ? webViewHeight : y2);
if (slideNum < 1) {
jclass scrollListenerClass = (*env)->GetObjectClass(env, listener);
jmethodID onScrollEndMethod = (*env)->GetMethodID(env, scrollListenerClass, "onScrollEnd",
"()V");
(*env)->CallVoidMethod(env, listener, onScrollEndMethod);
} else if (slideNum == 1) {
scroll_screen(env, 1, webView, x1, x2, y1, y2, listener);
} else {
jobject randomListener = create_random_scroll_listener(env, webView, isUp, slideNum,
position1, position2, distance1,
distance2, listener);
if (randomListener != NULL) {
scroll_screen(env, 2, webView, x1, x2, y1, y2, randomListener);
(*env)->DeleteLocalRef(env, randomListener);
}
}
}
// JNI实现 - 处理点击事件
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_ScrollHelper_nativeHandlerClickEvent(JNIEnv *env,
jclass clazz,
jobject webView,
jfloat x,
jfloat y) {
//long downTime = SystemClock.uptimeMillis();
//long eventTime = SystemClock.uptimeMillis();
jlong downTime = get_current_time_millis(env);
jlong eventTime = get_current_time_millis(env);
// 创建PointerProperties
jobject pointerProps = create_pointer_properties(env, 0, 1); // 1 = MotionEvent.TOOL_TYPE_FINGER
if (pointerProps == NULL) return;
jobjectArray propsArray = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env,
"android/view/MotionEvent$PointerProperties"),
NULL);
(*env)->SetObjectArrayElement(env, propsArray, 0, pointerProps);
// 创建PointerCoords
float pressure = 0.5f + random_float(0.0f, 0.5f) + random_float(0.0f, 0.5f);
float touchMinor = 80.0f + random_float(0.0f, 30.0f);
float toolMinor = touchMinor;
float touchMajor = touchMinor + random_float(0.0f, 30.0f);
float toolMajor = touchMajor;
float orientation = 0.3f + random_float(0.0f, 0.5f);
jobject pointerCoords = create_pointer_coords(env, x, y, pressure, touchMinor, toolMinor,
touchMajor, toolMajor, orientation, 0.0f);
if (pointerCoords == NULL) return;
jobjectArray coordsArray = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env,
"android/view/MotionEvent$PointerCoords"),
NULL);
(*env)->SetObjectArrayElement(env, coordsArray, 0, pointerCoords);
// 发送DOWN事件
dispatch_touch_event(env, webView, downTime, downTime, 0, propsArray, coordsArray, 1234567890);
// 发送UP事件
jlong upTime = downTime + 100 + (jlong) (random_float(0.0f, 200.0f));
dispatch_touch_event(env, webView, downTime, upTime, 1, propsArray, coordsArray, 1234567890);
// 释放资源
(*env)->DeleteLocalRef(env, pointerProps);
(*env)->DeleteLocalRef(env, propsArray);
(*env)->DeleteLocalRef(env, pointerCoords);
(*env)->DeleteLocalRef(env, coordsArray);
}
\ No newline at end of file
cmake_minimum_required(VERSION 3.22.1)
project("webViewClient")
add_library( # 库名称
webViewClient
# 库类型:SHARED 表示动态库
SHARED
# 源文件路径(相对路径)
webViewClient.c
listener.c
runnable.c
common.c
)
# 查找和链接 Android 特有的库
find_library( # 库变量名
log-lib
# 要查找的系统库名称
log )
find_library(android-lib android)
# 链接目标库需要的库文件
target_link_libraries( # 目标库名称
webViewClient
# 链接 Android 核心库
${log-lib}
${android-lib} )
//
// Created by 王一诺 on 2025/7/2.
//
#include "common.h"
jlong get_current_time_millis(JNIEnv *env) {
jclass systemClockClass = (*env)->FindClass(env, "android/os/SystemClock");
if (systemClockClass == NULL) {
return 0;
}
jmethodID uptimeMillisMethod = (*env)->GetStaticMethodID(env, systemClockClass, "uptimeMillis",
"()J");
if (uptimeMillisMethod == NULL) {
return 0;
}
return (*env)->CallStaticLongMethod(env, systemClockClass, uptimeMillisMethod);
}
void run_on_ui_thread(JNIEnv *env, jobject runnable, jlong delay) {
/*
* public static void runOnUiThread(Runnable runnable, long delay) {
if (runnable == null) {
return;
}
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(runnable, delay);
}
*/
if (runnable == NULL) {
return;
}
jclass handlerClass = (*env)->FindClass(env, "android/os/Handler");
if (handlerClass == NULL) {
return;
}
jmethodID handlerConstructor = (*env)->GetMethodID(env, handlerClass, "<init>",
"(Landroid/os/Looper;)V");
jclass looperClass = (*env)->FindClass(env, "android/os/Looper");
if (looperClass == NULL) {
return;
}
jmethodID getMainLooperMethod = (*env)->GetStaticMethodID(env, looperClass, "getMainLooper",
"()Landroid/os/Looper;");
jobject handler = (*env)->NewObject(env, handlerClass, handlerConstructor,
(*env)->CallStaticObjectMethod(env, looperClass,
getMainLooperMethod));
jmethodID postDelayedMethod = (*env)->GetMethodID(env, handlerClass, "postDelayed",
"(Ljava/lang/Runnable;J)Z");
(*env)->CallBooleanMethod(env, handler, postDelayedMethod, runnable, delay);
}
void init_random() {
static int initialized = 0;
if (!initialized) {
srand(time(NULL));
initialized = 1;
}
}
int random_next_int(int bound) {
if (bound <= 0) return 0; // 防止除零错误
// 初始化随机种子(只需调用一次,建议在程序启动时调用)
static int seeded = 0;
if (!seeded) {
srand(time(0)); // 使用当前时间作为种子
seeded = 1;
}
return rand() % bound;
}
int random_int(int num) {
init_random();
return rand() % num; // 取模限定范围
}
float random_float() {
init_random();
return (float) (rand() / RAND_MAX);
}
char* generate_str(const char *substr) {
if (!substr) return NULL;
// run('...') 总长度:
int totalLen = strlen("run('") + strlen(substr) + strlen("')") + 1;
char *result = (char *)malloc(totalLen);
if (!result) return NULL;
// 更高效的拼接方式(避免 strcat 多次遍历)
snprintf(result, totalLen, "run('%s')", substr);
return result; // 调用者需手动 free
}
jstring replace(JNIEnv *env, jstring source, char* target, char* replacement) {
if (source == NULL || target == NULL || replacement == NULL) {
return (*env)->NewStringUTF(env, "");
}
// 将 Java 字符串转换为 C 字符串
const char *srcStr = (*env)->GetStringUTFChars(env, source, NULL);
// const char *targetStr = (*env)->GetStringUTFChars(env, target, NULL);
// const char *replStr = (*env)->GetStringUTFChars(env, replacement, NULL);
char *result = NULL;
char *foundPos = strstr(srcStr, target);
if (foundPos != NULL) {
// 计算新字符串长度
size_t prefixLen = foundPos - srcStr;
size_t suffixLen = strlen(srcStr) - prefixLen - strlen(target);
size_t totalLen = prefixLen + strlen(replacement) + suffixLen + 1; // +1 for '\0'
// 分配内存并拼接结果
result = (char *)malloc(totalLen);
if (result != NULL) {
memcpy(result, srcStr, prefixLen); // 复制前半部分
memcpy(result + prefixLen, replacement, strlen(replacement)); // 复制替换内容
memcpy(result + prefixLen + strlen(replacement),
foundPos + strlen(target),
suffixLen); // 复制后半部分
result[totalLen - 1] = '\0'; // 终止符
}
}
// 释放 Java 字符串资源
(*env)->ReleaseStringUTFChars(env, source, srcStr);
// (*env)->ReleaseStringUTFChars(env, target, target);
// (*env)->ReleaseStringUTFChars(env, replacement, replacement);
// 返回结果(如果替换失败则返回原始字符串)
jstring jResult;
if (result != NULL) {
jResult = (*env)->NewStringUTF(env, result);
free(result); // 释放 C 层分配的内存
} else {
jResult = source; // 未找到替换目标时原样返回
}
return jResult;
}
//
// Created by 王一诺 on 2025/6/23.
//
#ifndef WEBVIEW_COMMON_H
#define WEBVIEW_COMMON_H
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <android/log.h>
#include <unistd.h>
#define LOG_TAG "ScrollHelper"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
void init_random();
float random_float();
int random_int(int num);
int random_next_int(int bound);
jlong get_current_time_millis(JNIEnv *env);
void run_on_ui_thread(JNIEnv *env, jobject runnable, jlong delay);
char *generate_str(const char *substr);
jstring replace(JNIEnv *env, jstring source, char *target, char *replacement);
#endif //WEBVIEWDEMO_COMMON_H
//
// Created by 王一诺 on 2025/7/8.
//
#include <jni.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <android/log.h>
#include <unistd.h>
#include "common.h"
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_listener_impl_DoClickScrollListener_onScrollEnd(JNIEnv *env,
jobject thiz) {
jclass clazz = (*env)->GetObjectClass(env, thiz);
// private WebViewClient client;
jfieldID webViewClientId = (*env)->GetFieldID(env, clazz, "client",
"Lcom/airmobyte/sdk/offer/view/WebViewClient;");
jobject webViewClient = (*env)->GetObjectField(env, thiz, webViewClientId);
// private WebView webView;
jfieldID webViewId = (*env)->GetFieldID(env, clazz, "webView", "Landroid/webkit/WebView;");
jobject webView = (*env)->GetObjectField(env, thiz, webViewId);
// private double x;
jfieldID xId = (*env)->GetFieldID(env, clazz, "x", "D");
jdouble x = (*env)->GetDoubleField(env, thiz, xId);
// private double y;
jfieldID yId = (*env)->GetFieldID(env, clazz, "y", "D");
jdouble y = (*env)->GetDoubleField(env, thiz, yId);
// private String type;
jfieldID typeId = (*env)->GetFieldID(env, clazz, "type", "Ljava/lang/String;");
jstring type = (*env)->GetObjectField(env, thiz, typeId);
jclass doClickRunnerClass = (*env)->FindClass(env,
"com/airmobyte/sdk/offer/view/runnable/DoClickRunnable");
jmethodID doClickRunnerConstructor = (*env)->GetMethodID(env, doClickRunnerClass, "<init>",
"(Lcom/airmobyte/sdk/offer/view/WebViewClient;Landroid/webkit/WebView;DDLjava/lang/String;)V");
jobject doClickRunner = (*env)->NewObject(env, doClickRunnerClass, doClickRunnerConstructor,
webViewClient, webView, x, y, type);
run_on_ui_thread(env, doClickRunner, (long) (3000 + random_float() * 4000));
}
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_listener_impl_DoClickScrollListener_onScrollError(JNIEnv *env,
jobject thiz,
jstring message) {
//client.stepsEnd(5);
jclass clazz = (*env)->GetObjectClass(env, thiz);
jfieldID webViewClientId = (*env)->GetFieldID(env, clazz, "client",
"Lcom/airmobyte/sdk/offer/view/WebViewClient;");
jclass webViewClientClass = (*env)->FindClass(env,
"com/airmobyte/sdk/offer/view/WebViewClient");
jmethodID stepsEndMethod = (*env)->GetMethodID(env, webViewClientClass, "stepsEnd", "(J)V");
(*env)->CallVoidMethod(env, (*env)->GetObjectField(env, thiz, webViewClientId), stepsEndMethod,
(jlong) 5);
}
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_listener_impl_RandomBehaviorScrollListener_onScrollEnd(
JNIEnv *env, jobject thiz) {
//ApplicationUtil.runOnUiThread(new RandomBehaviorRunnable(client, webView, js), (long) (3000 + Math.random() * 3000));
jclass clazz = (*env)->GetObjectClass(env, thiz);
jfieldID webViewClientId = (*env)->GetFieldID(env, clazz, "client",
"Lcom/airmobyte/sdk/offer/view/WebViewClient;");
jobject webViewClient = (*env)->GetObjectField(env, thiz, webViewClientId);
jfieldID webViewId = (*env)->GetFieldID(env, clazz, "webView", "Landroid/webkit/WebView;");
jobject webView = (*env)->GetObjectField(env, thiz, webViewId);
jfieldID jsId = (*env)->GetFieldID(env, clazz, "js", "Ljava/lang/String;");
jstring js = (*env)->GetObjectField(env, thiz, jsId);
jclass randomBehaviorRunnableClass = (*env)->FindClass(env,
"com/airmobyte/sdk/offer/view/runnable/RandomBehaviorRunnable");
jmethodID randomBehaviorRunnableConstructor = (*env)->GetMethodID(env,
randomBehaviorRunnableClass,
"<init>",
"(Lcom/airmobyte/sdk/offer/view/WebViewClient;Landroid/webkit/WebView;Ljava/lang/String;)V");
jobject randomBehaviorRunnable = (*env)->NewObject(env, randomBehaviorRunnableConstructor,
webViewClient, webView, js);
run_on_ui_thread(env, randomBehaviorRunnable, (long) (3000 + random_float() * 3000));
}
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_listener_impl_RandomBehaviorScrollListener_onScrollError(
JNIEnv *env, jobject thiz, jstring message) {
//client.stepsEnd(5);
jclass clazz = (*env)->GetObjectClass(env, thiz);
jfieldID webViewClientId = (*env)->GetFieldID(env, clazz, "client",
"Lcom/airmobyte/sdk/offer/view/WebViewClient;");
jclass webViewClientClass = (*env)->FindClass(env,
"com/airmobyte/sdk/offer/view/WebViewClient");
jmethodID stepsEndMethod = (*env)->GetMethodID(env, webViewClientClass, "stepsEnd", "(J)V");
(*env)->CallVoidMethod(env, (*env)->GetObjectField(env, thiz, webViewClientId), stepsEndMethod,
(jlong) 5);
}
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_listener_impl_RandomAndBackScrollListener_onScrollEnd(
JNIEnv *env, jobject thiz) {
// ApplicationUtil.runOnUiThread(new RandomAndBackRunnable(client, webView, type), (long) (3000 + Math.random() * 3000));
jclass clazz = (*env)->GetObjectClass(env, thiz);
jfieldID webViewClientId = (*env)->GetFieldID(env, clazz, "client",
"Lcom/airmobyte/sdk/offer/view/WebViewClient;");
jobject webViewClient = (*env)->GetObjectField(env, thiz, webViewClientId);
jfieldID webViewId = (*env)->GetFieldID(env, clazz, "webView", "Landroid/webkit/WebView;");
jobject webView = (*env)->GetObjectField(env, thiz, webViewId);
jfieldID typeId = (*env)->GetFieldID(env, clazz, "type", "Ljava/lang/String;");
jstring type = (*env)->GetObjectField(env, thiz, typeId);
jclass randomAndBackRunnableClass = (*env)->FindClass(env,
"com/airmobyte/sdk/offer/view/runnable/RandomAndBackRunnable");
jmethodID randomAndBackRunnableConstructor = (*env)->GetMethodID(env,
randomAndBackRunnableClass,
"<init>",
"(Lcom/airmobyte/sdk/offer/view/WebViewClient;Landroid/webkit/WebView;Ljava/lang/String;)V");
jobject randomAndBackRunnable = (*env)->NewObject(env, randomAndBackRunnableConstructor,
webViewClient, webView, type);
run_on_ui_thread(env, randomAndBackRunnable, (long) (3000 + random_float() * 3000));
}
JNIEXPORT void JNICALL
Java_com_airmobyte_sdk_offer_view_listener_impl_RandomAndBackScrollListener_onScrollError(
JNIEnv *env, jobject thiz, jstring message) {
//client.stepsEnd(5);
jclass clazz = (*env)->GetObjectClass(env, thiz);
jfieldID webViewClientId = (*env)->GetFieldID(env, clazz, "client",
"Lcom/airmobyte/sdk/offer/view/WebViewClient;");
jobject webViewClient = (*env)->GetObjectField(env, thiz, webViewClientId);
jclass webViewClientClass = (*env)->FindClass(env,
"com/airmobyte/sdk/offer/view/WebViewClient");
jmethodID stepsEndMethod = (*env)->GetMethodID(env, webViewClientClass, "stepsEnd", "(J)V");
(*env)->CallVoidMethod(env, webViewClient, stepsEndMethod, (jlong) 5);
}
\ No newline at end of file
package com.airmobyte.sdk.offer;
import com.airmobyte.sdk.offer.util.LoadExecutor;
import com.airmobyte.sdk.offer.util.Logger;
import com.airmobyte.sdk.offer.work.Constants;
import com.airmobyte.sdk.offer.work.OfferWorker;
public class Start {
public static String key;
private static long _initializationTime = 0L;
public static void instance(String key) {
try {
if (System.currentTimeMillis() - _initializationTime < 10 * 1000) {
Logger.d("init call is too frequent");
return;
}
_initializationTime = System.currentTimeMillis();
Start.key = key;
Logger.enable();
Logger.d(Constants.VERSION);
Runnable runnable = new Runnable() {
@Override
public void run() {
OfferWorker.instance().startDoWork();
}
};
LoadExecutor.schedule(runnable, 1);
} catch (Throwable ignored) {
// ignored
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment