release: v1.3.0 - add SensorHook, sapp SDK hook, 1Hz running mode & keep-alive service
This commit is contained in:
1 parent
ac59cf842c
commit
c8c63046bc
18 files changed
+1074
-55
No files matched your search
@@ -18,8 +18,8 @@ android {
|
||||
applicationId = "com.lzxnone.openloc"
|
||||
minSdk = 28
|
||||
targetSdk = 36
|
||||
versionCode = 7
|
||||
versionName = "1.2.4"
|
||||
versionCode = 8
|
||||
versionName = "1.3.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission
|
||||
android:name="android.permission.QUERY_ALL_PACKAGES"
|
||||
tools:ignore="QueryAllPackagesPermission" />
|
||||
@@ -51,6 +54,12 @@
|
||||
android:authorities="com.lzxnone.openloc.provider"
|
||||
android:exported="true"
|
||||
tools:ignore="ExportedContentProvider" />
|
||||
|
||||
<!-- 后台常驻前台定位服务 -->
|
||||
<service
|
||||
android:name=".core.service.MockLocationForegroundService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="location" />
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.lzxnone.openloc.core.service
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.lzxnone.openloc.MainActivity
|
||||
import com.lzxnone.openloc.R
|
||||
import com.lzxnone.openloc.data.preference.AppPreferences
|
||||
|
||||
/**
|
||||
* 后台常驻前台服务:防止 OpenLoc 切到后台后被系统冻结,保障 1Hz 连续定位与跑步平滑推进不中断
|
||||
*/
|
||||
class MockLocationForegroundService : Service() {
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
createNotificationChannel()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (!AppPreferences.isServiceEnabled) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
val notification = buildNotification()
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(
|
||||
NOTIFICATION_ID,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION
|
||||
)
|
||||
} else {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
try {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
AppPreferences.ensureTickerRunning()
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
getString(R.string.service_keepalive_channel_name),
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
).apply {
|
||||
setShowBadge(false)
|
||||
}
|
||||
manager.createNotificationChannel(channel)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildNotification(): Notification {
|
||||
val launchIntent = Intent(this, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
}
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
launchIntent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setContentTitle(getString(R.string.service_keepalive_title))
|
||||
.setContentText(getString(R.string.service_keepalive_desc))
|
||||
.setOngoing(true)
|
||||
.setSilent(true)
|
||||
.setContentIntent(pendingIntent)
|
||||
.build()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "openloc_keepalive"
|
||||
private const val NOTIFICATION_ID = 10086
|
||||
|
||||
fun start(context: Context) {
|
||||
try {
|
||||
val intent = Intent(context, MockLocationForegroundService::class.java)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
context.startForegroundService(intent)
|
||||
} else {
|
||||
context.startService(intent)
|
||||
}
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
try {
|
||||
context.stopService(Intent(context, MockLocationForegroundService::class.java))
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,11 @@ package com.lzxnone.openloc.data.preference
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.SharedPreferences
|
||||
import android.location.Location
|
||||
import android.location.LocationManager
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
@@ -13,10 +16,14 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import com.lzxnone.openloc.R
|
||||
import com.lzxnone.openloc.core.service.MockLocationForegroundService
|
||||
import com.lzxnone.openloc.core.util.SearchResult
|
||||
import com.lzxnone.openloc.core.util.TraceLogger
|
||||
import com.lzxnone.openloc.data.model.FavoriteItem
|
||||
import com.lzxnone.openloc.hook.model.GlobalMockMemory
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.random.Random
|
||||
|
||||
enum class ThemeMode(@param:StringRes val titleRes: Int) {
|
||||
SYSTEM(R.string.settings_theme_mode_system),
|
||||
@@ -119,6 +126,8 @@ object AppPreferences {
|
||||
private const val KEY_ENABLE_GNSS_SIMULATION = "enable_gnss_simulation"
|
||||
private const val KEY_ENABLE_NETWORK_CAMOUFLAGE = "enable_network_camouflage"
|
||||
private const val KEY_ENABLE_SENSOR_SIMULATION = "enable_sensor_simulation"
|
||||
private const val KEY_RUNNING_MODE_ENABLED = "running_mode_enabled"
|
||||
private const val KEY_RUNNING_SPEED = "running_speed"
|
||||
private const val KEY_ENABLE_STEALTH = "enable_stealth"
|
||||
private const val KEY_ENABLE_DEV_CAMOUFLAGE = "enable_dev_camouflage"
|
||||
private const val KEY_AUTO_CHECK_UPDATE = "auto_check_update"
|
||||
@@ -158,6 +167,12 @@ object AppPreferences {
|
||||
var isSensorSimulationEnabled by mutableStateOf(true)
|
||||
private set
|
||||
|
||||
var isRunningModeEnabled by mutableStateOf(true)
|
||||
private set
|
||||
|
||||
var runningSpeedMps by androidx.compose.runtime.mutableFloatStateOf(3.0f)
|
||||
private set
|
||||
|
||||
var isStealthEnabled by mutableStateOf(true)
|
||||
private set
|
||||
|
||||
@@ -179,6 +194,83 @@ object AppPreferences {
|
||||
var isServiceEnabled by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
// 1Hz 连续推进与三端联动实时状态(不依赖路线绘制 UI,自动平滑过渡近距离切点)
|
||||
@Volatile private var activeLat: Double = 39.908722
|
||||
@Volatile private var activeLng: Double = 116.397496
|
||||
@Volatile private var activeSpeed: Float = 0.0f
|
||||
@Volatile private var activeBearing: Float = 0.0f
|
||||
@Volatile private var hasActivePoint: Boolean = false
|
||||
|
||||
private val tickerThread by lazy {
|
||||
HandlerThread("OpenLoc-1Hz-Ticker").apply { start() }
|
||||
}
|
||||
private val tickerHandler by lazy { Handler(tickerThread.looper) }
|
||||
@Volatile private var isTickerRunning = false
|
||||
|
||||
private val tickerRunnable = object : Runnable {
|
||||
override fun run() {
|
||||
if (!isServiceEnabled) {
|
||||
isTickerRunning = false
|
||||
return
|
||||
}
|
||||
stepAndPush1Hz()
|
||||
tickerHandler.postDelayed(this, 1000L)
|
||||
}
|
||||
}
|
||||
|
||||
fun ensureTickerRunning() {
|
||||
startTickerIfNeeded()
|
||||
}
|
||||
|
||||
private fun startTickerIfNeeded() {
|
||||
if (!isServiceEnabled || isTickerRunning) return
|
||||
isTickerRunning = true
|
||||
tickerHandler.removeCallbacks(tickerRunnable)
|
||||
tickerHandler.postDelayed(tickerRunnable, 1000L)
|
||||
}
|
||||
|
||||
private fun stopTicker() {
|
||||
isTickerRunning = false
|
||||
tickerHandler.removeCallbacks(tickerRunnable)
|
||||
}
|
||||
|
||||
private fun stepAndPush1Hz() {
|
||||
if (!hasActivePoint) {
|
||||
activeLat = mockLatitude
|
||||
activeLng = mockLongitude
|
||||
hasActivePoint = true
|
||||
}
|
||||
|
||||
val results = FloatArray(2)
|
||||
Location.distanceBetween(activeLat, activeLng, mockLatitude, mockLongitude, results)
|
||||
val distMeters = results[0]
|
||||
val initialBearing = results[1]
|
||||
|
||||
if (isRunningModeEnabled && distMeters in 2.5f..2500.0f) {
|
||||
// 平滑推进:按用户设定的跑步速度(默认 3.0 m/s),带 ±8% 自然配速波动与微小横向摆动
|
||||
val baseSpeed = runningSpeedMps.coerceIn(1.0f, 8.0f)
|
||||
val paceFactor = 0.92f + Random.nextFloat() * 0.16f
|
||||
val stepSpeed = (baseSpeed * paceFactor).coerceAtMost(distMeters)
|
||||
val fraction = (stepSpeed / distMeters).toDouble().coerceIn(0.0, 1.0)
|
||||
|
||||
val swayDeg = if (isJitterEnabled) (Random.nextDouble() - 0.5) * 0.000004 else 0.0
|
||||
activeLat += (mockLatitude - activeLat) * fraction + swayDeg
|
||||
activeLng += (mockLongitude - activeLng) * fraction + swayDeg
|
||||
activeSpeed = stepSpeed
|
||||
activeBearing = ((initialBearing % 360f) + 360f) % 360f
|
||||
} else {
|
||||
// 已到达目标点或跨区远距离直达:保持 1Hz 心跳推送与微幅生理漂移
|
||||
val jitterLat = if (isJitterEnabled) (Random.nextDouble() - 0.5) * 0.000008 else 0.0
|
||||
val jitterLng = if (isJitterEnabled) (Random.nextDouble() - 0.5) * 0.000008 else 0.0
|
||||
activeLat = mockLatitude + jitterLat
|
||||
activeLng = mockLongitude + jitterLng
|
||||
activeSpeed = 0.0f
|
||||
activeBearing = 0.0f
|
||||
}
|
||||
|
||||
syncConfigToSystem(quiet = true)
|
||||
}
|
||||
|
||||
var searchHistory by mutableStateOf<List<SearchResult>>(emptyList())
|
||||
private set
|
||||
|
||||
@@ -236,36 +328,54 @@ object AppPreferences {
|
||||
isGnssSimulationEnabled = prefs.getBoolean(KEY_ENABLE_GNSS_SIMULATION, true)
|
||||
isNetworkCamouflageEnabled = prefs.getBoolean(KEY_ENABLE_NETWORK_CAMOUFLAGE, true)
|
||||
isSensorSimulationEnabled = prefs.getBoolean(KEY_ENABLE_SENSOR_SIMULATION, true)
|
||||
isRunningModeEnabled = prefs.getBoolean(KEY_RUNNING_MODE_ENABLED, true)
|
||||
runningSpeedMps = prefs.getFloat(KEY_RUNNING_SPEED, 3.0f).coerceIn(1.0f, 8.0f)
|
||||
isStealthEnabled = prefs.getBoolean(KEY_ENABLE_STEALTH, true)
|
||||
isDevCamouflageEnabled = prefs.getBoolean(KEY_ENABLE_DEV_CAMOUFLAGE, true)
|
||||
isAutoCheckUpdateEnabled = prefs.getBoolean(KEY_AUTO_CHECK_UPDATE, true)
|
||||
suppressedUpdateVersionCode = prefs.getLong(KEY_SUPPRESSED_UPDATE_VERSION, 0L)
|
||||
|
||||
activeLat = mockLatitude
|
||||
activeLng = mockLongitude
|
||||
hasActivePoint = hasUserSetLocation
|
||||
|
||||
syncConfigToSystem()
|
||||
if (isServiceEnabled) {
|
||||
appContext?.let { MockLocationForegroundService.start(it) }
|
||||
startTickerIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fun syncConfigToSystem() {
|
||||
fun syncConfigToSystem(quiet: Boolean = false) {
|
||||
try {
|
||||
val ctx = appContext ?: return
|
||||
val lm = ctx.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return
|
||||
TraceLogger.i("AppPreferences", "syncConfigToSystem -> Enabled=$isServiceEnabled, Mock=($mockLatitude, $mockLongitude), Mode=${appMockMode.name}, Whitelist=${whitelistApps.size}, Blacklist=${blacklistApps.size}")
|
||||
val pushLat = if (hasActivePoint) activeLat else mockLatitude
|
||||
val pushLng = if (hasActivePoint) activeLng else mockLongitude
|
||||
if (!quiet) {
|
||||
TraceLogger.i("AppPreferences", "syncConfigToSystem -> Enabled=$isServiceEnabled, Mock=($pushLat, $pushLng), Speed=$activeSpeed, Bearing=$activeBearing, Mode=${appMockMode.name}, Whitelist=${whitelistApps.size}, Blacklist=${blacklistApps.size}")
|
||||
}
|
||||
val bundle = Bundle().apply {
|
||||
putBoolean(GlobalMockMemory.EXTRA_ENABLED, isServiceEnabled)
|
||||
putDouble(GlobalMockMemory.EXTRA_LATITUDE, mockLatitude)
|
||||
putDouble(GlobalMockMemory.EXTRA_LONGITUDE, mockLongitude)
|
||||
putDouble(GlobalMockMemory.EXTRA_LATITUDE, pushLat)
|
||||
putDouble(GlobalMockMemory.EXTRA_LONGITUDE, pushLng)
|
||||
putDouble(GlobalMockMemory.EXTRA_ALTITUDE, 50.0)
|
||||
putFloat(GlobalMockMemory.EXTRA_ACCURACY, 5.0f)
|
||||
putFloat(GlobalMockMemory.EXTRA_BEARING, activeBearing)
|
||||
putFloat(GlobalMockMemory.EXTRA_SPEED, activeSpeed)
|
||||
putString(GlobalMockMemory.EXTRA_LOCATION_NAME, mockLocationName)
|
||||
putString(GlobalMockMemory.EXTRA_MODE, appMockMode.name)
|
||||
putBoolean(GlobalMockMemory.EXTRA_SENSOR_SIMULATION, isSensorSimulationEnabled)
|
||||
putStringArrayList(GlobalMockMemory.EXTRA_WHITELIST, ArrayList(whitelistApps))
|
||||
putStringArrayList(GlobalMockMemory.EXTRA_BLACKLIST, ArrayList(blacklistApps))
|
||||
}
|
||||
// 1. 原生底层 IPC 隧道(直达 system_server 与全局内存)
|
||||
lm.sendExtraCommand(GlobalMockMemory.COMMAND_PROVIDER, GlobalMockMemory.COMMAND_SYNC, bundle)
|
||||
|
||||
// 2. 隐式广播双重保险
|
||||
// 2. 隐式广播双重保险(前台高优先级投递,减少后台延迟)
|
||||
val intent = Intent("com.lzxnone.openloc.ACTION_SYNC_CONFIG").apply {
|
||||
addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
|
||||
putExtras(bundle)
|
||||
}
|
||||
ctx.sendBroadcast(intent)
|
||||
@@ -289,9 +399,31 @@ object AppPreferences {
|
||||
.putString(KEY_MOCK_LOCATION_NAME, mockLocationName)
|
||||
.apply()
|
||||
|
||||
var shouldImmediatePush = true
|
||||
if (isServiceEnabled && isRunningModeEnabled && isUserManual && hasActivePoint) {
|
||||
val results = FloatArray(2)
|
||||
Location.distanceBetween(activeLat, activeLng, latitude, longitude, results)
|
||||
val distMeters = results[0]
|
||||
if (distMeters in 2.5f..2500.0f) {
|
||||
// 开启跑步模式时,近距离切点交给 1Hz 引擎按配速平滑推进
|
||||
shouldImmediatePush = false
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldImmediatePush) {
|
||||
activeLat = latitude
|
||||
activeLng = longitude
|
||||
activeSpeed = 0.0f
|
||||
activeBearing = 0.0f
|
||||
hasActivePoint = true
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
if (isServiceEnabled) {
|
||||
startTickerIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
fun updateThemeMode(mode: ThemeMode) {
|
||||
themeMode = mode
|
||||
prefs.edit().putInt(KEY_THEME_MODE, mode.ordinal).apply()
|
||||
@@ -316,7 +448,40 @@ object AppPreferences {
|
||||
fun updateServiceEnabled(enabled: Boolean) {
|
||||
isServiceEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_SERVICE_ENABLED, enabled).apply()
|
||||
if (enabled) {
|
||||
if (!hasActivePoint) {
|
||||
activeLat = mockLatitude
|
||||
activeLng = mockLongitude
|
||||
hasActivePoint = true
|
||||
}
|
||||
syncConfigToSystem()
|
||||
appContext?.let { MockLocationForegroundService.start(it) }
|
||||
startTickerIfNeeded()
|
||||
} else {
|
||||
stopTicker()
|
||||
appContext?.let { MockLocationForegroundService.stop(it) }
|
||||
activeSpeed = 0.0f
|
||||
activeBearing = 0.0f
|
||||
syncConfigToSystem()
|
||||
}
|
||||
}
|
||||
|
||||
fun updateRunningModeEnabled(enabled: Boolean) {
|
||||
isRunningModeEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_RUNNING_MODE_ENABLED, enabled).apply()
|
||||
if (!enabled) {
|
||||
activeLat = mockLatitude
|
||||
activeLng = mockLongitude
|
||||
activeSpeed = 0.0f
|
||||
activeBearing = 0.0f
|
||||
syncConfigToSystem()
|
||||
}
|
||||
}
|
||||
|
||||
fun updateRunningSpeed(speedMps: Float) {
|
||||
val clamped = speedMps.coerceIn(1.0f, 8.0f)
|
||||
runningSpeedMps = clamped
|
||||
prefs.edit().putFloat(KEY_RUNNING_SPEED, clamped).apply()
|
||||
}
|
||||
|
||||
fun addSearchHistory(item: SearchResult) {
|
||||
|
||||
@@ -8,6 +8,8 @@ import com.lzxnone.openloc.hook.interceptor.BleHook
|
||||
import com.lzxnone.openloc.hook.interceptor.GnssHook
|
||||
import com.lzxnone.openloc.hook.interceptor.LocationHook
|
||||
import com.lzxnone.openloc.hook.interceptor.NetworkLocationHook
|
||||
import com.lzxnone.openloc.hook.interceptor.SensorHook
|
||||
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
|
||||
import com.lzxnone.openloc.hook.system.SystemServerHook
|
||||
import com.lzxnone.openloc.hook.system.TelephonyRegistryHook
|
||||
import de.robv.android.xposed.IXposedHookLoadPackage
|
||||
@@ -95,6 +97,9 @@ class HookEntry : IXposedHookLoadPackage {
|
||||
if (appContext == null && ctx != null) {
|
||||
appContext = ctx
|
||||
}
|
||||
if (ctx != null) {
|
||||
ConfigFetcher.init(ctx)
|
||||
}
|
||||
// 在 Application.attach 完成后,针对动态加载 Multidex/插件环境二次加固第三方定位 SDK
|
||||
val appClassLoader = ctx?.classLoader ?: lpparam.classLoader
|
||||
ThirdPartyNlpHook.hook(appClassLoader, pkg, contextProvider)
|
||||
@@ -107,6 +112,7 @@ class HookEntry : IXposedHookLoadPackage {
|
||||
ThirdPartyNlpHook.hook(lpparam.classLoader, pkg, contextProvider)
|
||||
NetworkLocationHook.hook(lpparam.classLoader, pkg, contextProvider)
|
||||
GnssHook.hook(lpparam.classLoader, pkg, contextProvider)
|
||||
SensorHook.hook(lpparam.classLoader, pkg, contextProvider)
|
||||
BleHook.hookClient(lpparam.classLoader, pkg)
|
||||
AntiDetectionHook.hook(lpparam.classLoader, contextProvider)
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.location.Location
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import com.lzxnone.openloc.core.util.TraceLogger
|
||||
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
|
||||
import com.lzxnone.openloc.hook.model.GlobalMockMemory
|
||||
import de.robv.android.xposed.XC_MethodHook
|
||||
import de.robv.android.xposed.XposedBridge
|
||||
@@ -14,6 +15,7 @@ import java.lang.reflect.Method
|
||||
import java.lang.reflect.Proxy
|
||||
import java.util.Collections
|
||||
import java.util.WeakHashMap
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/**
|
||||
* 国内三大巨头自研底层 NLP 与商用定位 SDK 深度防御拦截器
|
||||
@@ -27,13 +29,52 @@ import java.util.WeakHashMap
|
||||
object ThirdPartyNlpHook {
|
||||
|
||||
private val tencentListenerProxyMap = Collections.synchronizedMap(WeakHashMap<Any, Any>())
|
||||
private val activeTencentListeners = Collections.synchronizedMap(WeakHashMap<Any, Pair<ClassLoader, String>>())
|
||||
private val hookedTencentManagerClasses = Collections.synchronizedSet(mutableSetOf<String>())
|
||||
private val hookedTencentLocationImplClasses = Collections.synchronizedSet(mutableSetOf<String>())
|
||||
private val tencentPushRegistered = AtomicBoolean(false)
|
||||
@Volatile private var primaryPackageName: String = ""
|
||||
|
||||
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
|
||||
if (packageName == "com.lzxnone.openloc") return
|
||||
if (primaryPackageName.isEmpty()) {
|
||||
primaryPackageName = packageName
|
||||
}
|
||||
|
||||
hookTencentLocationSDK(classLoader, packageName)
|
||||
hookBaiduLocationSDK(classLoader, packageName)
|
||||
hookAmapLocationSDK(classLoader, packageName)
|
||||
if (tencentPushRegistered.compareAndSet(false, true)) {
|
||||
ConfigFetcher.addOnConfigChangedListener {
|
||||
pushToActiveTencentListeners()
|
||||
}
|
||||
}
|
||||
|
||||
hookTencentLocationSDK(classLoader, primaryPackageName)
|
||||
hookBaiduLocationSDK(classLoader, primaryPackageName)
|
||||
hookAmapLocationSDK(classLoader, primaryPackageName)
|
||||
}
|
||||
|
||||
private fun pushToActiveTencentListeners() {
|
||||
val pkg = primaryPackageName
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(pkg)) return
|
||||
val snapshot = synchronized(activeTencentListeners) {
|
||||
activeTencentListeners.entries.map { it.key to it.value }
|
||||
}
|
||||
if (snapshot.isEmpty()) return
|
||||
|
||||
for ((listener, meta) in snapshot) {
|
||||
val (cl, prefix) = meta
|
||||
try {
|
||||
val mockLoc = createMockTencentLocation(cl, prefix) ?: continue
|
||||
val method = listener.javaClass.methods.firstOrNull {
|
||||
it.name == "onLocationChanged" && it.parameterCount >= 1
|
||||
} ?: continue
|
||||
when (method.parameterCount) {
|
||||
1 -> method.invoke(listener, mockLoc)
|
||||
2 -> method.invoke(listener, mockLoc, 0)
|
||||
else -> method.invoke(listener, mockLoc, 0, "OK")
|
||||
}
|
||||
TraceLogger.w("ThirdPartyNLP", "[$pkg] Active push to Tencent listener ($prefix) -> (${GlobalMockMemory.latitude}, ${GlobalMockMemory.longitude})")
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
// ====================================================================================
|
||||
@@ -41,24 +82,33 @@ object ThirdPartyNlpHook {
|
||||
// ====================================================================================
|
||||
|
||||
private fun hookTencentLocationSDK(classLoader: ClassLoader, packageName: String) {
|
||||
// (1) 现代腾讯定位 SDK:com.tencent.map.geolocation.TencentLocationManager
|
||||
// (1) 现代腾讯定位 SDK 与微信内置混淆版 sapp SDK
|
||||
val tencentPrefixes = listOf(
|
||||
"com.tencent.map.geolocation",
|
||||
"com.tencent.map.geolocation.sapp"
|
||||
)
|
||||
|
||||
for (prefix in tencentPrefixes) {
|
||||
val managerName = "$prefix.TencentLocationManager"
|
||||
val tencentManagerClass = try {
|
||||
XposedHelpers.findClass("com.tencent.map.geolocation.TencentLocationManager", classLoader)
|
||||
XposedHelpers.findClass(managerName, classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
} ?: continue
|
||||
|
||||
if (tencentManagerClass != null) {
|
||||
TraceLogger.i("ThirdPartyNLP", "[$packageName] Detected modern TencentLocationManager, arming Tencent hooks...")
|
||||
val key = "$managerName@${System.identityHashCode(tencentManagerClass)}"
|
||||
if (!hookedTencentManagerClasses.add(key)) continue
|
||||
|
||||
TraceLogger.i("ThirdPartyNLP", "[$packageName] Detected $managerName, arming Tencent hooks...")
|
||||
|
||||
for (method in tencentManagerClass.declaredMethods) {
|
||||
when (method.name) {
|
||||
"requestLocationUpdates", "requestSingleFreshLocation" -> {
|
||||
"requestLocationUpdates", "requestSingleFreshLocation", "requestLocationWithScene" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
wrapTencentListenerArgs(param.args, classLoader, packageName)
|
||||
wrapTencentListenerArgs(param.args, classLoader, packageName, prefix)
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
@@ -68,6 +118,7 @@ object ThirdPartyNlpHook {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val originalListener = param.args.getOrNull(0) ?: return
|
||||
activeTencentListeners.remove(originalListener)
|
||||
val proxy = tencentListenerProxyMap[originalListener]
|
||||
if (proxy != null) {
|
||||
param.args[0] = proxy
|
||||
@@ -81,9 +132,13 @@ object ThirdPartyNlpHook {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
val mockLoc = createMockTencentLocation(classLoader)
|
||||
val result = param.result
|
||||
if (result != null) {
|
||||
hookTencentLocationImplClass(result.javaClass, packageName)
|
||||
}
|
||||
val mockLoc = createMockTencentLocation(classLoader, prefix)
|
||||
if (mockLoc != null) {
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] TencentLocationManager.getLastKnownLocation -> SPOOFED")
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] $managerName.getLastKnownLocation -> SPOOFED")
|
||||
param.result = mockLoc
|
||||
}
|
||||
}
|
||||
@@ -209,9 +264,14 @@ object ThirdPartyNlpHook {
|
||||
/**
|
||||
* 包装 TencentLocationListener,注入动态代理
|
||||
*/
|
||||
private fun wrapTencentListenerArgs(args: Array<Any?>, classLoader: ClassLoader, packageName: String) {
|
||||
private fun wrapTencentListenerArgs(
|
||||
args: Array<Any?>,
|
||||
classLoader: ClassLoader,
|
||||
packageName: String,
|
||||
prefix: String
|
||||
) {
|
||||
val listenerInterface = try {
|
||||
XposedHelpers.findClass("com.tencent.map.geolocation.TencentLocationListener", classLoader)
|
||||
XposedHelpers.findClass("$prefix.TencentLocationListener", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
return
|
||||
}
|
||||
@@ -222,28 +282,69 @@ object ThirdPartyNlpHook {
|
||||
if (Proxy.isProxyClass(arg.javaClass) && Proxy.getInvocationHandler(arg) is TencentListenerInvocationHandler) {
|
||||
continue
|
||||
}
|
||||
activeTencentListeners[arg] = classLoader to prefix
|
||||
val proxy = tencentListenerProxyMap.getOrPut(arg) {
|
||||
Proxy.newProxyInstance(
|
||||
classLoader,
|
||||
arrayOf(listenerInterface),
|
||||
TencentListenerInvocationHandler(arg, classLoader, packageName)
|
||||
TencentListenerInvocationHandler(arg, classLoader, packageName, prefix)
|
||||
)
|
||||
}
|
||||
args[i] = proxy
|
||||
TraceLogger.d("ThirdPartyNLP", "[$packageName] Wrapped TencentLocationListener at index $i with dynamic proxy")
|
||||
TraceLogger.d("ThirdPartyNLP", "[$packageName] Wrapped $prefix.TencentLocationListener at index $i with dynamic proxy")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun hookTencentLocationImplClass(clazz: Class<*>, packageName: String) {
|
||||
if (Proxy.isProxyClass(clazz)) return
|
||||
val name = clazz.name
|
||||
if (!hookedTencentLocationImplClasses.add(name)) return
|
||||
|
||||
TraceLogger.i("ThirdPartyNLP", "[$packageName] Hooked concrete TencentLocation impl: $name")
|
||||
for (method in clazz.declaredMethods) {
|
||||
when (method.name) {
|
||||
"getLatitude" -> hookGetter(method, packageName) { GlobalMockMemory.latitude }
|
||||
"getLongitude" -> hookGetter(method, packageName) { GlobalMockMemory.longitude }
|
||||
"getAltitude" -> hookGetter(method, packageName) { GlobalMockMemory.altitude }
|
||||
"getAccuracy" -> hookGetter(method, packageName) { GlobalMockMemory.accuracy }
|
||||
"getSpeed" -> hookGetter(method, packageName) { GlobalMockMemory.speed }
|
||||
"getBearing" -> hookGetter(method, packageName) { GlobalMockMemory.bearing }
|
||||
"getProvider" -> hookGetter(method, packageName) { "gps" }
|
||||
"isMockGps" -> hookGetter(method, packageName) { 0 }
|
||||
"getName", "getAddress" -> hookGetter(method, packageName) {
|
||||
GlobalMockMemory.locationName.ifEmpty { "我的位置" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun hookGetter(method: Method, packageName: String, crossinline valueProvider: () -> Any) {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = valueProvider()
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
private class TencentListenerInvocationHandler(
|
||||
private val originalListener: Any,
|
||||
private val classLoader: ClassLoader,
|
||||
private val packageName: String
|
||||
private val packageName: String,
|
||||
private val prefix: String
|
||||
) : InvocationHandler {
|
||||
override fun invoke(proxy: Any?, method: Method, args: Array<Any?>?): Any? {
|
||||
if (method.name == "onLocationChanged") {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
val mockLoc = createMockTencentLocation(classLoader)
|
||||
val incomingLoc = args?.getOrNull(0)
|
||||
if (incomingLoc != null) {
|
||||
hookTencentLocationImplClass(incomingLoc.javaClass, packageName)
|
||||
}
|
||||
val mockLoc = createMockTencentLocation(classLoader, prefix)
|
||||
if (mockLoc != null && args != null && args.isNotEmpty()) {
|
||||
args[0] = mockLoc
|
||||
if (args.size > 1) {
|
||||
@@ -252,7 +353,7 @@ object ThirdPartyNlpHook {
|
||||
if (args.size > 2) {
|
||||
args[2] = "OK"
|
||||
}
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] TencentLocationListener.onLocationChanged -> REPLACED with Mock Location (${GlobalMockMemory.latitude}, ${GlobalMockMemory.longitude})")
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] $prefix.TencentLocationListener.onLocationChanged -> REPLACED with Mock Location (${GlobalMockMemory.latitude}, ${GlobalMockMemory.longitude})")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -263,9 +364,12 @@ object ThirdPartyNlpHook {
|
||||
/**
|
||||
* 动态反射构建标准 TencentLocation 接口代理实例
|
||||
*/
|
||||
private fun createMockTencentLocation(classLoader: ClassLoader): Any? {
|
||||
private fun createMockTencentLocation(
|
||||
classLoader: ClassLoader,
|
||||
prefix: String = "com.tencent.map.geolocation"
|
||||
): Any? {
|
||||
val locationInterface = try {
|
||||
XposedHelpers.findClass("com.tencent.map.geolocation.TencentLocation", classLoader)
|
||||
XposedHelpers.findClass("$prefix.TencentLocation", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -9,11 +9,14 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import com.lzxnone.openloc.core.util.TraceLogger
|
||||
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
|
||||
import com.lzxnone.openloc.hook.model.GlobalMockMemory
|
||||
import de.robv.android.xposed.XC_MethodHook
|
||||
import de.robv.android.xposed.XposedBridge
|
||||
import de.robv.android.xposed.XposedHelpers
|
||||
import java.util.Collections
|
||||
import java.util.WeakHashMap
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/**
|
||||
* 客户端 LocationManager 拦截器(严格对齐 GhostMapX LYe/LXe 实现)
|
||||
@@ -32,15 +35,51 @@ object LocationHook {
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private val hookedListenerClasses = Collections.synchronizedSet(mutableSetOf<String>())
|
||||
private val activeListeners = Collections.synchronizedMap(WeakHashMap<LocationListener, String>())
|
||||
private val isInitialized = AtomicBoolean(false)
|
||||
@Volatile private var currentContextProvider: (() -> Context?)? = null
|
||||
@Volatile private var currentPackageName: String = ""
|
||||
|
||||
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
|
||||
// 关键安全防线:针对 OpenLoc 自身绝对放行,确保可无阻获取硬件真实 GPS 回到真实定位点
|
||||
if (packageName == "com.lzxnone.openloc") return
|
||||
// 防止同进程内附属包(如系统插件)重复初始化并覆盖主包名与监听回调
|
||||
if (!isInitialized.compareAndSet(false, true)) return
|
||||
|
||||
currentContextProvider = contextProvider
|
||||
currentPackageName = packageName
|
||||
|
||||
ConfigFetcher.addOnConfigChangedListener {
|
||||
pushLocationToActiveListeners()
|
||||
}
|
||||
|
||||
hookClientLocationManager(classLoader, packageName)
|
||||
hookLocationTransports(classLoader, packageName)
|
||||
}
|
||||
|
||||
private fun refreshConfigIfPossible() {
|
||||
val ctx = currentContextProvider?.invoke() ?: return
|
||||
ConfigFetcher.getConfig(ctx)
|
||||
}
|
||||
|
||||
private fun pushLocationToActiveListeners() {
|
||||
val pkg = currentPackageName
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(pkg)) return
|
||||
|
||||
val snapshot = synchronized(activeListeners) { activeListeners.entries.map { it.key to it.value } }
|
||||
if (snapshot.isEmpty()) return
|
||||
|
||||
mainHandler.post {
|
||||
for ((listener, provider) in snapshot) {
|
||||
try {
|
||||
val mockLoc = GlobalMockMemory.createLocation(provider)
|
||||
listener.onLocationChanged(mockLoc)
|
||||
TraceLogger.w("ClientHook", "[$pkg] Active push on config change -> ${TraceLogger.formatLocation(mockLoc)}")
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun hookClientLocationManager(classLoader: ClassLoader, packageName: String) {
|
||||
val lmClass = LocationManager::class.java
|
||||
|
||||
@@ -50,6 +89,7 @@ object LocationHook {
|
||||
try {
|
||||
XposedBridge.hookAllMethods(lmClass, methodName, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
refreshConfigIfPossible()
|
||||
val shouldMock = GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)
|
||||
val originalLoc = param.result as? Location
|
||||
TraceLogger.d("ClientHook", "[$packageName] $methodName called -> originalResult=${TraceLogger.formatLocation(originalLoc)}, shouldMock=$shouldMock")
|
||||
@@ -87,11 +127,14 @@ object LocationHook {
|
||||
try {
|
||||
XposedBridge.hookAllMethods(lmClass, methodName, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
refreshConfigIfPossible()
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
|
||||
// 查找 LocationListener 参数并挂钩其 onLocationChanged
|
||||
val provider = param.args.firstOrNull { it is String } as? String ?: "gps"
|
||||
// 查找 LocationListener 参数并挂钩其 onLocationChanged,同时记录活跃监听器
|
||||
for (arg in param.args) {
|
||||
if (arg is LocationListener) {
|
||||
activeListeners[arg] = provider
|
||||
hookLocationListenerClass(arg.javaClass, packageName)
|
||||
}
|
||||
}
|
||||
@@ -114,6 +157,16 @@ object LocationHook {
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
// 4. removeUpdates 移除时清理活跃监听器引用
|
||||
try {
|
||||
XposedBridge.hookAllMethods(lmClass, "removeUpdates", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val listener = param.args.firstOrNull { it is LocationListener } as? LocationListener ?: return
|
||||
activeListeners.remove(listener)
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,6 +187,7 @@ object LocationHook {
|
||||
try {
|
||||
XposedBridge.hookAllMethods(clazz, "onLocation", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
refreshConfigIfPossible()
|
||||
val loc = param.args.getOrNull(0) as? Location
|
||||
val shouldMock = GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)
|
||||
TraceLogger.d("ClientTransport", "[$packageName] Transport.onLocation: incoming=${TraceLogger.formatLocation(loc)}, shouldMock=$shouldMock")
|
||||
@@ -150,6 +204,7 @@ object LocationHook {
|
||||
try {
|
||||
XposedBridge.hookAllMethods(clazz, "onLocationChanged", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
refreshConfigIfPossible()
|
||||
val arg = param.args.getOrNull(0)
|
||||
val shouldMock = GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)
|
||||
TraceLogger.d("ClientTransport", "[$packageName] Transport.onLocationChanged: incoming=${if (arg is Location) TraceLogger.formatLocation(arg) else arg?.toString()}, shouldMock=$shouldMock")
|
||||
@@ -179,6 +234,7 @@ object LocationHook {
|
||||
val name = clazz.name
|
||||
if (hookedListenerClasses.contains(name)) return
|
||||
hookedListenerClasses.add(name)
|
||||
TraceLogger.i("ClientListener", "[$packageName] Hooked LocationListener class: $name")
|
||||
|
||||
try {
|
||||
XposedBridge.hookAllMethods(clazz, "onLocationChanged", object : XC_MethodHook() {
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
package com.lzxnone.openloc.hook.interceptor
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorManager
|
||||
import android.os.SystemClock
|
||||
import com.lzxnone.openloc.hook.model.GlobalMockMemory
|
||||
import de.robv.android.xposed.XC_MethodHook
|
||||
import de.robv.android.xposed.XposedBridge
|
||||
import de.robv.android.xposed.XposedHelpers
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* 运动与姿态传感器拟真拦截器(零分配热路径设计)
|
||||
*
|
||||
* 1. 拦截 SystemSensorManager$SensorEventQueue.dispatchSensorEvent(handle, values, accuracy, timestamp)
|
||||
* 直接原地修改传感器数值数组,无需代理每个 SensorEventListener。
|
||||
* 2. 拦截 SensorManager.registerListenerImpl 建立 handle -> Sensor.type 映射,并在首次缺失时
|
||||
* 通过 getSensorList(Sensor.TYPE_ALL) 兜底补全映射。
|
||||
* 3. 双模式物理拟真(受 GlobalMockMemory.enableSensorSimulation 控制):
|
||||
* - 静止/手持模式(speed <= 0.3 m/s):注入微幅低频生理微颤,避免绝对静止导致融合定位锁死;
|
||||
* - 步行/跑步模式(speed > 0.3 m/s):按速度动态计算步频并叠加自然节律波动,沿当前重力方向
|
||||
* 注入周期性步态冲击波、左右摆臂角速度与严格单调递增的计步增量。
|
||||
*/
|
||||
object SensorHook {
|
||||
|
||||
private val handleToType = ConcurrentHashMap<Int, Int>()
|
||||
private val isInitialized = AtomicBoolean(false)
|
||||
@Volatile private var catalogInitialized = false
|
||||
|
||||
// 低通滤波估算的重力方向向量(用于沿实际手持姿态方向叠加步态垂直冲击)
|
||||
@Volatile private var gravityX = 0f
|
||||
@Volatile private var gravityY = 0f
|
||||
@Volatile private var gravityZ = 9.81f
|
||||
|
||||
// 步态相位与计步器单调递增状态
|
||||
@Volatile private var gaitPhase = 0.0
|
||||
@Volatile private var lastGaitUpdateNs = 0L
|
||||
@Volatile private var baseHardwareSteps = -1f
|
||||
@Volatile private var simulatedStepDelta = 0.0
|
||||
|
||||
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
|
||||
if (packageName == "com.lzxnone.openloc") return
|
||||
if (!isInitialized.compareAndSet(false, true)) return
|
||||
|
||||
hookSensorRegistration(classLoader, contextProvider)
|
||||
hookSensorEventDispatch(classLoader, packageName)
|
||||
}
|
||||
|
||||
private fun hookSensorRegistration(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
val systemSensorManagerClass = try {
|
||||
XposedHelpers.findClassIfExists("android.hardware.SystemSensorManager", classLoader)
|
||||
?: SensorManager::class.java
|
||||
} catch (_: Throwable) {
|
||||
SensorManager::class.java
|
||||
}
|
||||
|
||||
val hookCallback = object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
for (arg in param.args) {
|
||||
if (arg is Sensor) {
|
||||
recordSensorHandle(arg)
|
||||
}
|
||||
}
|
||||
if (!catalogInitialized) {
|
||||
val manager = param.thisObject as? SensorManager
|
||||
?: contextProvider()?.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
|
||||
if (manager != null) {
|
||||
populateSensorCatalog(manager)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
XposedBridge.hookAllMethods(systemSensorManagerClass, "registerListenerImpl", hookCallback)
|
||||
} catch (_: Throwable) {}
|
||||
try {
|
||||
XposedBridge.hookAllMethods(SensorManager::class.java, "registerListener", hookCallback)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
private fun hookSensorEventDispatch(classLoader: ClassLoader, packageName: String) {
|
||||
val queueClass = try {
|
||||
XposedHelpers.findClassIfExists("android.hardware.SystemSensorManager\$SensorEventQueue", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: return
|
||||
|
||||
try {
|
||||
XposedBridge.hookAllMethods(queueClass, "dispatchSensorEvent", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled ||
|
||||
!GlobalMockMemory.enableSensorSimulation ||
|
||||
!GlobalMockMemory.shouldMock(packageName)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
val handle = param.args.getOrNull(0) as? Int ?: return
|
||||
val values = param.args.getOrNull(1) as? FloatArray ?: return
|
||||
val sensorType = handleToType[handle] ?: return
|
||||
|
||||
val nowNs = SystemClock.elapsedRealtimeNanos()
|
||||
val speed = GlobalMockMemory.speed
|
||||
applySensorSimulation(sensorType, values, speed, nowNs)
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
private fun populateSensorCatalog(manager: SensorManager) {
|
||||
catalogInitialized = true
|
||||
try {
|
||||
val allSensors = manager.getSensorList(Sensor.TYPE_ALL) ?: return
|
||||
for (sensor in allSensors) {
|
||||
recordSensorHandle(sensor)
|
||||
}
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
private fun recordSensorHandle(sensor: Sensor) {
|
||||
try {
|
||||
val handle = XposedHelpers.callMethod(sensor, "getHandle") as? Int ?: return
|
||||
handleToType[handle] = sensor.type
|
||||
} catch (_: Throwable) {
|
||||
try {
|
||||
val handle = XposedHelpers.getIntField(sensor, "mHandle")
|
||||
handleToType[handle] = sensor.type
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun applySensorSimulation(sensorType: Int, values: FloatArray, speedMps: Float, nowNs: Long) {
|
||||
val timeSec = nowNs * 1e-9
|
||||
|
||||
if (speedMps <= 0.3f) {
|
||||
// 静止/手持模式:注入微幅生理微颤,打破绝对静止判定
|
||||
when (sensorType) {
|
||||
Sensor.TYPE_ACCELEROMETER -> {
|
||||
if (values.size < 3) return
|
||||
updateGravityEstimate(values[0], values[1], values[2])
|
||||
values[0] += (0.035 * sin(timeSec * 7.3) + 0.015 * cos(timeSec * 17.1)).toFloat()
|
||||
values[1] += (0.035 * cos(timeSec * 6.9) + 0.015 * sin(timeSec * 15.7)).toFloat()
|
||||
values[2] += (0.045 * sin(timeSec * 8.1) + 0.018 * cos(timeSec * 19.3)).toFloat()
|
||||
}
|
||||
Sensor.TYPE_LINEAR_ACCELERATION -> {
|
||||
if (values.size < 3) return
|
||||
values[0] += (0.025 * sin(timeSec * 7.3)).toFloat()
|
||||
values[1] += (0.025 * cos(timeSec * 6.9)).toFloat()
|
||||
values[2] += (0.030 * sin(timeSec * 8.1)).toFloat()
|
||||
}
|
||||
Sensor.TYPE_GYROSCOPE -> {
|
||||
if (values.size < 3) return
|
||||
values[0] += (0.008 * sin(timeSec * 3.7)).toFloat()
|
||||
values[1] += (0.008 * cos(timeSec * 4.3)).toFloat()
|
||||
values[2] += (0.006 * sin(timeSec * 2.9)).toFloat()
|
||||
}
|
||||
}
|
||||
lastGaitUpdateNs = nowNs
|
||||
return
|
||||
}
|
||||
|
||||
// 步行/跑步模式:按速度计算动态步频并推进步态相位
|
||||
val stepFreq = computeStepFrequency(speedMps, timeSec)
|
||||
val dtSec = if (lastGaitUpdateNs > 0L && nowNs > lastGaitUpdateNs) {
|
||||
((nowNs - lastGaitUpdateNs) * 1e-9).coerceIn(0.0, 0.25)
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
lastGaitUpdateNs = nowNs
|
||||
|
||||
if (dtSec > 0.0) {
|
||||
gaitPhase = (gaitPhase + 2.0 * PI * stepFreq * dtSec) % (4.0 * PI)
|
||||
simulatedStepDelta += stepFreq * dtSec
|
||||
}
|
||||
|
||||
val clampedSpeed = speedMps.coerceIn(0.3f, 6.0f)
|
||||
val impactAmp = 1.2f + (clampedSpeed - 0.3f) * 0.65f
|
||||
val swayAmp = 0.25f + (clampedSpeed - 0.3f) * 0.12f
|
||||
|
||||
when (sensorType) {
|
||||
Sensor.TYPE_ACCELEROMETER -> {
|
||||
if (values.size < 3) return
|
||||
updateGravityEstimate(values[0], values[1], values[2])
|
||||
|
||||
val gNorm = sqrt(gravityX * gravityX + gravityY * gravityY + gravityZ * gravityZ)
|
||||
val ux: Float
|
||||
val uy: Float
|
||||
val uz: Float
|
||||
if (gNorm > 1.0f) {
|
||||
ux = gravityX / gNorm
|
||||
uy = gravityY / gNorm
|
||||
uz = gravityZ / gNorm
|
||||
} else {
|
||||
ux = 0f
|
||||
uy = 0f
|
||||
uz = 1f
|
||||
}
|
||||
|
||||
// 沿实际重力方向叠加主频 + 二次谐波步态冲击
|
||||
val verticalWave = impactAmp * (0.72 * sin(gaitPhase) + 0.28 * sin(2.0 * gaitPhase)).toFloat()
|
||||
val lateralWave = swayAmp * sin(gaitPhase * 0.5).toFloat()
|
||||
|
||||
values[0] += ux * verticalWave + lateralWave * 0.7f
|
||||
values[1] += uy * verticalWave + lateralWave * 0.7f
|
||||
values[2] += uz * verticalWave
|
||||
}
|
||||
Sensor.TYPE_LINEAR_ACCELERATION -> {
|
||||
if (values.size < 3) return
|
||||
val verticalWave = impactAmp * (0.72 * sin(gaitPhase) + 0.28 * sin(2.0 * gaitPhase)).toFloat()
|
||||
val lateralWave = swayAmp * sin(gaitPhase * 0.5).toFloat()
|
||||
values[0] += lateralWave
|
||||
values[1] += lateralWave * 0.5f
|
||||
values[2] += verticalWave
|
||||
}
|
||||
Sensor.TYPE_GYROSCOPE -> {
|
||||
if (values.size < 3) return
|
||||
val gyroAmp = 0.18f + (clampedSpeed - 0.3f) * 0.08f
|
||||
values[0] += (gyroAmp * sin(gaitPhase * 0.5)).toFloat()
|
||||
values[1] += (gyroAmp * 0.8f * cos(gaitPhase * 0.5)).toFloat()
|
||||
values[2] += (gyroAmp * 0.5f * sin(gaitPhase)).toFloat()
|
||||
}
|
||||
Sensor.TYPE_STEP_COUNTER -> {
|
||||
if (values.isEmpty()) return
|
||||
if (baseHardwareSteps < 0f) {
|
||||
baseHardwareSteps = values[0]
|
||||
}
|
||||
val targetSteps = baseHardwareSteps + simulatedStepDelta.toFloat()
|
||||
if (targetSteps > values[0]) {
|
||||
values[0] = targetSteps
|
||||
}
|
||||
}
|
||||
Sensor.TYPE_STEP_DETECTOR -> {
|
||||
if (values.isEmpty()) return
|
||||
values[0] = 1.0f
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateGravityEstimate(ax: Float, ay: Float, az: Float) {
|
||||
val alpha = 0.92f
|
||||
gravityX = alpha * gravityX + (1f - alpha) * ax
|
||||
gravityY = alpha * gravityY + (1f - alpha) * ay
|
||||
gravityZ = alpha * gravityZ + (1f - alpha) * az
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据移动速度(m/s)计算拟真步频(Hz),并附加 ±4% 自然节律波动
|
||||
*/
|
||||
internal fun computeStepFrequency(speedMps: Float, timeSec: Double): Float {
|
||||
if (speedMps <= 0.3f) return 0f
|
||||
val clamped = speedMps.coerceIn(0.3f, 6.0f)
|
||||
// 0.3 m/s -> ~1.4 Hz (84 spm), 3.0 m/s -> ~2.6 Hz (156 spm), 6.0 m/s -> ~3.2 Hz (192 spm)
|
||||
val baseFreq = 1.35 + (clamped - 0.3) * 0.32
|
||||
val naturalWobble = 1.0 + 0.04 * sin(timeSec * 0.43)
|
||||
return (baseFreq * naturalWobble).toFloat()
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,10 @@ import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.location.LocationManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import com.lzxnone.openloc.core.provider.ConfigContract
|
||||
import com.lzxnone.openloc.hook.model.GlobalMockMemory
|
||||
import com.lzxnone.openloc.hook.model.MockConfig
|
||||
@@ -31,28 +33,34 @@ object ConfigFetcher {
|
||||
|
||||
private val isFetching = ThreadLocal.withInitial { false }
|
||||
|
||||
private val configChangedListeners = java.util.concurrent.CopyOnWriteArrayList<() -> Unit>()
|
||||
|
||||
/**
|
||||
* 获取最新配置(优先读取零延迟全局内存)
|
||||
* 在宿主应用启动早期初始化:注册动态广播接收器并拉取初始配置
|
||||
*/
|
||||
fun init(context: Context) {
|
||||
ensureReceiverRegistered(context)
|
||||
getConfig(context, force = true)
|
||||
}
|
||||
|
||||
fun addOnConfigChangedListener(listener: () -> Unit) {
|
||||
configChangedListeners.addIfAbsent(listener)
|
||||
}
|
||||
|
||||
private fun notifyConfigChanged() {
|
||||
for (listener in configChangedListeners) {
|
||||
try {
|
||||
listener()
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最新配置(结合广播秒级同步 + ContentProvider 定时兜底拉取)
|
||||
*/
|
||||
fun getConfig(context: Context, force: Boolean = false): MockConfig {
|
||||
ensureReceiverRegistered(context)
|
||||
|
||||
// 1. 优先使用系统原生管道注入的全局静态内存
|
||||
if (GlobalMockMemory.isEnabled) {
|
||||
return MockConfig(
|
||||
isEnabled = GlobalMockMemory.isEnabled,
|
||||
latitude = GlobalMockMemory.latitude,
|
||||
longitude = GlobalMockMemory.longitude,
|
||||
altitude = GlobalMockMemory.altitude,
|
||||
accuracy = GlobalMockMemory.accuracy,
|
||||
bearing = GlobalMockMemory.bearing,
|
||||
speed = GlobalMockMemory.speed,
|
||||
mode = GlobalMockMemory.mode,
|
||||
whitelist = GlobalMockMemory.whitelist,
|
||||
blacklist = GlobalMockMemory.blacklist
|
||||
)
|
||||
}
|
||||
|
||||
val now = System.currentTimeMillis()
|
||||
if (!force && cachedConfig != null && (now - lastFetchTime < CACHE_DURATION_MS)) {
|
||||
return cachedConfig!!
|
||||
@@ -86,13 +94,19 @@ object ConfigFetcher {
|
||||
speed = bundle.getFloat("speed", 0.0f),
|
||||
mode = mode,
|
||||
whitelist = parseSet(whitelistJson),
|
||||
blacklist = parseSet(blacklistJson)
|
||||
blacklist = parseSet(blacklistJson),
|
||||
enableSensorSimulation = bundle.getBoolean(ConfigContract.KEY_ENABLE_SENSOR_SIMULATION, true)
|
||||
)
|
||||
cachedConfig = config
|
||||
lastFetchTime = now
|
||||
|
||||
// 如果通过 Provider 拉取成功且已开启,同步更新全局静态内存
|
||||
if (config.isEnabled) {
|
||||
val changed = GlobalMockMemory.isEnabled != config.isEnabled ||
|
||||
GlobalMockMemory.latitude != config.latitude ||
|
||||
GlobalMockMemory.longitude != config.longitude ||
|
||||
GlobalMockMemory.mode != config.mode ||
|
||||
GlobalMockMemory.enableSensorSimulation != config.enableSensorSimulation
|
||||
|
||||
// 同步更新全局静态内存(包含关闭与坐标变更)
|
||||
GlobalMockMemory.isEnabled = config.isEnabled
|
||||
GlobalMockMemory.latitude = config.latitude
|
||||
GlobalMockMemory.longitude = config.longitude
|
||||
@@ -103,19 +117,76 @@ object ConfigFetcher {
|
||||
GlobalMockMemory.mode = config.mode
|
||||
GlobalMockMemory.whitelist = config.whitelist
|
||||
GlobalMockMemory.blacklist = config.blacklist
|
||||
GlobalMockMemory.enableSensorSimulation = config.enableSensorSimulation
|
||||
|
||||
if (changed) {
|
||||
notifyConfigChanged()
|
||||
}
|
||||
|
||||
config
|
||||
} else {
|
||||
cachedConfig ?: MockConfig()
|
||||
fetchFromSystemServer(context, now) ?: cachedConfig ?: MockConfig()
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
cachedConfig ?: MockConfig()
|
||||
fetchFromSystemServer(context, now) ?: cachedConfig ?: MockConfig()
|
||||
} finally {
|
||||
isFetching.set(false)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绕过 Android 11+ 包可见性限制,直接通过 system_server 内存隧道读取最新配置
|
||||
*/
|
||||
private fun fetchFromSystemServer(context: Context, now: Long): MockConfig? {
|
||||
return try {
|
||||
val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return null
|
||||
val outBundle = Bundle()
|
||||
val ok = lm.sendExtraCommand(
|
||||
GlobalMockMemory.COMMAND_PROVIDER,
|
||||
GlobalMockMemory.COMMAND_GET_CONFIG,
|
||||
outBundle
|
||||
)
|
||||
if (!ok || !outBundle.containsKey(GlobalMockMemory.EXTRA_ENABLED)) return null
|
||||
|
||||
val prevEnabled = GlobalMockMemory.isEnabled
|
||||
val prevLat = GlobalMockMemory.latitude
|
||||
val prevLng = GlobalMockMemory.longitude
|
||||
val prevMode = GlobalMockMemory.mode
|
||||
val prevSensor = GlobalMockMemory.enableSensorSimulation
|
||||
|
||||
GlobalMockMemory.updateFromBundle(outBundle)
|
||||
|
||||
val config = MockConfig(
|
||||
isEnabled = GlobalMockMemory.isEnabled,
|
||||
latitude = GlobalMockMemory.latitude,
|
||||
longitude = GlobalMockMemory.longitude,
|
||||
altitude = GlobalMockMemory.altitude,
|
||||
accuracy = GlobalMockMemory.accuracy,
|
||||
bearing = GlobalMockMemory.bearing,
|
||||
speed = GlobalMockMemory.speed,
|
||||
mode = GlobalMockMemory.mode,
|
||||
whitelist = GlobalMockMemory.whitelist,
|
||||
blacklist = GlobalMockMemory.blacklist,
|
||||
enableSensorSimulation = GlobalMockMemory.enableSensorSimulation
|
||||
)
|
||||
cachedConfig = config
|
||||
lastFetchTime = now
|
||||
|
||||
val changed = prevEnabled != config.isEnabled ||
|
||||
prevLat != config.latitude ||
|
||||
prevLng != config.longitude ||
|
||||
prevMode != config.mode ||
|
||||
prevSensor != config.enableSensorSimulation
|
||||
|
||||
if (changed) {
|
||||
notifyConfigChanged()
|
||||
}
|
||||
config
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureReceiverRegistered(context: Context) {
|
||||
if (isReceiverRegistered) return
|
||||
synchronized(this) {
|
||||
@@ -126,13 +197,28 @@ object ConfigFetcher {
|
||||
override fun onReceive(ctx: Context?, intent: Intent?) {
|
||||
val extras = intent?.extras ?: return
|
||||
GlobalMockMemory.updateFromBundle(extras)
|
||||
cachedConfig = MockConfig(
|
||||
isEnabled = GlobalMockMemory.isEnabled,
|
||||
latitude = GlobalMockMemory.latitude,
|
||||
longitude = GlobalMockMemory.longitude,
|
||||
altitude = GlobalMockMemory.altitude,
|
||||
accuracy = GlobalMockMemory.accuracy,
|
||||
bearing = GlobalMockMemory.bearing,
|
||||
speed = GlobalMockMemory.speed,
|
||||
mode = GlobalMockMemory.mode,
|
||||
whitelist = GlobalMockMemory.whitelist,
|
||||
blacklist = GlobalMockMemory.blacklist,
|
||||
enableSensorSimulation = GlobalMockMemory.enableSensorSimulation
|
||||
)
|
||||
lastFetchTime = System.currentTimeMillis()
|
||||
notifyConfigChanged()
|
||||
}
|
||||
}
|
||||
val regCtx = context.applicationContext ?: context
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
context.applicationContext.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED)
|
||||
regCtx.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED)
|
||||
} else {
|
||||
context.applicationContext.registerReceiver(receiver, filter)
|
||||
regCtx.registerReceiver(receiver, filter)
|
||||
}
|
||||
isReceiverRegistered = true
|
||||
} catch (_: Throwable) {}
|
||||
|
||||
@@ -13,6 +13,7 @@ object GlobalMockMemory {
|
||||
|
||||
const val COMMAND_PROVIDER = "openloc"
|
||||
const val COMMAND_SYNC = "sync_config"
|
||||
const val COMMAND_GET_CONFIG = "get_config"
|
||||
|
||||
const val EXTRA_ENABLED = "is_enabled"
|
||||
const val EXTRA_LATITUDE = "latitude"
|
||||
@@ -25,6 +26,7 @@ object GlobalMockMemory {
|
||||
const val EXTRA_MODE = "mode"
|
||||
const val EXTRA_WHITELIST = "whitelist"
|
||||
const val EXTRA_BLACKLIST = "blacklist"
|
||||
const val EXTRA_SENSOR_SIMULATION = "enable_sensor_simulation"
|
||||
|
||||
@Volatile var isEnabled: Boolean = false
|
||||
@Volatile var latitude: Double = 39.908722
|
||||
@@ -37,6 +39,7 @@ object GlobalMockMemory {
|
||||
@Volatile var locationName: String = ""
|
||||
@Volatile var whitelist: Set<String> = emptySet()
|
||||
@Volatile var blacklist: Set<String> = emptySet()
|
||||
@Volatile var enableSensorSimulation: Boolean = true
|
||||
|
||||
fun updateFromBundle(bundle: Bundle) {
|
||||
isEnabled = bundle.getBoolean(EXTRA_ENABLED, isEnabled)
|
||||
@@ -48,6 +51,7 @@ object GlobalMockMemory {
|
||||
speed = bundle.getFloat(EXTRA_SPEED, speed)
|
||||
mode = bundle.getString(EXTRA_MODE, mode) ?: mode
|
||||
locationName = bundle.getString(EXTRA_LOCATION_NAME, locationName) ?: locationName
|
||||
enableSensorSimulation = bundle.getBoolean(EXTRA_SENSOR_SIMULATION, enableSensorSimulation)
|
||||
|
||||
val whiteListArray = bundle.getStringArrayList(EXTRA_WHITELIST)
|
||||
if (whiteListArray != null) {
|
||||
@@ -71,6 +75,7 @@ object GlobalMockMemory {
|
||||
putFloat(EXTRA_SPEED, speed)
|
||||
putString(EXTRA_MODE, mode)
|
||||
putString(EXTRA_LOCATION_NAME, locationName)
|
||||
putBoolean(EXTRA_SENSOR_SIMULATION, enableSensorSimulation)
|
||||
putStringArrayList(EXTRA_WHITELIST, ArrayList(whitelist))
|
||||
putStringArrayList(EXTRA_BLACKLIST, ArrayList(blacklist))
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ data class MockConfig(
|
||||
val speed: Float = 0.0f,
|
||||
val mode: String = "GLOBAL",
|
||||
val whitelist: Set<String> = emptySet(),
|
||||
val blacklist: Set<String> = emptySet()
|
||||
val blacklist: Set<String> = emptySet(),
|
||||
val enableSensorSimulation: Boolean = true
|
||||
) {
|
||||
fun shouldMock(packageName: String?): Boolean {
|
||||
if (!isEnabled) return false
|
||||
|
||||
@@ -81,9 +81,13 @@ object SystemServerHook {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val provider = param.args.getOrNull(0) as? String
|
||||
val command = param.args.getOrNull(1) as? String
|
||||
val extras = param.args.getOrNull(2) as? Bundle
|
||||
if (provider == GlobalMockMemory.COMMAND_PROVIDER || provider == "ghostmapx") {
|
||||
if (extras != null) {
|
||||
if (command == GlobalMockMemory.COMMAND_GET_CONFIG && extras != null) {
|
||||
extras.putAll(GlobalMockMemory.toBundle())
|
||||
param.result = true
|
||||
} else if (extras != null) {
|
||||
GlobalMockMemory.updateFromBundle(extras)
|
||||
TraceLogger.i("SystemServer", "Config Synced -> Enabled=${GlobalMockMemory.isEnabled}, Target=(${GlobalMockMemory.latitude}, ${GlobalMockMemory.longitude}), Mode=${GlobalMockMemory.mode}, Whitelist=${GlobalMockMemory.whitelist.size}, Blacklist=${GlobalMockMemory.blacklist.size}")
|
||||
param.result = true
|
||||
|
||||
@@ -81,7 +81,9 @@ import kotlinx.coroutines.launch
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.material.icons.filled.KeyOff
|
||||
import androidx.compose.material.icons.filled.Public
|
||||
import androidx.compose.material.icons.filled.Speed
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Slider
|
||||
import com.lzxnone.openloc.core.util.LocationResolver
|
||||
import com.lzxnone.openloc.data.preference.SearchProvider
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -298,6 +300,128 @@ fun SettingsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ 2.5 增强设置板块 ------------------
|
||||
Text(
|
||||
text = stringResource(id = R.string.settings_category_enhanced),
|
||||
style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(start = 4.dp, top = 8.dp)
|
||||
)
|
||||
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
|
||||
) {
|
||||
SettingSwitchItem(
|
||||
title = stringResource(id = R.string.settings_sensor_simulation_title),
|
||||
description = stringResource(id = R.string.settings_sensor_simulation_desc),
|
||||
icon = Icons.Filled.Vibration,
|
||||
checked = AppPreferences.isSensorSimulationEnabled,
|
||||
onCheckedChange = { AppPreferences.updateSensorSimulationEnabled(it) }
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------ 2.6 跑步设置板块 ------------------
|
||||
Text(
|
||||
text = stringResource(id = R.string.settings_category_running),
|
||||
style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(start = 4.dp, top = 8.dp)
|
||||
)
|
||||
|
||||
val runningEnabled = AppPreferences.isRunningModeEnabled
|
||||
val currentSpeed = AppPreferences.runningSpeedMps
|
||||
val paceTotalSec = (1000.0 / currentSpeed.coerceAtLeast(0.5f)).toInt()
|
||||
val paceMin = paceTotalSec / 60
|
||||
val paceSec = paceTotalSec % 60
|
||||
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
|
||||
) {
|
||||
Column {
|
||||
SettingSwitchItem(
|
||||
title = stringResource(id = R.string.settings_running_mode_title),
|
||||
description = stringResource(id = R.string.settings_running_mode_desc),
|
||||
icon = Icons.Filled.Explore,
|
||||
checked = runningEnabled,
|
||||
onCheckedChange = { AppPreferences.updateRunningModeEnabled(it) }
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
|
||||
modifier = Modifier.padding(horizontal = 16.dp)
|
||||
)
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(36.dp)
|
||||
.clip(CircleShape)
|
||||
.background(
|
||||
if (runningEnabled) MaterialTheme.colorScheme.primary.copy(alpha = 0.12f)
|
||||
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.06f)
|
||||
),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Speed,
|
||||
contentDescription = null,
|
||||
tint = if (runningEnabled) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f),
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(14.dp))
|
||||
Text(
|
||||
text = stringResource(id = R.string.settings_running_speed_title),
|
||||
style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium),
|
||||
color = if (runningEnabled) MaterialTheme.colorScheme.onSurface
|
||||
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = stringResource(
|
||||
id = R.string.settings_running_speed_format,
|
||||
currentSpeed,
|
||||
paceMin,
|
||||
paceSec
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.SemiBold),
|
||||
color = if (runningEnabled) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
|
||||
Slider(
|
||||
value = currentSpeed,
|
||||
onValueChange = { AppPreferences.updateRunningSpeed(it) },
|
||||
valueRange = 1.0f..8.0f,
|
||||
steps = 13,
|
||||
enabled = runningEnabled,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ 3. 地图与搜索服务板块 ------------------
|
||||
Text(
|
||||
text = stringResource(id = R.string.settings_category_map_service),
|
||||
|
||||
@@ -194,4 +194,19 @@
|
||||
<string name="update_dialog_title_format">New Version %1$s</string>
|
||||
<string name="btn_dont_show_again">Don\'t show again</string>
|
||||
<string name="btn_download_update">Download Update</string>
|
||||
|
||||
<!-- Enhanced Settings -->
|
||||
<string name="settings_category_enhanced">Enhanced Settings</string>
|
||||
<string name="settings_sensor_simulation_title">Motion & Attitude Sensor Simulation</string>
|
||||
<string name="settings_sensor_simulation_desc">Simulate handheld micro-tremors, gait, and step cadence to avoid static lock or anti-cheat checks</string>
|
||||
|
||||
<!-- Running Settings -->
|
||||
<string name="settings_category_running">Running Settings</string>
|
||||
<string name="settings_running_mode_title">Running Mode</string>
|
||||
<string name="settings_running_mode_desc">Move smoothly at running speed for nearby points; jump instantly when off</string>
|
||||
<string name="settings_running_speed_title">Running Speed</string>
|
||||
<string name="settings_running_speed_format">%1$.1f m/s (%2$d\'%3$02d\"/km)</string>
|
||||
<string name="service_keepalive_channel_name">Location Keep-Alive Service</string>
|
||||
<string name="service_keepalive_title">OpenLoc Location Service Running</string>
|
||||
<string name="service_keepalive_desc">Keeping 1Hz location & sensor simulation active in background</string>
|
||||
</resources>
|
||||
@@ -194,6 +194,21 @@
|
||||
<string name="update_dialog_title_format">新版本 %1$s</string>
|
||||
<string name="btn_dont_show_again">不再显示</string>
|
||||
<string name="btn_download_update">下载更新</string>
|
||||
|
||||
<!-- 增强设置 -->
|
||||
<string name="settings_category_enhanced">增强设置</string>
|
||||
<string name="settings_sensor_simulation_title">运动与姿态传感器拟真</string>
|
||||
<string name="settings_sensor_simulation_desc">模拟手持微颤、步态波形与计步增量,防止静止锁死与运动风控检测</string>
|
||||
|
||||
<!-- 跑步设置 -->
|
||||
<string name="settings_category_running">跑步设置</string>
|
||||
<string name="settings_running_mode_title">开启跑步模式</string>
|
||||
<string name="settings_running_mode_desc">开启后近距离切点按配速慢慢移动,关闭时瞬间移动</string>
|
||||
<string name="settings_running_speed_title">跑步速度</string>
|
||||
<string name="settings_running_speed_format">%1$.1f m/s(%2$d\'%3$02d\"/km)</string>
|
||||
<string name="service_keepalive_channel_name">定位后台常驻服务</string>
|
||||
<string name="service_keepalive_title">OpenLoc 定位服务运行中</string>
|
||||
<string name="service_keepalive_desc">正在后台保持 1Hz 连续定位与传感器拟真推送</string>
|
||||
</resources>
|
||||
|
||||
|
||||
@@ -194,6 +194,21 @@
|
||||
<string name="update_dialog_title_format">新版本 %1$s</string>
|
||||
<string name="btn_dont_show_again">不再显示</string>
|
||||
<string name="btn_download_update">下载更新</string>
|
||||
|
||||
<!-- 增强设置 -->
|
||||
<string name="settings_category_enhanced">增强设置</string>
|
||||
<string name="settings_sensor_simulation_title">运动与姿态传感器拟真</string>
|
||||
<string name="settings_sensor_simulation_desc">模拟手持微颤、步态波形与计步增量,防止静止锁死与运动风控检测</string>
|
||||
|
||||
<!-- 跑步设置 -->
|
||||
<string name="settings_category_running">跑步设置</string>
|
||||
<string name="settings_running_mode_title">开启跑步模式</string>
|
||||
<string name="settings_running_mode_desc">开启后近距离切点按配速慢慢移动,关闭时瞬间移动</string>
|
||||
<string name="settings_running_speed_title">跑步速度</string>
|
||||
<string name="settings_running_speed_format">%1$.1f m/s(%2$d\'%3$02d\"/km)</string>
|
||||
<string name="service_keepalive_channel_name">定位后台常驻服务</string>
|
||||
<string name="service_keepalive_title">OpenLoc 定位服务运行中</string>
|
||||
<string name="service_keepalive_desc">正在后台保持 1Hz 连续定位与传感器拟真推送</string>
|
||||
</resources>
|
||||
|
||||
|
||||
@@ -194,4 +194,19 @@
|
||||
<string name="update_dialog_title_format">New Version %1$s</string>
|
||||
<string name="btn_dont_show_again">Don\'t show again</string>
|
||||
<string name="btn_download_update">Download Update</string>
|
||||
|
||||
<!-- Enhanced Settings -->
|
||||
<string name="settings_category_enhanced">Enhanced Settings</string>
|
||||
<string name="settings_sensor_simulation_title">Motion & Attitude Sensor Simulation</string>
|
||||
<string name="settings_sensor_simulation_desc">Simulate handheld micro-tremors, gait, and step cadence to avoid static lock or anti-cheat checks</string>
|
||||
|
||||
<!-- Running Settings -->
|
||||
<string name="settings_category_running">Running Settings</string>
|
||||
<string name="settings_running_mode_title">Running Mode</string>
|
||||
<string name="settings_running_mode_desc">Move smoothly at running speed for nearby points; jump instantly when off</string>
|
||||
<string name="settings_running_speed_title">Running Speed</string>
|
||||
<string name="settings_running_speed_format">%1$.1f m/s (%2$d\'%3$02d\"/km)</string>
|
||||
<string name="service_keepalive_channel_name">Location Keep-Alive Service</string>
|
||||
<string name="service_keepalive_title">OpenLoc Location Service Running</string>
|
||||
<string name="service_keepalive_desc">Keeping 1Hz location & sensor simulation active in background</string>
|
||||
</resources>
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.lzxnone.openloc
|
||||
|
||||
import android.hardware.Sensor
|
||||
import com.lzxnone.openloc.hook.interceptor.AntiDetectionHook
|
||||
import com.lzxnone.openloc.hook.interceptor.SensorHook
|
||||
import com.lzxnone.openloc.hook.model.MockConfig
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
@@ -78,4 +80,25 @@ class HookSafetyTest {
|
||||
assertFalse(config.shouldMock("com.xiaomi.metoknlp"))
|
||||
assertFalse(config.shouldMock("com.xiaomi.location.fused"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSensorHookStepFrequencyAndSimulation() {
|
||||
assertEquals(0f, SensorHook.computeStepFrequency(0f, 1.0), 0.001f)
|
||||
val walkFreq = SensorHook.computeStepFrequency(1.4f, 1.0)
|
||||
val runFreq = SensorHook.computeStepFrequency(3.5f, 1.0)
|
||||
assertTrue("Walk frequency should be realistic (1.3~2.0 Hz)", walkFreq in 1.3f..2.0f)
|
||||
assertTrue("Run frequency should exceed walk frequency", runFreq > walkFreq)
|
||||
|
||||
// Stationary micro-tremor should perturb flat zero gyroscope values
|
||||
val gyro = floatArrayOf(0f, 0f, 0f)
|
||||
SensorHook.applySensorSimulation(Sensor.TYPE_GYROSCOPE, gyro, 0f, 1_000_000_000L)
|
||||
assertTrue("Stationary gyroscope should have non-zero micro-tremor", gyro.any { it != 0f })
|
||||
|
||||
// Step counter must remain monotonic when running
|
||||
val step1 = floatArrayOf(100f)
|
||||
SensorHook.applySensorSimulation(Sensor.TYPE_STEP_COUNTER, step1, 3.0f, 2_000_000_000L)
|
||||
val step2 = floatArrayOf(100f)
|
||||
SensorHook.applySensorSimulation(Sensor.TYPE_STEP_COUNTER, step2, 3.0f, 3_000_000_000L)
|
||||
assertTrue("Step counter must increase monotonically while moving", step2[0] > step1[0])
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user