Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc60b0de15 | ||
|
|
b039f610b3 | ||
|
|
c8c63046bc | ||
|
|
ac59cf842c | ||
|
|
df9eb548cb | ||
|
|
253f3c72b1 | ||
|
|
7b0d5b802d | ||
|
|
32fa4a611a | ||
|
|
6ffa7d8108 | ||
|
|
07abd416b6 | ||
|
|
ee7b7d3666 | ||
|
|
02a206d384 | ||
|
|
8b49607efe | ||
|
|
2f5b852e00 | ||
|
|
80bba05ecf | ||
|
|
a341d862c2 | ||
|
|
b21966e5b5 | ||
|
|
4d26ffae06 | ||
|
|
22d3197309 | ||
|
|
7ad462a524 | ||
|
|
d615f5d030 | ||
|
|
4b6ae12df6 |
No files matched your search
@@ -54,6 +54,7 @@ captures/
|
||||
*.jks
|
||||
*.keystore
|
||||
keystore.properties
|
||||
keystore_base64.txt
|
||||
|
||||
# OS-specific files
|
||||
.DS_Store
|
||||
|
||||
@@ -1,44 +1,70 @@
|
||||
<div align="center">
|
||||
<p align="center">
|
||||
<img src="assets/logo.png" width="128" height="128" alt="OpenLoc Logo" />
|
||||
</p>
|
||||
|
||||
<img src="assets/logo.png" width="128" height="128" alt="OpenLoc Logo" />
|
||||
<h1 align="center">OpenLoc</h1>
|
||||
|
||||
# OpenLoc
|
||||
|
||||
专为 Android 平台设计的现代地理位置模拟与隐私辅助工具
|
||||
<p align="center">
|
||||
专为 Android 平台设计的现代地理位置模拟与隐私辅助工具
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/Platform-Android-3DDC84?style=flat-square&logo=android&logoColor=white" alt="Platform" />
|
||||
<img src="https://img.shields.io/badge/Language-Kotlin-7F52FF?style=flat-square&logo=kotlin&logoColor=white" alt="Language" />
|
||||
<img src="https://img.shields.io/badge/UI-Jetpack_Compose_/_Material_3-4285F4?style=flat-square&logo=jetpackcompose&logoColor=white" alt="UI" />
|
||||
<img src="https://img.shields.io/badge/Privacy-Local_Only-00C853?style=flat-square" alt="Privacy" />
|
||||
<img src="https://img.shields.io/badge/UI-Jetpack%20Compose%20%2F%20Material%203-4285F4?style=flat-square&logo=jetpackcompose&logoColor=white" alt="UI" />
|
||||
<br>
|
||||
<img src="https://img.shields.io/badge/Privacy-Local%20Only-00C853?style=flat-square" alt="Privacy" />
|
||||
<img src="https://img.shields.io/badge/License-GPL--3.0-007AFF?style=flat-square" alt="License" />
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<p align="center">
|
||||
<b>简体中文</b> | <a href="README_EN.md">English</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## 软件用途
|
||||
OpenLoc 旨在为开发者、测试人员以及关注个人数字隐私的用户提供安全、可控且纯净的位置环境模拟服务。基于 Xposed / LSPosed 运行时注入与现代 Android 架构设计,提供高拟真、无残留的多维环境模拟能力。
|
||||
|
||||
OpenLoc 旨在为开发者、测试人员以及关注个人数字隐私的用户提供安全、可控且纯净的位置环境模拟服务,主要用于以下场景:
|
||||
---
|
||||
|
||||
- **位置环境模拟**
|
||||
支持在地图上自由选定目标位置或精确检索地理坐标,为应用提供自定义的虚拟定位环境,便于进行基于位置的应用功能开发与场景联调。
|
||||
## 核心实现架构
|
||||
|
||||
- **应用作用域管控**
|
||||
支持全局模式、黑名单模式与白名单模式,用户可灵活指定哪些应用接收模拟位置、哪些应用使用真实网络环境,避免影响日常无关应用的正常使用。
|
||||
### 1. 底层 Hook 与多维定位拦截
|
||||
- **系统层级深度劫持**:通过 Xposed 框架深度挂钩 Android 系统底层 `LocationManagerService`、网络定位提供者及第三方 NLP 接口,接管全球卫星导航、网络基站与 Wi-Fi 扫描结果。
|
||||
- **内存级模拟脱敏**:在内存对象层实时抹除 `isMock` 与 `mIsFromMockProvider` 标志,从源头消除底层定位模拟特征。
|
||||
- **模块包名自隐匿**:针对受控目标应用动态隐藏 OpenLoc 自身的安装包信息,有效防御应用通过 `PackageManager` 扫描安装列表以识别模块存在的行为。
|
||||
|
||||
- **常用地点快捷收藏**
|
||||
提供便捷的地点收藏与管理功能,支持常用测试点位或兴趣位置的自定义命名、快速切换与拖拽排序。
|
||||
### 2. 多维拟真与防检测矩阵
|
||||
- **自然位置微漂移**:采用高斯平滑滤波与布朗运动随机游走模型,动态生成拟真经纬度微小漂移,防止因坐标绝对静止触发服务端风控策略。
|
||||
- **全星座卫星信号仿真**:支持 GPS、北斗(BeiDou)、GLONASS、Galileo 等主流卫星星座的物理载噪比与伪距仿真,动态生成合规的全量 NMEA GSV/GSA 报文流。
|
||||
- **生物手持生理拟真**:向设备传感器层注入微弱的生理微颤信号,模拟手持设备日常轻微晃动,规避步态与姿态静止监测。
|
||||
- **基站小区与 Wi-Fi 防反查**:针对周围蜂窝基站(Cell Tower)与 Wi-Fi 接入点(BSSID)进行脱敏混淆,杜绝目标应用上传网络指纹至云端数据库反查真实物理位置。
|
||||
|
||||
- **多维环境拟真与隐私防护**
|
||||
在提供虚拟坐标的同时,协同拟真设备在日常手持、运动状态下的环境表现,避免单一静态坐标导致的数据异常,有效防止个人真实物理行踪的过度获取与隐私泄露。
|
||||
### 3. 应用作用域精细化管控
|
||||
- **多维度生效策略**:
|
||||
- **全局模式**:整机所有应用统一接收模拟位置。
|
||||
- **黑名单模式**:黑名单内的特定应用保持真实物理定位,其余应用接收模拟位置。
|
||||
- **白名单模式**:仅白名单指定的应用接收模拟位置,其余应用保持真实定位。
|
||||
- **高效应用检索**:内置快速搜索、分类筛选(系统应用/用户应用)以及全选/全不选批处理能力。
|
||||
|
||||
- **纯粹无干扰的交互体验**
|
||||
基于 Material 3 现代设计语言构建,界面简洁直观,无后台冗余常驻,注重工具属性的克制与易用性。
|
||||
### 4. 交互式地图与地点管理
|
||||
- **现代化地图选点**:集成 OpenStreetMap 地图引擎,提供流畅的手势选点、缩放与精准坐标拾取体验。
|
||||
- **多引擎智能检索**:支持高德地图、百度地图、Photon、Nominatim 等多元化位置搜索引擎与经纬度坐标直达。
|
||||
- **常用地点收藏夹**:支持收藏自定义命名地点,提供即时选定、拖拽排序与离线存储管理。
|
||||
|
||||
### 5. 纯净体验与全站国际化
|
||||
- **Jetpack Compose & Material 3**:采用现代声明式 UI 体系构建,深度支持 Material You 壁纸动态取色与多套质感主题色切换。
|
||||
- **全站国际化(i18n)**:UI 界面文字完全解耦,支持简体中文与英文多语言环境,严格禁止硬编码。
|
||||
- **本地纯净运行**:无任何非必要的后台常驻常驻驻留进程,隐私数据完全保留于设备本地。
|
||||
|
||||
---
|
||||
|
||||
## 免责声明
|
||||
|
||||
本软件仅供合法的软件开发调试、学术研究、定位功能测试及个人隐私保护使用,请勿用于任何违反法律法规或破坏第三方服务协议的用途。
|
||||
|
||||
---
|
||||
|
||||
## 开源协议
|
||||
|
||||
本项目基于 **GNU General Public License v3.0 (GPL-3.0)** 协议开源。详细条款请参阅 [LICENSE](LICENSE) 文件。
|
||||
@@ -0,0 +1,70 @@
|
||||
<p align="center">
|
||||
<img src="assets/logo.png" width="128" height="128" alt="OpenLoc Logo" />
|
||||
</p>
|
||||
|
||||
<h1 align="center">OpenLoc</h1>
|
||||
|
||||
<p align="center">
|
||||
A modern location simulation and privacy assistant tailored for the Android platform
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/Platform-Android-3DDC84?style=flat-square&logo=android&logoColor=white" alt="Platform" />
|
||||
<img src="https://img.shields.io/badge/Language-Kotlin-7F52FF?style=flat-square&logo=kotlin&logoColor=white" alt="Language" />
|
||||
<img src="https://img.shields.io/badge/UI-Jetpack%20Compose%20%2F%20Material%203-4285F4?style=flat-square&logo=jetpackcompose&logoColor=white" alt="UI" />
|
||||
<br>
|
||||
<img src="https://img.shields.io/badge/Privacy-Local%20Only-00C853?style=flat-square" alt="Privacy" />
|
||||
<img src="https://img.shields.io/badge/License-GPL--3.0-007AFF?style=flat-square" alt="License" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">简体中文</a> | <b>English</b>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
OpenLoc is designed for developers, QA engineers, and privacy-conscious users who require a secure, controllable, and clean mock location environment. Built on top of runtime hooking via Xposed / LSPosed alongside modern Android architectural components, OpenLoc delivers high-fidelity, residue-free multi-dimensional environmental simulation.
|
||||
|
||||
---
|
||||
|
||||
## Core Architecture & Implementation
|
||||
|
||||
### 1. Low-Level Hooking & Multi-Dimensional Geolocation Interception
|
||||
- **System-Level Deep Hooking**: Deeply hooks into Android's core `LocationManagerService`, network location providers, and third-party NLP frameworks via Xposed to intercept GNSS data, cellular base station scans, and Wi-Fi networks.
|
||||
- **In-Memory Mock Flag Sanitization**: Clears the `isMock` and `mIsFromMockProvider` fields in memory objects in real time, eliminating fundamental mock location signatures at the source.
|
||||
- **Module Package Self-Stealth**: Transparently conceals OpenLoc's own package information from monitored applications, defeating detection mechanisms that scan installed packages via `PackageManager`.
|
||||
|
||||
### 2. Multi-Dimensional Realism & Anti-Detection Matrix
|
||||
- **Natural Location Drift**: Employs Gaussian smoothing and Brownian motion random walk models to dynamically generate lifelike subtle coordinate drifts, preventing risk control alarms triggered by absolute static coordinates.
|
||||
- **Full Constellation GNSS Simulation**: Simulates physical Carrier-to-Noise ratio (C/N0) and pseudoranges across GPS, BeiDou, GLONASS, and Galileo constellations, generating compliant full-stream NMEA GSV/GSA sentences.
|
||||
- **Physiological Micro-Tremor Simulation**: Injects subtle physiological tremors into the device's accelerometer sensors, replicating natural handheld micro-movements to bypass gait and stationary posture detections.
|
||||
- **Cell Tower & Wi-Fi Camouflage**: Sanitizes and obfuscates nearby cellular cell identifiers and Wi-Fi BSSIDs, preventing apps from querying cloud fingerprint databases to trace real physical locations.
|
||||
|
||||
### 3. Granular Application Scope Management
|
||||
- **Versatile Scope Policies**:
|
||||
- **Global Mode**: All applications across the system receive simulated coordinates.
|
||||
- **Blacklist Mode**: Designated blacklisted applications retain real physical positioning, while all other applications receive simulated locations.
|
||||
- **Whitelist Mode**: Only explicitly whitelisted applications receive simulated locations, leaving all other applications untouched.
|
||||
- **Intuitive App Selector**: Equipped with fast search indexing, category filtering (System vs. User apps), and bulk selection capabilities.
|
||||
|
||||
### 4. Interactive Map & Favorites Management
|
||||
- **Modern Map Interaction**: Integrated with OpenStreetMap engine for fluid gestures, smooth zooming, and accurate coordinate selection.
|
||||
- **Multi-Engine Geosearch**: Supports diverse search providers including AMap, Baidu Maps, Photon, and Nominatim, with direct coordinate jump functionality.
|
||||
- **Favorites & Waypoints**: Save and name custom locations with instant switching, drag-to-reorder, and persistent local storage.
|
||||
|
||||
### 5. Clean Experience & Internationalization
|
||||
- **Jetpack Compose & Material 3**: Built with a modern declarative UI framework, supporting Material You dynamic color extraction and customizable palette themes with light/dark modes.
|
||||
- **Strict Internationalization (i18n)**: All UI strings are completely decoupled with zero hardcoded text, providing comprehensive native support for Simplified Chinese and English.
|
||||
- **Pure Local Execution**: Zero background daemon overhead and zero external analytics; all privacy configurations remain strictly on the local device.
|
||||
|
||||
---
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This software is intended solely for legitimate software development, academic research, geolocation testing, and personal privacy protection. Please do not use it for any activity that violates laws, regulations, or third-party service agreements.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the **GNU General Public License v3.0 (GPL-3.0)**. See the [LICENSE](LICENSE) file for details.
|
||||
+14
-10
@@ -18,19 +18,14 @@ android {
|
||||
applicationId = "com.lzxnone.openloc"
|
||||
minSdk = 28
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "1.0.0"
|
||||
versionCode = 10
|
||||
versionName = "1.3.2"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
splits {
|
||||
abi {
|
||||
isEnable = true
|
||||
reset()
|
||||
include("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
|
||||
isUniversalApk = true
|
||||
}
|
||||
base {
|
||||
archivesName.set("OpenLoc-v${defaultConfig.versionName}")
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +41,13 @@ android {
|
||||
storePassword = props.getProperty("storePassword")
|
||||
keyAlias = props.getProperty("keyAlias")
|
||||
keyPassword = props.getProperty("keyPassword")
|
||||
} else {
|
||||
// CI/CD 或未配置密钥时平滑降级,确保构建永远不抛错中断
|
||||
val debugConfig = getByName("debug")
|
||||
storeFile = debugConfig.storeFile
|
||||
storePassword = debugConfig.storePassword
|
||||
keyAlias = debugConfig.keyAlias
|
||||
keyPassword = debugConfig.keyPassword
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +55,8 @@ android {
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
@@ -68,6 +71,7 @@ android {
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
+22
-18
@@ -1,21 +1,25 @@
|
||||
# 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
|
||||
# 仅代码裁剪(Tree Shaking),完全禁用重命名混淆
|
||||
-dontobfuscate
|
||||
-dontoptimize
|
||||
|
||||
# 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 *;
|
||||
#}
|
||||
# 保留调试堆栈信息与注解签名
|
||||
-keepattributes SourceFile,LineNumberTable,InnerClasses,EnclosingMethod,Exceptions,Signature
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
# 保持 Android 基础组件(Activity, Provider 等)
|
||||
-keep public class * extends android.app.Activity
|
||||
-keep public class * extends android.app.Application
|
||||
-keep public class * extends android.app.Service
|
||||
-keep public class * extends android.content.BroadcastReceiver
|
||||
-keep public class * extends android.content.ContentProvider
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
# 保持 Xposed / LSPosed 钩子入口及所有 Hook 类(在目标进程反射加载)
|
||||
-keep class com.lzxnone.openloc.hook.** { *; }
|
||||
|
||||
# 保持数据模型与配置实体
|
||||
-keep class com.lzxnone.openloc.data.model.** { *; }
|
||||
-keep class com.lzxnone.openloc.hook.model.** { *; }
|
||||
-keep class com.lzxnone.openloc.core.provider.** { *; }
|
||||
|
||||
# 保持 osmdroid 地图库必须的反射类与组件
|
||||
-keep class org.osmdroid.** { *; }
|
||||
-dontwarn org.osmdroid.**
|
||||
@@ -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>
|
||||
@@ -30,8 +30,11 @@ class LocationConfigProvider : ContentProvider() {
|
||||
val prefs = ctx.getSharedPreferences("openloc_prefs", Context.MODE_PRIVATE)
|
||||
|
||||
val isEnabled = prefs.getBoolean("mock_service_enabled", false)
|
||||
val lat = prefs.getString("mock_latitude", "39.908722")?.toDoubleOrNull() ?: 39.908722
|
||||
val lng = prefs.getString("mock_longitude", "116.397496")?.toDoubleOrNull() ?: 116.397496
|
||||
val runtime = AppPreferences.getRuntimeMockState()
|
||||
val lat = if (isEnabled) runtime.latitude else (prefs.getString("mock_latitude", "39.908722")?.toDoubleOrNull() ?: 39.908722)
|
||||
val lng = if (isEnabled) runtime.longitude else (prefs.getString("mock_longitude", "116.397496")?.toDoubleOrNull() ?: 116.397496)
|
||||
val speed = if (isEnabled) runtime.speed else 0.0f
|
||||
val bearing = if (isEnabled) runtime.bearing else 0.0f
|
||||
val name = prefs.getString("mock_location_name", "") ?: ""
|
||||
val mode = prefs.getString("app_mock_mode", "GLOBAL") ?: "GLOBAL"
|
||||
val whitelistJson = prefs.getString("whitelist_apps", "[]") ?: "[]"
|
||||
@@ -47,6 +50,10 @@ class LocationConfigProvider : ContentProvider() {
|
||||
putBoolean(ConfigContract.KEY_ENABLED, isEnabled)
|
||||
putDouble(ConfigContract.KEY_LATITUDE, lat)
|
||||
putDouble(ConfigContract.KEY_LONGITUDE, lng)
|
||||
putDouble("altitude", 50.0)
|
||||
putFloat("accuracy", 5.0f)
|
||||
putFloat("bearing", bearing)
|
||||
putFloat("speed", speed)
|
||||
putString(ConfigContract.KEY_LOCATION_NAME, name)
|
||||
putString(ConfigContract.KEY_APP_MOCK_MODE, mode)
|
||||
putString(ConfigContract.KEY_WHITELIST_APPS, whitelistJson)
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.lzxnone.openloc.core.service
|
||||
|
||||
import android.app.AlarmManager
|
||||
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.graphics.BitmapFactory
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.SystemClock
|
||||
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()
|
||||
AppPreferences.init(applicationContext)
|
||||
createNotificationChannel()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (!AppPreferences.isServiceEnabled || !AppPreferences.isNotificationEnabled) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
val notification = buildNotification(this)
|
||||
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
|
||||
}
|
||||
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
if (AppPreferences.isServiceEnabled && AppPreferences.isNotificationEnabled) {
|
||||
try {
|
||||
val restartIntent = Intent(applicationContext, MockLocationForegroundService::class.java)
|
||||
val pendingIntentFlags = PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
|
||||
val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
PendingIntent.getForegroundService(applicationContext, RESTART_REQUEST_CODE, restartIntent, pendingIntentFlags)
|
||||
} else {
|
||||
PendingIntent.getService(applicationContext, RESTART_REQUEST_CODE, restartIntent, pendingIntentFlags)
|
||||
}
|
||||
val alarmManager = getSystemService(Context.ALARM_SERVICE) as? AlarmManager
|
||||
alarmManager?.set(
|
||||
AlarmManager.ELAPSED_REALTIME_WAKEUP,
|
||||
SystemClock.elapsedRealtime() + 1000L,
|
||||
pendingIntent
|
||||
)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
super.onTaskRemoved(rootIntent)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "openloc_keepalive"
|
||||
private const val NOTIFICATION_ID = 10086
|
||||
private const val RESTART_REQUEST_CODE = 10087
|
||||
|
||||
fun buildNotification(context: Context): Notification {
|
||||
val launchIntent = Intent(context, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
}
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
0,
|
||||
launchIntent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
val title = context.getString(R.string.service_keepalive_title)
|
||||
val desc = context.getString(R.string.service_keepalive_desc)
|
||||
val largeIcon = try {
|
||||
BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher_round)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
return NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.apply {
|
||||
if (largeIcon != null) {
|
||||
setLargeIcon(largeIcon)
|
||||
}
|
||||
}
|
||||
.setContentTitle(title)
|
||||
.setContentText(desc)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setSilent(true)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setContentIntent(pendingIntent)
|
||||
.build()
|
||||
}
|
||||
|
||||
fun updateNotification(context: Context) {
|
||||
if (!AppPreferences.isServiceEnabled || !AppPreferences.isNotificationEnabled) return
|
||||
try {
|
||||
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
|
||||
manager.notify(NOTIFICATION_ID, buildNotification(context))
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
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) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.lzxnone.openloc.core.util
|
||||
|
||||
import android.location.Location
|
||||
import android.util.Log
|
||||
import de.robv.android.xposed.XposedBridge
|
||||
|
||||
/**
|
||||
* OpenLoc 全链路高精度诊断跟踪器
|
||||
* 统一向 Android Logcat (Tag: OpenLocTrace) 和 XposedBridge 日志双通道输出
|
||||
*/
|
||||
object TraceLogger {
|
||||
|
||||
const val TAG = "OpenLocTrace"
|
||||
|
||||
fun d(component: String, message: String) {
|
||||
val formatted = "[$component] $message"
|
||||
Log.d(TAG, formatted)
|
||||
try {
|
||||
XposedBridge.log("$TAG: $formatted")
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
fun i(component: String, message: String) {
|
||||
val formatted = "[$component] $message"
|
||||
Log.i(TAG, formatted)
|
||||
try {
|
||||
XposedBridge.log("$TAG: $formatted")
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
fun w(component: String, message: String) {
|
||||
val formatted = "[$component] $message"
|
||||
Log.w(TAG, formatted)
|
||||
try {
|
||||
XposedBridge.log("$TAG: $formatted")
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
fun e(component: String, message: String) {
|
||||
val formatted = "[$component] $message"
|
||||
Log.e(TAG, formatted)
|
||||
try {
|
||||
XposedBridge.log("$TAG: $formatted")
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
fun formatLocation(loc: Location?): String {
|
||||
if (loc == null) return "null"
|
||||
val ageMs = System.currentTimeMillis() - loc.time
|
||||
return "Location[provider=${loc.provider}, lat=${loc.latitude}, lng=${loc.longitude}, acc=${loc.accuracy}m, age=${ageMs}ms]"
|
||||
}
|
||||
}
|
||||
@@ -1,103 +1,162 @@
|
||||
package com.lzxnone.openloc.core.util
|
||||
|
||||
import android.os.Build
|
||||
import com.lzxnone.openloc.BuildConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* 版本更新信息
|
||||
*/
|
||||
data class UpdateInfo(
|
||||
val hasUpdate: Boolean,
|
||||
val latestVersion: String,
|
||||
val currentVersion: String,
|
||||
val releaseTitle: String,
|
||||
val versionCode: Long,
|
||||
val versionName: String,
|
||||
val changelog: String,
|
||||
val releaseUrl: String
|
||||
)
|
||||
val downloadUrl: String,
|
||||
val apkSize: String = ""
|
||||
) {
|
||||
val hasUpdate: Boolean
|
||||
get() = UpdateChecker.isNewerVersion(versionName, BuildConfig.VERSION_NAME)
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub Releases 版本更新检查器
|
||||
* Gitea Releases 版本更新检查器
|
||||
*/
|
||||
object UpdateChecker {
|
||||
private const val GITHUB_API_URL = "https://api.github.com/repos/lzxnone/openloc/releases/latest"
|
||||
private const val UPDATE_URL = "https://gitea.lzxnone.cloud/api/v1/repos/lzxnone/OpenLoc/releases/latest"
|
||||
|
||||
/**
|
||||
* 检查 GitHub 是否有新版本
|
||||
* 检查是否有新版本
|
||||
*/
|
||||
suspend fun checkUpdate(currentVersion: String = "v1.0.0"): Result<UpdateInfo> = withContext(Dispatchers.IO) {
|
||||
suspend fun checkUpdate(): Result<UpdateInfo> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val url = URL(GITHUB_API_URL)
|
||||
val conn = (url.openConnection() as HttpURLConnection).apply {
|
||||
requestMethod = "GET"
|
||||
val url = URL(UPDATE_URL)
|
||||
val connection = (url.openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 8000
|
||||
readTimeout = 8000
|
||||
setRequestProperty("Accept", "application/vnd.github.v3+json")
|
||||
setRequestProperty("User-Agent", "OpenLoc-App")
|
||||
requestMethod = "GET"
|
||||
setRequestProperty("Accept", "application/json")
|
||||
setRequestProperty("User-Agent", "OpenLoc-Android")
|
||||
}
|
||||
|
||||
val code = conn.responseCode
|
||||
if (code == 200) {
|
||||
val responseText = conn.inputStream.bufferedReader().use { it.readText() }
|
||||
val json = JSONObject(responseText)
|
||||
val tagName = json.optString("tag_name", "").trim()
|
||||
val title = json.optString("name", tagName).trim()
|
||||
val body = json.optString("body", "").trim()
|
||||
val htmlUrl = json.optString("html_url", "https://github.com/lzxnone/openloc/releases").trim()
|
||||
val responseCode = connection.responseCode
|
||||
if (responseCode == HttpURLConnection.HTTP_OK) {
|
||||
val reader = BufferedReader(InputStreamReader(connection.inputStream, Charsets.UTF_8))
|
||||
val response = reader.use { it.readText() }
|
||||
connection.disconnect()
|
||||
|
||||
val hasUpdate = isNewerVersion(tagName, currentVersion)
|
||||
Result.success(
|
||||
UpdateInfo(
|
||||
hasUpdate = hasUpdate,
|
||||
latestVersion = tagName.ifEmpty { currentVersion },
|
||||
currentVersion = currentVersion,
|
||||
releaseTitle = title.ifEmpty { tagName },
|
||||
changelog = body,
|
||||
releaseUrl = htmlUrl
|
||||
)
|
||||
)
|
||||
} else if (code == 404) {
|
||||
// 仓库尚未发布任何 Release 时 GitHub 会返回 404
|
||||
Result.success(
|
||||
UpdateInfo(
|
||||
hasUpdate = false,
|
||||
latestVersion = currentVersion,
|
||||
currentVersion = currentVersion,
|
||||
releaseTitle = "",
|
||||
changelog = "",
|
||||
releaseUrl = "https://github.com/lzxnone/openloc/releases"
|
||||
)
|
||||
)
|
||||
Result.success(parseReleaseJson(response))
|
||||
} else {
|
||||
Result.failure(Exception("HTTP $code"))
|
||||
connection.disconnect()
|
||||
Result.failure(Exception("HTTP error $responseCode"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较版本号:remote > current 则返回 true
|
||||
*/
|
||||
fun isNewerVersion(remoteTag: String, currentVer: String): Boolean {
|
||||
if (remoteTag.isBlank()) return false
|
||||
val cleanRemote = remoteTag.trim().removePrefix("v").removePrefix("V")
|
||||
val cleanCurrent = currentVer.trim().removePrefix("v").removePrefix("V")
|
||||
internal fun parseReleaseJson(
|
||||
response: String,
|
||||
supportedAbis: Array<String> = Build.SUPPORTED_ABIS ?: emptyArray()
|
||||
): UpdateInfo {
|
||||
val json = JSONObject(response)
|
||||
val rawTag = json.optString("tag_name", "").trim()
|
||||
val versionName = rawTag.removePrefix("v").removePrefix("V")
|
||||
val versionCode = parseVersionCode(versionName)
|
||||
val changelog = json.optString("body", "").ifBlank {
|
||||
json.optString("name", "")
|
||||
}
|
||||
|
||||
val remoteParts = cleanRemote.split(".").mapNotNull { it.toIntOrNull() }
|
||||
val currentParts = cleanCurrent.split(".").mapNotNull { it.toIntOrNull() }
|
||||
val (downloadUrl, apkSize) = selectApkAsset(
|
||||
assets = json.optJSONArray("assets"),
|
||||
supportedAbis = supportedAbis,
|
||||
fallbackUrl = json.optString("html_url", "")
|
||||
)
|
||||
|
||||
return UpdateInfo(
|
||||
versionCode = versionCode,
|
||||
versionName = versionName,
|
||||
changelog = changelog,
|
||||
downloadUrl = downloadUrl,
|
||||
apkSize = apkSize
|
||||
)
|
||||
}
|
||||
|
||||
private fun selectApkAsset(
|
||||
assets: JSONArray?,
|
||||
supportedAbis: Array<String>,
|
||||
fallbackUrl: String
|
||||
): Pair<String, String> {
|
||||
if (assets == null || assets.length() == 0) {
|
||||
return fallbackUrl to ""
|
||||
}
|
||||
|
||||
val apkAssets = buildList {
|
||||
for (i in 0 until assets.length()) {
|
||||
val asset = assets.optJSONObject(i) ?: continue
|
||||
val name = asset.optString("name", "")
|
||||
val downloadUrl = asset.optString("browser_download_url", "")
|
||||
val size = asset.optLong("size", 0L)
|
||||
if (name.endsWith(".apk", ignoreCase = true) && downloadUrl.isNotBlank()) {
|
||||
add(Triple(name, downloadUrl, size))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (apkAssets.isEmpty()) {
|
||||
return fallbackUrl to ""
|
||||
}
|
||||
|
||||
val matched = supportedAbis.firstNotNullOfOrNull { abi ->
|
||||
apkAssets.firstOrNull { (name, _, _) ->
|
||||
name.contains(abi, ignoreCase = true)
|
||||
}
|
||||
} ?: apkAssets.firstOrNull { (name, _, _) ->
|
||||
name.contains("universal", ignoreCase = true)
|
||||
} ?: apkAssets.first()
|
||||
|
||||
val sizeText = if (matched.third > 0L) {
|
||||
String.format(Locale.US, "%.2f MB", matched.third / (1024.0 * 1024.0))
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return matched.second to sizeText
|
||||
}
|
||||
|
||||
internal fun isNewerVersion(remoteVersion: String, currentVersion: String): Boolean {
|
||||
val remoteParts = parseVersionParts(remoteVersion)
|
||||
val currentParts = parseVersionParts(currentVersion)
|
||||
if (remoteParts.isEmpty()) return false
|
||||
|
||||
val maxLen = maxOf(remoteParts.size, currentParts.size)
|
||||
for (i in 0 until maxLen) {
|
||||
val r = remoteParts.getOrElse(i) { 0 }
|
||||
val c = currentParts.getOrElse(i) { 0 }
|
||||
if (r > c) return true
|
||||
if (r < c) return false
|
||||
if (r != c) return r > c
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
internal fun parseVersionCode(versionName: String): Long {
|
||||
val parts = parseVersionParts(versionName)
|
||||
if (parts.isEmpty()) return 0L
|
||||
val major = parts.getOrElse(0) { 0 }
|
||||
val minor = parts.getOrElse(1) { 0 }
|
||||
val patch = parts.getOrElse(2) { 0 }
|
||||
return major * 10000L + minor * 100L + patch
|
||||
}
|
||||
|
||||
private fun parseVersionParts(version: String): List<Int> {
|
||||
val cleaned = version.trim().removePrefix("v").removePrefix("V")
|
||||
if (cleaned.isBlank()) return emptyList()
|
||||
return cleaned.split(".")
|
||||
.map { segment -> segment.takeWhile { it.isDigit() }.toIntOrNull() ?: 0 }
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
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
|
||||
@@ -11,7 +17,12 @@ import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import com.lzxnone.openloc.R
|
||||
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),
|
||||
@@ -84,8 +95,11 @@ object AppPreferences {
|
||||
private const val KEY_DYNAMIC_COLOR = "dynamic_color"
|
||||
private const val KEY_LANGUAGE = "language"
|
||||
private const val KEY_SERVICE_ENABLED = "mock_service_enabled"
|
||||
private const val KEY_NOTIFICATION_ENABLED = "enable_notification"
|
||||
|
||||
private lateinit var prefs: SharedPreferences
|
||||
@Volatile
|
||||
private var appContext: Context? = null
|
||||
|
||||
var themeMode by mutableStateOf(ThemeMode.SYSTEM)
|
||||
private set
|
||||
@@ -112,9 +126,12 @@ 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"
|
||||
private const val KEY_SUPPRESSED_UPDATE_VERSION = "suppressed_update_version"
|
||||
|
||||
var appLanguage by mutableStateOf(AppLanguage.SYSTEM)
|
||||
private set
|
||||
@@ -122,6 +139,9 @@ object AppPreferences {
|
||||
var isAutoCheckUpdateEnabled by mutableStateOf(true)
|
||||
private set
|
||||
|
||||
var suppressedUpdateVersionCode by mutableLongStateOf(0L)
|
||||
private set
|
||||
|
||||
|
||||
var searchProvider by mutableStateOf(SearchProvider.AMAP)
|
||||
private set
|
||||
@@ -147,6 +167,17 @@ object AppPreferences {
|
||||
var isSensorSimulationEnabled by mutableStateOf(true)
|
||||
private set
|
||||
|
||||
var isRunningModeEnabled by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
private val processToken = android.os.Binder()
|
||||
|
||||
var runningSpeedMps by androidx.compose.runtime.mutableFloatStateOf(3.0f)
|
||||
private set
|
||||
|
||||
var isNotificationEnabled by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
var isStealthEnabled by mutableStateOf(true)
|
||||
private set
|
||||
|
||||
@@ -168,6 +199,96 @@ 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
|
||||
|
||||
internal data class RuntimeMockState(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val speed: Float,
|
||||
val bearing: Float
|
||||
)
|
||||
|
||||
internal fun getRuntimeMockState(): RuntimeMockState {
|
||||
val pushLat = if (hasActivePoint) activeLat else mockLatitude
|
||||
val pushLng = if (hasActivePoint) activeLng else mockLongitude
|
||||
return RuntimeMockState(pushLat, pushLng, activeSpeed, activeBearing)
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -181,6 +302,7 @@ object AppPreferences {
|
||||
private set
|
||||
|
||||
fun init(context: Context) {
|
||||
appContext = context.applicationContext
|
||||
prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
|
||||
|
||||
val modeOrdinal = prefs.getInt(KEY_THEME_MODE, ThemeMode.SYSTEM.ordinal)
|
||||
@@ -224,13 +346,66 @@ 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, false)
|
||||
runningSpeedMps = prefs.getFloat(KEY_RUNNING_SPEED, 3.0f).coerceIn(1.0f, 8.0f)
|
||||
isNotificationEnabled = prefs.getBoolean(KEY_NOTIFICATION_ENABLED, false)
|
||||
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) {
|
||||
startTickerIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fun syncConfigToSystem(quiet: Boolean = false) {
|
||||
try {
|
||||
val ctx = appContext ?: return
|
||||
val lm = ctx.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return
|
||||
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, 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)
|
||||
putBoolean(GlobalMockMemory.EXTRA_NOTIFICATION_ENABLED, isNotificationEnabled)
|
||||
putBoolean(GlobalMockMemory.EXTRA_RUNNING_MODE_ENABLED, isRunningModeEnabled)
|
||||
putBoolean(GlobalMockMemory.EXTRA_JITTER_ENABLED, isJitterEnabled)
|
||||
putBinder("process_token", processToken)
|
||||
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. 隐式广播双重保险(前台高优先级投递,减少后台延迟)
|
||||
val intent = Intent("com.lzxnone.openloc.ACTION_SYNC_CONFIG").apply {
|
||||
addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
|
||||
putExtras(bundle)
|
||||
}
|
||||
ctx.sendBroadcast(intent)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
fun updateMockLocation(latitude: Double, longitude: Double, name: String = "", isUserManual: Boolean = true) {
|
||||
TraceLogger.i("AppPreferences", "updateMockLocation called: ($latitude, $longitude), name=$name, isUserManual=$isUserManual")
|
||||
mockLatitude = latitude
|
||||
mockLongitude = longitude
|
||||
if (name.isNotEmpty()) {
|
||||
@@ -245,6 +420,30 @@ object AppPreferences {
|
||||
.putString(KEY_MOCK_LONGITUDE, longitude.toString())
|
||||
.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) {
|
||||
@@ -271,6 +470,44 @@ 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()
|
||||
startTickerIfNeeded()
|
||||
} else {
|
||||
stopTicker()
|
||||
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 updateNotificationEnabled(enabled: Boolean) {
|
||||
isNotificationEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_NOTIFICATION_ENABLED, enabled).apply()
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun addSearchHistory(item: SearchResult) {
|
||||
@@ -425,11 +662,13 @@ object AppPreferences {
|
||||
fun updateAppMockMode(mode: AppMockMode) {
|
||||
appMockMode = mode
|
||||
prefs.edit().putString(KEY_APP_MOCK_MODE, mode.name).apply()
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun updateWhitelistApps(packages: Set<String>) {
|
||||
whitelistApps = packages
|
||||
savePackageSet(KEY_WHITELIST_APPS, packages)
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun toggleWhitelistApp(packageName: String) {
|
||||
@@ -444,6 +683,7 @@ object AppPreferences {
|
||||
fun updateBlacklistApps(packages: Set<String>) {
|
||||
blacklistApps = packages
|
||||
savePackageSet(KEY_BLACKLIST_APPS, packages)
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun toggleBlacklistApp(packageName: String) {
|
||||
@@ -479,36 +719,47 @@ object AppPreferences {
|
||||
fun updateJitterEnabled(enabled: Boolean) {
|
||||
isJitterEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_ENABLE_JITTER, enabled).apply()
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun updateGnssSimulationEnabled(enabled: Boolean) {
|
||||
isGnssSimulationEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_ENABLE_GNSS_SIMULATION, enabled).apply()
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun updateNetworkCamouflageEnabled(enabled: Boolean) {
|
||||
isNetworkCamouflageEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_ENABLE_NETWORK_CAMOUFLAGE, enabled).apply()
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun updateSensorSimulationEnabled(enabled: Boolean) {
|
||||
isSensorSimulationEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_ENABLE_SENSOR_SIMULATION, enabled).apply()
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun updateStealthEnabled(enabled: Boolean) {
|
||||
isStealthEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_ENABLE_STEALTH, enabled).apply()
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun updateDevCamouflageEnabled(enabled: Boolean) {
|
||||
isDevCamouflageEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_ENABLE_DEV_CAMOUFLAGE, enabled).apply()
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun updateAutoCheckUpdateEnabled(enabled: Boolean) {
|
||||
isAutoCheckUpdateEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_AUTO_CHECK_UPDATE, enabled).apply()
|
||||
}
|
||||
|
||||
fun updateSuppressedVersionCode(code: Long) {
|
||||
suppressedUpdateVersionCode = code
|
||||
prefs.edit().putLong(KEY_SUPPRESSED_UPDATE_VERSION, code).apply()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,16 @@ package com.lzxnone.openloc.hook
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import com.lzxnone.openloc.hook.client.ThirdPartyNlpHook
|
||||
import com.lzxnone.openloc.hook.interceptor.AntiDetectionHook
|
||||
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
|
||||
import de.robv.android.xposed.XC_MethodHook
|
||||
import de.robv.android.xposed.XC_MethodReplacement
|
||||
@@ -16,7 +20,7 @@ import de.robv.android.xposed.XposedHelpers
|
||||
import de.robv.android.xposed.callbacks.XC_LoadPackage
|
||||
|
||||
/**
|
||||
* Xposed / LSPosed 统一 Hook 分发主入口
|
||||
* Xposed / LSPosed 统一路由入口(全新四维工业级架构)
|
||||
*/
|
||||
class HookEntry : IXposedHookLoadPackage {
|
||||
|
||||
@@ -24,31 +28,41 @@ class HookEntry : IXposedHookLoadPackage {
|
||||
private var appContext: Context? = null
|
||||
|
||||
override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam) {
|
||||
// 1. 系统级全局拦截:如果是 Android 系统框架 (system_server)
|
||||
// 只要在 LSPosed 中勾选了【Android 系统 (android)】,整机所有应用全部享受全局定位拦截!
|
||||
if (lpparam.packageName == "android") {
|
||||
val pkg = lpparam.packageName
|
||||
|
||||
// 1. 系统底层服务 (system_server / UID 1000)
|
||||
if (pkg == "android" || android.os.Process.myUid() == 1000) {
|
||||
SystemServerHook.hook(lpparam.classLoader)
|
||||
return
|
||||
}
|
||||
|
||||
// 过滤系统 UI 进程
|
||||
if (lpparam.packageName == "com.android.systemui") {
|
||||
// 2. 电话系统与基站塔管理守护进程
|
||||
if (pkg == "com.android.phone") {
|
||||
TelephonyRegistryHook.hook(lpparam.classLoader)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 如果加载的是本应用自身,Hook 激活判定桩使其恒返回 true
|
||||
if (lpparam.packageName == MODULE_PACKAGE_NAME) {
|
||||
// 4. 蓝牙服务守护进程(拦截底层 BLE 室内信标微定位,GhostMapX 架构)
|
||||
if (pkg == "com.android.bluetooth") {
|
||||
BleHook.hookBluetoothProcess(lpparam.classLoader)
|
||||
return
|
||||
}
|
||||
|
||||
// 过滤系统 UI 及管理工具环境
|
||||
if (isManagementPackage(pkg)) {
|
||||
return
|
||||
}
|
||||
|
||||
// 4. 模块自身激活判定
|
||||
if (pkg == MODULE_PACKAGE_NAME) {
|
||||
hookSelfActiveStatus(lpparam.classLoader)
|
||||
return
|
||||
}
|
||||
|
||||
// 3. 注入目标应用进程(客户端双重兜底):挂载 Context 并启动深度拦截链路(WiFi/基站/NMEA)
|
||||
// 5. 目标应用进程(QQ、微信、百度地图、打卡软件等)全链路拦截
|
||||
initTargetHooks(lpparam)
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook 本身应用的 HookStatus.isModuleActive(),令其返回 true
|
||||
*/
|
||||
private fun hookSelfActiveStatus(classLoader: ClassLoader) {
|
||||
try {
|
||||
XposedHelpers.findAndHookMethod(
|
||||
@@ -67,35 +81,42 @@ class HookEntry : IXposedHookLoadPackage {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 目标应用进程初始化与全链路 Hook 挂载
|
||||
*/
|
||||
private fun initTargetHooks(lpparam: XC_LoadPackage.LoadPackageParam) {
|
||||
try {
|
||||
val contextProvider = { appContext }
|
||||
|
||||
// 监听 Application 启动以安全捕获应用级 Context
|
||||
val pkg = lpparam.packageName
|
||||
|
||||
XposedHelpers.findAndHookMethod(
|
||||
Application::class.java,
|
||||
"attach",
|
||||
Context::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (appContext == null) {
|
||||
appContext = param.args[0] as? Context
|
||||
val ctx = param.args[0] as? Context
|
||||
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)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// 挂载定位与防检测核心拦截线
|
||||
LocationHook.hook(lpparam.classLoader, contextProvider)
|
||||
NetworkLocationHook.hook(lpparam.classLoader, contextProvider)
|
||||
GnssHook.hook(lpparam.classLoader, contextProvider)
|
||||
SensorHook.hook(lpparam.classLoader, contextProvider)
|
||||
// 全新多层防穿透管道(显式传递绝对已知的应用包名,第 0 毫秒即就绪)
|
||||
LocationHook.hook(lpparam.classLoader, pkg, contextProvider)
|
||||
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)
|
||||
|
||||
XposedBridge.log("[OpenLoc] Injected target hooks for: ${lpparam.packageName}")
|
||||
XposedBridge.log("[OpenLoc] Fully armed target hooks for: ${lpparam.packageName}")
|
||||
} catch (t: Throwable) {
|
||||
XposedBridge.log("[OpenLoc] Error initializing target hooks for ${lpparam.packageName}: ${t.message}")
|
||||
}
|
||||
@@ -103,5 +124,27 @@ class HookEntry : IXposedHookLoadPackage {
|
||||
|
||||
companion object {
|
||||
const val MODULE_PACKAGE_NAME = "com.lzxnone.openloc"
|
||||
|
||||
private val MANAGEMENT_PACKAGES = setOf(
|
||||
"com.android.systemui",
|
||||
"com.android.settings",
|
||||
"com.topjohnwu.magisk",
|
||||
"io.github.vvb2060.magisk",
|
||||
"me.weishu.kernelsu",
|
||||
"com.android.packageinstaller",
|
||||
"com.google.android.packageinstaller",
|
||||
"com.miui.packageinstaller",
|
||||
// 系统底层网络定位与硬件驱动服务(提供物理定位数据,绝对不 Hook)
|
||||
"com.xiaomi.metoknlp",
|
||||
"com.xiaomi.location.fused",
|
||||
"com.qualcomm.location",
|
||||
"com.qualcomm.qti.location",
|
||||
"com.android.location.fused",
|
||||
"com.google.android.location"
|
||||
)
|
||||
|
||||
fun isManagementPackage(packageName: String): Boolean {
|
||||
return packageName in MANAGEMENT_PACKAGES || packageName.startsWith("org.lsposed.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,749 @@
|
||||
package com.lzxnone.openloc.hook.client
|
||||
|
||||
import android.content.Context
|
||||
import android.location.Location
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import com.lzxnone.openloc.core.util.CoordinateConverter
|
||||
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.lang.reflect.InvocationHandler
|
||||
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 深度防御拦截器
|
||||
* 核心覆盖:
|
||||
* 1. 腾讯定位 SDK (com.tencent.map.geolocation.*):全面拦截 TencentLocationManager、TencentLocationListener 与动态代理 TencentLocation;
|
||||
* 2. QQ 专有 LBS 接口 (com.tencent.mobileqq.soso.location.*):动态防御 SosoLocation 结构;
|
||||
* 3. 百度定位 SDK (com.baidu.location.*):深度挂钩 BDLocation 核心属性与 LocationClient 回调;
|
||||
* 4. 高德定位 SDK (com.amap.api.location.* / NetworkLocationManager):全链路防护 AMapLocation;
|
||||
* 严格遵循 GhostMapX 规范:绝不抛出异常破坏状态机,返回真实结构成功响应。
|
||||
*/
|
||||
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
|
||||
}
|
||||
|
||||
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) {}
|
||||
}
|
||||
}
|
||||
|
||||
// ====================================================================================
|
||||
// 1. 腾讯定位 SDK (TencentLocationManager / TencentLocationListener / SosoInterface)
|
||||
// ====================================================================================
|
||||
|
||||
private fun hookTencentLocationSDK(classLoader: ClassLoader, packageName: String) {
|
||||
// (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(managerName, classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: continue
|
||||
|
||||
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", "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, prefix)
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"removeUpdates" -> {
|
||||
try {
|
||||
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
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getLastKnownLocation" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
val result = param.result
|
||||
if (result != null) {
|
||||
hookTencentLocationImplClass(result.javaClass, packageName)
|
||||
}
|
||||
val mockLoc = createMockTencentLocation(classLoader, prefix)
|
||||
if (mockLoc != null) {
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] $managerName.getLastKnownLocation -> SPOOFED")
|
||||
param.result = mockLoc
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (2) 兼容旧版腾讯 NLP:com.tencent.geolocation.nlp.TencentNLPManager
|
||||
val oldNlpClass = try {
|
||||
XposedHelpers.findClass("com.tencent.geolocation.nlp.TencentNLPManager", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
if (oldNlpClass != null) {
|
||||
for (method in oldNlpClass.declaredMethods) {
|
||||
if (method.returnType == Location::class.java) {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
val mockLoc = GlobalMockMemory.createLocation("network")
|
||||
param.result = mockLoc
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] TencentNLP.${method.name} -> REPLACED")
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (3) QQ 内部专有 SosoLocation 结构拦截
|
||||
val sosoLocationClasses = listOf(
|
||||
"com.tencent.mobileqq.soso.location.data.SosoLocation",
|
||||
"com.tencent.mobileqq.app.soso.SosoInterface\$SosoLocation"
|
||||
)
|
||||
for (className in sosoLocationClasses) {
|
||||
val sosoClass = try {
|
||||
XposedHelpers.findClass(className, classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: continue
|
||||
|
||||
TraceLogger.i("ThirdPartyNLP", "[$packageName] Detected MobileQQ $className, arming SosoLocation hooks...")
|
||||
for (method in sosoClass.declaredMethods) {
|
||||
when (method.name) {
|
||||
"getLatitude", "getLat02", "getLat84" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.latitude
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getLongitude", "getLon02", "getLon84" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.longitude
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getAltitude" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.altitude
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getAccuracy" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.accuracy
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getSpeed" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.speed
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getAddress", "getName" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
val locName = GlobalMockMemory.locationName
|
||||
if (locName.isNotEmpty()) {
|
||||
param.result = locName
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 包装 TencentLocationListener,注入动态代理
|
||||
*/
|
||||
private fun wrapTencentListenerArgs(
|
||||
args: Array<Any?>,
|
||||
classLoader: ClassLoader,
|
||||
packageName: String,
|
||||
prefix: String
|
||||
) {
|
||||
val listenerInterface = try {
|
||||
XposedHelpers.findClass("$prefix.TencentLocationListener", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
return
|
||||
}
|
||||
|
||||
for (i in args.indices) {
|
||||
val arg = args[i] ?: continue
|
||||
if (listenerInterface.isAssignableFrom(arg.javaClass)) {
|
||||
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, prefix)
|
||||
)
|
||||
}
|
||||
args[i] = 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 }
|
||||
"getDirection" -> hookGetter(method, packageName) { GlobalMockMemory.bearing.toDouble() }
|
||||
"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 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 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) {
|
||||
args[1] = 0 // TencentLocation.ERROR_OK
|
||||
}
|
||||
if (args.size > 2) {
|
||||
args[2] = "OK"
|
||||
}
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] $prefix.TencentLocationListener.onLocationChanged -> REPLACED with Mock Location (${GlobalMockMemory.latitude}, ${GlobalMockMemory.longitude})")
|
||||
}
|
||||
}
|
||||
}
|
||||
return method.invoke(originalListener, *(args ?: emptyArray()))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态反射构建标准 TencentLocation 接口代理实例
|
||||
*/
|
||||
private fun createMockTencentLocation(
|
||||
classLoader: ClassLoader,
|
||||
prefix: String = "com.tencent.map.geolocation"
|
||||
): Any? {
|
||||
val locationInterface = try {
|
||||
XposedHelpers.findClass("$prefix.TencentLocation", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
return null
|
||||
}
|
||||
|
||||
val lat = GlobalMockMemory.latitude
|
||||
val lng = GlobalMockMemory.longitude
|
||||
val alt = GlobalMockMemory.altitude
|
||||
val accuracy = GlobalMockMemory.accuracy
|
||||
val speed = GlobalMockMemory.speed
|
||||
val bearing = GlobalMockMemory.bearing
|
||||
val time = System.currentTimeMillis()
|
||||
val elapsed = SystemClock.elapsedRealtime()
|
||||
val locName = GlobalMockMemory.locationName.ifEmpty { "我的位置" }
|
||||
|
||||
return Proxy.newProxyInstance(
|
||||
classLoader,
|
||||
arrayOf(locationInterface)
|
||||
) { _, method, args ->
|
||||
when (method.name) {
|
||||
"getLatitude" -> lat
|
||||
"getLongitude" -> lng
|
||||
"getAltitude" -> alt
|
||||
"getAccuracy" -> accuracy
|
||||
"getSpeed" -> speed
|
||||
"getBearing" -> bearing
|
||||
"getTime" -> time
|
||||
"getElapsedRealtime" -> elapsed
|
||||
"getProvider" -> "gps"
|
||||
"getAddress" -> locName
|
||||
"getName" -> locName
|
||||
"getNation" -> "中国"
|
||||
"getProvince" -> ""
|
||||
"getCity" -> ""
|
||||
"getDistrict" -> ""
|
||||
"getTown" -> ""
|
||||
"getVillage" -> ""
|
||||
"getStreet" -> ""
|
||||
"getStreetNo" -> ""
|
||||
"getCityCode" -> ""
|
||||
"getCityPhoneCode" -> ""
|
||||
"getAreaStat" -> 0
|
||||
"getCoordinateType" -> 1 // 1: GCJ-02
|
||||
"isMockGps" -> 0 // 核心伪装:假装是硬件 GPS,非 Mock
|
||||
"getIndoorBuildingId" -> null
|
||||
"getIndoorBuildingFloor" -> null
|
||||
"getIndoorLocationType" -> 0
|
||||
"getDirection" -> bearing.toDouble()
|
||||
"getExtra" -> Bundle()
|
||||
"getSourceProvider" -> 0
|
||||
"getVerifyKey" -> ""
|
||||
"toString" -> "TencentLocation{lat=$lat,lng=$lng,name=$locName}"
|
||||
"hashCode" -> lat.hashCode() xor lng.hashCode()
|
||||
"equals" -> args?.getOrNull(0) === this
|
||||
else -> {
|
||||
when (method.returnType) {
|
||||
java.lang.Boolean.TYPE -> false
|
||||
java.lang.Integer.TYPE -> 0
|
||||
java.lang.Long.TYPE -> 0L
|
||||
java.lang.Double.TYPE -> 0.0
|
||||
java.lang.Float.TYPE -> 0.0f
|
||||
java.lang.String::class.java -> ""
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ====================================================================================
|
||||
// 2. 百度定位核心 (com.baidu.location.BDLocation / LocationClient)
|
||||
// ====================================================================================
|
||||
|
||||
private fun hookBaiduLocationSDK(classLoader: ClassLoader, packageName: String) {
|
||||
// (1) 挂钩 BDLocation 全系列 Getter(全场景覆盖)
|
||||
val bdLocationClass = try {
|
||||
XposedHelpers.findClass("com.baidu.location.BDLocation", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
if (bdLocationClass != null) {
|
||||
TraceLogger.i("ThirdPartyNLP", "[$packageName] Detected BDLocation, arming Baidu hooks...")
|
||||
val getCoorTypeMethod = try {
|
||||
bdLocationClass.getMethod("getCoorType")
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
fun resolveBaiduCoords(instance: Any?): DoubleArray? {
|
||||
val coorType = try {
|
||||
(getCoorTypeMethod?.invoke(instance) as? String)?.lowercase()
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
return when {
|
||||
coorType == "bd09mc" || (coorType != null && coorType.contains("mc")) -> null
|
||||
coorType == "wgs84" -> doubleArrayOf(GlobalMockMemory.latitude, GlobalMockMemory.longitude)
|
||||
coorType == "gcj02" -> CoordinateConverter.wgs84ToGcj02(GlobalMockMemory.latitude, GlobalMockMemory.longitude)
|
||||
else -> CoordinateConverter.wgs84ToBd09(GlobalMockMemory.latitude, GlobalMockMemory.longitude)
|
||||
}
|
||||
}
|
||||
|
||||
var lastBdLogTime = 0L
|
||||
for (method in bdLocationClass.declaredMethods) {
|
||||
when (method.name) {
|
||||
"getLatitude" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
val orig = param.result as? Double ?: return
|
||||
if (orig == Double.MIN_VALUE || orig == 0.0 || kotlin.math.abs(orig) > 90.0) return
|
||||
val coords = resolveBaiduCoords(param.thisObject) ?: return
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - lastBdLogTime > 2000L) {
|
||||
lastBdLogTime = now
|
||||
val coorType = try { getCoorTypeMethod?.invoke(param.thisObject) as? String } catch (_: Throwable) { null }
|
||||
TraceLogger.d("ThirdPartyNLP", "[$packageName] BDLocation.getLatitude orig=$orig, coorType=$coorType -> ${coords[0]}")
|
||||
}
|
||||
param.result = coords[0]
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getLongitude" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
val orig = param.result as? Double ?: return
|
||||
if (orig == Double.MIN_VALUE || orig == 0.0 || kotlin.math.abs(orig) > 180.0) return
|
||||
val coords = resolveBaiduCoords(param.thisObject) ?: return
|
||||
param.result = coords[1]
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getAltitude" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.altitude
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getRadius" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.accuracy
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getSpeed" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.speed
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getDirection" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.bearing
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getLocType" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
val orig = param.result as? Int
|
||||
if (orig == 161 || orig == 66 || orig == 65 || orig == 68) {
|
||||
param.result = 61 // 将网络/离线成功态统一伪装为 GPS 定位成功
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getAddrStr", "getLocationDescribe" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
val locName = GlobalMockMemory.locationName
|
||||
if (locName.isNotEmpty()) {
|
||||
param.result = locName
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (2) 挂钩 LocationClient 返回 Location 的方法
|
||||
val clientClass = try {
|
||||
XposedHelpers.findClass("com.baidu.location.LocationClient", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
if (clientClass != null) {
|
||||
for (method in clientClass.declaredMethods) {
|
||||
if (method.returnType == Location::class.java) {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
val mockLoc = GlobalMockMemory.createLocation("gps")
|
||||
param.result = mockLoc
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] Baidu LocationClient.${method.name} -> REPLACED")
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ====================================================================================
|
||||
// 3. 高德定位核心 (com.amap.api.location.AMapLocation / NetworkLocationManager)
|
||||
// ====================================================================================
|
||||
|
||||
private fun hookAmapLocationSDK(classLoader: ClassLoader, packageName: String) {
|
||||
// (1) 挂钩 AMapLocation 核心 Getter
|
||||
val amapLocClass = try {
|
||||
XposedHelpers.findClass("com.amap.api.location.AMapLocation", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
if (amapLocClass != null) {
|
||||
TraceLogger.i("ThirdPartyNLP", "[$packageName] Detected AMapLocation, arming Gaode hooks...")
|
||||
|
||||
for (method in amapLocClass.declaredMethods) {
|
||||
when (method.name) {
|
||||
"getLatitude" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.latitude
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getLongitude" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.longitude
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getAltitude" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.altitude
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getAccuracy" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.accuracy
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getSpeed" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.speed
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getBearing" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = GlobalMockMemory.bearing
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getErrorCode" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
param.result = 0 // 0: 定位成功
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getAddress", "getDescription", "getPoiName" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
val locName = GlobalMockMemory.locationName
|
||||
if (locName.isNotEmpty()) {
|
||||
param.result = locName
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (2) 挂钩 NetworkLocationManager 底层
|
||||
val nlpClass = try {
|
||||
XposedHelpers.findClass("com.amap.android.location.NetworkLocationManager", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
if (nlpClass != null) {
|
||||
for (method in nlpClass.declaredMethods) {
|
||||
if (method.returnType == Location::class.java) {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
val mockLoc = GlobalMockMemory.createLocation("network")
|
||||
param.result = mockLoc
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] AmapNLP.${method.name} -> REPLACED")
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.lzxnone.openloc.hook.interceptor
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.content.pm.PackageInfo
|
||||
@@ -11,114 +10,125 @@ import de.robv.android.xposed.XposedBridge
|
||||
import de.robv.android.xposed.XposedHelpers
|
||||
|
||||
/**
|
||||
* 防检测与隐匿拦截器
|
||||
* 1. 堆栈清洗:过滤 Xposed / LSPosed / OpenLoc 相关调用栈帧
|
||||
* 2. 模块包名自隐匿:隐藏 com.lzxnone.openloc,防止被目标应用通过 PackageManager 探测
|
||||
* 3. 开发者选项与模拟位置状态伪装:伪装开发者模式、USB调试、模拟位置为未开启
|
||||
* 模块自隐匿拦截器(安全级别:高,零系统递归风险)
|
||||
* 仅在目标应用进程内过滤 PackageManager 针对 com.lzxnone.openloc 的包名扫描
|
||||
* 彻底移除对 Throwable/Thread 堆栈以及 Settings.Global/Secure 等易引发死锁的系统基础类的 Hook
|
||||
*/
|
||||
object AntiDetectionHook {
|
||||
|
||||
private val isSanitizingStack = ThreadLocal.withInitial { false }
|
||||
|
||||
private val CAMOUFLAGE_SETTINGS_KEYS = setOf(
|
||||
"development_settings_enabled",
|
||||
"adb_enabled",
|
||||
"mock_location",
|
||||
"ALLOW_MOCK_LOCATION"
|
||||
)
|
||||
|
||||
private const val MODULE_PACKAGE_NAME = "com.lzxnone.openloc"
|
||||
|
||||
// 豁免调用方白名单:LSPosed 管理器、Root 工具和系统包管理组件绝不隐藏,确保能正常读取模块名称与状态
|
||||
private val EXCLUDED_CALLERS = setOf(
|
||||
MODULE_PACKAGE_NAME,
|
||||
"android",
|
||||
"com.android.systemui",
|
||||
"com.android.settings",
|
||||
"org.lsposed.manager",
|
||||
"org.lsposed.lspd",
|
||||
"com.topjohnwu.magisk",
|
||||
"io.github.vvb2060.magisk",
|
||||
"me.weishu.kernelsu",
|
||||
"com.android.packageinstaller",
|
||||
"com.google.android.packageinstaller",
|
||||
"com.miui.packageinstaller"
|
||||
)
|
||||
|
||||
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
hookStackTrace(contextProvider)
|
||||
hookPackageManager(classLoader, contextProvider)
|
||||
hookSettingsCamouflage(classLoader, contextProvider)
|
||||
hookLocationEntityFlags(classLoader)
|
||||
hookSettingsSecure(classLoader)
|
||||
hookGeocoder(classLoader)
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 调用栈隐匿:对 Throwable 与 Thread 的 getStackTrace 进行清洗
|
||||
* 1. 消除 Location 实体类中的 Mock 标记(isFromMockProvider / isMock)
|
||||
*/
|
||||
private fun hookStackTrace(contextProvider: () -> Context?) {
|
||||
try {
|
||||
// Hook Throwable.getStackTrace()
|
||||
XposedHelpers.findAndHookMethod(
|
||||
Throwable::class.java,
|
||||
"getStackTrace",
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (isSanitizingStack.get() == true) return
|
||||
try {
|
||||
isSanitizingStack.set(true)
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return
|
||||
private fun hookLocationEntityFlags(classLoader: ClassLoader) {
|
||||
val locationClass = try {
|
||||
XposedHelpers.findClass("android.location.Location", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: return
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val originalElements = param.result as? Array<StackTraceElement> ?: return
|
||||
var hasForbidden = false
|
||||
for (elem in originalElements) {
|
||||
if (isForbiddenClassName(elem.className)) {
|
||||
hasForbidden = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (hasForbidden) {
|
||||
param.result = originalElements.filter { !isForbiddenClassName(it.className) }.toTypedArray()
|
||||
}
|
||||
} finally {
|
||||
isSanitizingStack.set(false)
|
||||
for (method in locationClass.declaredMethods) {
|
||||
if (method.name == "isFromMockProvider" || method.name == "isMock") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
param.result = false
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Hook Thread.getStackTrace()
|
||||
XposedHelpers.findAndHookMethod(
|
||||
Thread::class.java,
|
||||
"getStackTrace",
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (isSanitizingStack.get() == true) return
|
||||
try {
|
||||
isSanitizingStack.set(true)
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val originalElements = param.result as? Array<StackTraceElement> ?: return
|
||||
var hasForbidden = false
|
||||
for (elem in originalElements) {
|
||||
if (isForbiddenClassName(elem.className)) {
|
||||
hasForbidden = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (hasForbidden) {
|
||||
param.result = originalElements.filter { !isForbiddenClassName(it.className) }.toTypedArray()
|
||||
}
|
||||
} finally {
|
||||
isSanitizingStack.set(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (t: Throwable) {
|
||||
XposedBridge.log("[OpenLoc] hookStackTrace error: ${t.message}")
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isForbiddenClassName(className: String): Boolean {
|
||||
val lower = className.lowercase()
|
||||
return lower.contains("openloc") ||
|
||||
lower.contains("xposed") ||
|
||||
lower.contains("lsposed") ||
|
||||
lower.contains("sandhook") ||
|
||||
lower.contains("edxposed")
|
||||
/**
|
||||
* 2. 拦截 Settings.Secure.mock_location 读取
|
||||
*/
|
||||
private fun hookSettingsSecure(classLoader: ClassLoader) {
|
||||
val secureClass = try {
|
||||
XposedHelpers.findClass("android.provider.Settings\$Secure", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: return
|
||||
|
||||
for (method in secureClass.declaredMethods) {
|
||||
if (method.name == "getString" || method.name == "getStringForUser") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val name = param.args.firstOrNull { it is String } as? String
|
||||
if (name == "mock_location") {
|
||||
param.result = "0"
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
} else if (method.name == "getInt" || method.name == "getIntForUser") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val name = param.args.firstOrNull { it is String } as? String
|
||||
if (name == "mock_location") {
|
||||
param.result = 0
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. PackageManager 模块自隐匿
|
||||
* 3. 拦截 Geocoder 经纬度反查街道真实地址(反向地理编码)
|
||||
*/
|
||||
private fun hookGeocoder(classLoader: ClassLoader) {
|
||||
val geocoderClass = try {
|
||||
XposedHelpers.findClass("android.location.Geocoder", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: return
|
||||
|
||||
for (method in geocoderClass.declaredMethods) {
|
||||
if (method.name == "getFromLocation" || method.name == "getFromLocationName") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
// 若需深度伪装,返回空列表防透传
|
||||
if (param.result == null || (param.result as? List<*>)?.isEmpty() == true) {
|
||||
param.result = emptyList<Any>()
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PackageManager 模块包名安全隐匿
|
||||
*/
|
||||
private fun hookPackageManager(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
val pmClasses = listOf(
|
||||
@@ -142,8 +152,9 @@ object AntiDetectionHook {
|
||||
val pkgName = param.args.firstOrNull { it is String } as? String ?: return
|
||||
if (pkgName == MODULE_PACKAGE_NAME) {
|
||||
val ctx = contextProvider() ?: return
|
||||
if (isCallerExcluded(ctx.packageName)) return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isStealthEnabled) {
|
||||
if (config.shouldMock(ctx.packageName)) {
|
||||
param.throwable = PackageManager.NameNotFoundException(pkgName)
|
||||
}
|
||||
}
|
||||
@@ -158,8 +169,9 @@ object AntiDetectionHook {
|
||||
val pkgName = param.args.firstOrNull { it is String } as? String ?: return
|
||||
if (pkgName == MODULE_PACKAGE_NAME) {
|
||||
val ctx = contextProvider() ?: return
|
||||
if (isCallerExcluded(ctx.packageName)) return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isStealthEnabled) {
|
||||
if (config.shouldMock(ctx.packageName)) {
|
||||
param.throwable = PackageManager.NameNotFoundException(pkgName)
|
||||
}
|
||||
}
|
||||
@@ -172,8 +184,9 @@ object AntiDetectionHook {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
if (isCallerExcluded(ctx.packageName)) return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return
|
||||
if (!config.shouldMock(ctx.packageName)) return
|
||||
|
||||
val list = param.result as? List<*> ?: return
|
||||
val filtered = list.filter {
|
||||
@@ -189,8 +202,9 @@ object AntiDetectionHook {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
if (isCallerExcluded(ctx.packageName)) return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return
|
||||
if (!config.shouldMock(ctx.packageName)) return
|
||||
|
||||
val list = param.result as? List<*> ?: return
|
||||
val filtered = list.filter {
|
||||
@@ -206,75 +220,7 @@ object AntiDetectionHook {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3. 开发者选项与系统模拟位置状态伪装 (Settings.Secure & Settings.Global)
|
||||
*/
|
||||
private fun hookSettingsCamouflage(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
val settingsClasses = listOf(
|
||||
"android.provider.Settings\$Secure",
|
||||
"android.provider.Settings\$Global"
|
||||
)
|
||||
|
||||
for (className in settingsClasses) {
|
||||
val settingsClass = try {
|
||||
XposedHelpers.findClass(className, classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: continue
|
||||
|
||||
for (method in settingsClass.declaredMethods) {
|
||||
val methodName = method.name
|
||||
when (methodName) {
|
||||
"getString" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val key = param.args.firstOrNull { it is String } as? String ?: return
|
||||
if (CAMOUFLAGE_SETTINGS_KEYS.contains(key)) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isDevCamouflageEnabled) {
|
||||
param.result = "0"
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getInt" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val key = param.args.firstOrNull { it is String } as? String ?: return
|
||||
if (CAMOUFLAGE_SETTINGS_KEYS.contains(key)) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isDevCamouflageEnabled) {
|
||||
param.result = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getLong" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val key = param.args.firstOrNull { it is String } as? String ?: return
|
||||
if (CAMOUFLAGE_SETTINGS_KEYS.contains(key)) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isDevCamouflageEnabled) {
|
||||
param.result = 0L
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun isCallerExcluded(callerPackageName: String): Boolean {
|
||||
return EXCLUDED_CALLERS.contains(callerPackageName) || callerPackageName.startsWith("org.lsposed.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.lzxnone.openloc.hook.interceptor
|
||||
|
||||
import android.bluetooth.le.ScanCallback
|
||||
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
|
||||
|
||||
/**
|
||||
* 蓝牙低功耗 (BLE) 扫描与室内 iBeacon 信标断粮拦截器
|
||||
* (基于 GhostMapX 核心架构设计)
|
||||
*
|
||||
* 核心目标:
|
||||
* 阻断室内商场、大厦、地铁站通过 BLE iBeacon 信标扫描反查出物理室内位置,
|
||||
* 彻底封死大厂 App(QQ、微信、打卡软件等)的微定位旁路。
|
||||
*/
|
||||
object BleHook {
|
||||
|
||||
/**
|
||||
* 1. 在 com.android.bluetooth 进程中拦截底层 GattService 与 Native 接口
|
||||
*/
|
||||
fun hookBluetoothProcess(classLoader: ClassLoader) {
|
||||
XposedBridge.log("[OpenLoc] [BleHook] Initializing BleHook for com.android.bluetooth...")
|
||||
|
||||
// A. GattService 拦截
|
||||
val gattServiceClass = try {
|
||||
XposedHelpers.findClass("com.android.bluetooth.gatt.GattService", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
if (gattServiceClass != null) {
|
||||
for (method in gattServiceClass.declaredMethods) {
|
||||
if (method.name == "onScanResult" || method.name == "onBatchScanResults" || method.name == "onFoundOrLost") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled) {
|
||||
// 拦截蓝牙信标广播结果
|
||||
param.result = null
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// B. GattNativeInterface 拦截
|
||||
val nativeInterfaceClass = try {
|
||||
XposedHelpers.findClass("com.android.bluetooth.gatt.GattNativeInterface", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
if (nativeInterfaceClass != null) {
|
||||
for (method in nativeInterfaceClass.declaredMethods) {
|
||||
if (method.name.contains("onScan")) {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled) {
|
||||
param.result = null
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. 在目标客户端 App 进程中拦截 BluetoothLeScanner.startScan
|
||||
*/
|
||||
fun hookClient(classLoader: ClassLoader, packageName: String) {
|
||||
val scannerClass = try {
|
||||
XposedHelpers.findClass("android.bluetooth.le.BluetoothLeScanner", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: return
|
||||
|
||||
for (method in scannerClass.declaredMethods) {
|
||||
if (method.name == "startScan") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
|
||||
// 寻找 ScanCallback 参数并阻断或返回空结果
|
||||
val callback = param.args.firstOrNull { it is ScanCallback } as? ScanCallback
|
||||
if (callback != null) {
|
||||
try {
|
||||
// 给调用者触发一次空的批量扫描结果,避免某些应用抛出未收到扫描回调异常
|
||||
callback.onBatchScanResults(emptyList())
|
||||
param.result = null
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,312 +3,66 @@
|
||||
package com.lzxnone.openloc.hook.interceptor
|
||||
|
||||
import android.content.Context
|
||||
import android.location.GnssStatus
|
||||
import android.location.GpsStatus
|
||||
import android.location.LocationManager
|
||||
import android.location.OnNmeaMessageListener
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
|
||||
import com.lzxnone.openloc.hook.util.LocationSimulator
|
||||
import com.lzxnone.openloc.hook.util.VirtualGnssEngine
|
||||
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
|
||||
|
||||
/**
|
||||
* 全真多星座 GNSS 卫星与 NMEA 报文拦截器
|
||||
*
|
||||
* 1. 深度拦截 GnssStatus.Callback,构造注入 26 颗多星座卫星(GPS、北斗、GLONASS、Galileo)
|
||||
* 2. 维持 1Hz 卫星心跳分发,室内/无真实信号下仍持续稳定分发有效卫星解
|
||||
* 3. 拦截 NMEA 监听器,全量伪造 $GNGGA、$GNRMC、$GNGSA、$BDGSA、$GPGSV、$BDGSV、$GLGSV
|
||||
* 4. 兼容旧版 GpsStatus.Listener 探测
|
||||
* 轻量稳健的 GNSS 卫星与 NMEA 拦截器(GhostMapX 设计)
|
||||
* 不再运行消耗 CPU 的 26 卫星物理引擎与大定时器,
|
||||
* 专注于阻断真实卫星泄露并抹除冷启动定星超时。
|
||||
*/
|
||||
object GnssHook {
|
||||
|
||||
private val isDeliveringNmea = ThreadLocal.withInitial { false }
|
||||
private val activeGnssCallbacks = Collections.newSetFromMap(WeakHashMap<GnssStatus.Callback, Boolean>())
|
||||
private val activeGpsListeners = Collections.newSetFromMap(WeakHashMap<GpsStatus.Listener, Boolean>())
|
||||
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
|
||||
if (packageName == "com.lzxnone.openloc") return
|
||||
|
||||
@Volatile
|
||||
private var isTickerStarted = false
|
||||
private var mainHandler: Handler? = null
|
||||
|
||||
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
hookNmeaListener(contextProvider)
|
||||
hookGnssStatusCallbacks(classLoader, contextProvider)
|
||||
hookGpsStatusLegacy(contextProvider)
|
||||
hookNmeaListener(packageName)
|
||||
hookGpsStatusLegacy(packageName)
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 拦截并分发全真 NMEA-0183 多星座报文阵列
|
||||
* 阻断/规整 NMEA 原始报文,防止经纬度及原始卫星数据穿透
|
||||
*/
|
||||
private fun hookNmeaListener(contextProvider: () -> Context?) {
|
||||
private fun hookNmeaListener(packageName: String) {
|
||||
try {
|
||||
val methods = LocationManager::class.java.declaredMethods
|
||||
for (method in methods) {
|
||||
if (method.name == "addNmeaListener") {
|
||||
val paramTypes = method.parameterTypes
|
||||
val listenerIndex = paramTypes.indexOfFirst {
|
||||
OnNmeaMessageListener::class.java.isAssignableFrom(it)
|
||||
}
|
||||
|
||||
if (listenerIndex != -1) {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val originalListener = param.args[listenerIndex] as? OnNmeaMessageListener ?: return
|
||||
hookNmeaCallback(originalListener, contextProvider)
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
XposedBridge.log("[OpenLoc] hookNmeaListener error: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private val hookedNmeaClasses = mutableSetOf<String>()
|
||||
|
||||
private fun hookNmeaCallback(listener: OnNmeaMessageListener, contextProvider: () -> Context?) {
|
||||
val clazz = listener.javaClass
|
||||
val className = clazz.name
|
||||
if (hookedNmeaClasses.contains(className)) return
|
||||
hookedNmeaClasses.add(className)
|
||||
|
||||
try {
|
||||
XposedHelpers.findAndHookMethod(
|
||||
clazz,
|
||||
"onNmeaMessage",
|
||||
String::class.java,
|
||||
Long::class.javaPrimitiveType,
|
||||
object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (isDeliveringNmea.get() == true) return
|
||||
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return
|
||||
|
||||
val rawMessage = param.args[0] as? String ?: return
|
||||
val timestamp = param.args[1] as? Long ?: System.currentTimeMillis()
|
||||
|
||||
// 当系统开始触发 NMEA 时,动态替换并批量补齐多星座全套报文
|
||||
if (rawMessage.startsWith("\$GP") || rawMessage.startsWith("\$GN") || rawMessage.startsWith("\$BD")) {
|
||||
val (curLat, curLng) = LocationSimulator.getSimulatedCoordinates(
|
||||
config.latitude,
|
||||
config.longitude,
|
||||
config.isJitterEnabled
|
||||
)
|
||||
|
||||
val fullNmeaList = VirtualGnssEngine.generateFullNmeaSequence(curLat, curLng, timestamp)
|
||||
if (fullNmeaList.isNotEmpty()) {
|
||||
// 替换当前句为第一句($GNGGA)
|
||||
param.args[0] = fullNmeaList[0]
|
||||
|
||||
// 补发剩余语句 ($GNRMC, $GNGSA, $BDGSA, $GPGSV...)
|
||||
try {
|
||||
isDeliveringNmea.set(true)
|
||||
val targetListener = param.thisObject as? OnNmeaMessageListener
|
||||
if (targetListener != null) {
|
||||
for (i in 1 until fullNmeaList.size) {
|
||||
targetListener.onNmeaMessage(fullNmeaList[i], timestamp)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
isDeliveringNmea.set(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. 深度拦截 GnssStatus 回调并维持 1Hz 卫星心跳
|
||||
*/
|
||||
private fun hookGnssStatusCallbacks(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
try {
|
||||
// (1) 拦截 LocationManager.registerGnssStatusCallback 各重载
|
||||
val methods = LocationManager::class.java.declaredMethods
|
||||
for (method in methods) {
|
||||
if (method.name == "registerGnssStatusCallback") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val callback = param.args.firstOrNull { it is GnssStatus.Callback } as? GnssStatus.Callback ?: return
|
||||
synchronized(activeGnssCallbacks) {
|
||||
activeGnssCallbacks.add(callback)
|
||||
}
|
||||
ensureTickerStarted(contextProvider)
|
||||
hookSingleGnssCallbackClass(callback.javaClass, contextProvider)
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
} else if (method.name == "unregisterGnssStatusCallback") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val callback = param.args.firstOrNull { it is GnssStatus.Callback } as? GnssStatus.Callback ?: return
|
||||
synchronized(activeGnssCallbacks) {
|
||||
activeGnssCallbacks.remove(callback)
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
// 开启模拟定位时,不向应用分发真实硬件原始 NMEA 报文
|
||||
param.result = true
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
XposedBridge.log("[OpenLoc] hookGnssStatusCallbacks error: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private val hookedGnssCallbackClasses = mutableSetOf<String>()
|
||||
|
||||
private fun hookSingleGnssCallbackClass(clazz: Class<*>, contextProvider: () -> Context?) {
|
||||
val className = clazz.name
|
||||
if (hookedGnssCallbackClasses.contains(className)) return
|
||||
hookedGnssCallbackClasses.add(className)
|
||||
|
||||
try {
|
||||
// Hook onSatelliteStatusChanged(GnssStatus)
|
||||
XposedHelpers.findAndHookMethod(
|
||||
clazz,
|
||||
"onSatelliteStatusChanged",
|
||||
GnssStatus::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return
|
||||
|
||||
val fakeStatus = VirtualGnssEngine.createGnssStatus()
|
||||
if (fakeStatus != null) {
|
||||
param.args[0] = fakeStatus
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3. 启动 1Hz 定时卫星仿真分发调度(针对无真实卫星信号、室内等环境兜底)
|
||||
* 兼容老版本 SDK 的 GpsStatus.Listener,恒定返回已极速定星状态
|
||||
*/
|
||||
private fun ensureTickerStarted(contextProvider: () -> Context?) {
|
||||
if (isTickerStarted) return
|
||||
synchronized(this) {
|
||||
if (isTickerStarted) return
|
||||
isTickerStarted = true
|
||||
|
||||
if (mainHandler == null) {
|
||||
try {
|
||||
mainHandler = Handler(Looper.getMainLooper())
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
mainHandler?.post(object : Runnable {
|
||||
override fun run() {
|
||||
try {
|
||||
dispatchSimulatedGnssTick(contextProvider)
|
||||
} catch (_: Throwable) {}
|
||||
mainHandler?.postDelayed(this, 1000L) // 1 秒刷新一次
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private val notifiedFirstFixSet = Collections.newSetFromMap(WeakHashMap<GnssStatus.Callback, Boolean>())
|
||||
|
||||
private fun dispatchSimulatedGnssTick(contextProvider: () -> Context?) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return
|
||||
|
||||
val fakeStatus = VirtualGnssEngine.createGnssStatus() ?: return
|
||||
|
||||
val callbacksSnapshot = synchronized(activeGnssCallbacks) {
|
||||
activeGnssCallbacks.toList()
|
||||
}
|
||||
|
||||
for (cb in callbacksSnapshot) {
|
||||
try {
|
||||
if (!notifiedFirstFixSet.contains(cb)) {
|
||||
notifiedFirstFixSet.add(cb)
|
||||
cb.onStarted()
|
||||
cb.onFirstFix(1200) // 1.2s 极速逼真定位时间
|
||||
}
|
||||
cb.onSatelliteStatusChanged(fakeStatus)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
// 兼容旧版 GpsStatus
|
||||
val listenersSnapshot = synchronized(activeGpsListeners) {
|
||||
activeGpsListeners.toList()
|
||||
}
|
||||
for (listener in listenersSnapshot) {
|
||||
try {
|
||||
listener.onGpsStatusChanged(GpsStatus.GPS_EVENT_SATELLITE_STATUS)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. 兼容老版本 SDK 的 GpsStatus.Listener
|
||||
*/
|
||||
private fun hookGpsStatusLegacy(contextProvider: () -> Context?) {
|
||||
private fun hookGpsStatusLegacy(packageName: String) {
|
||||
try {
|
||||
// Hook addGpsStatusListener
|
||||
XposedHelpers.findAndHookMethod(
|
||||
LocationManager::class.java,
|
||||
"addGpsStatusListener",
|
||||
GpsStatus.Listener::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val listener = param.args[0] as? GpsStatus.Listener ?: return
|
||||
synchronized(activeGpsListeners) {
|
||||
activeGpsListeners.add(listener)
|
||||
}
|
||||
ensureTickerStarted(contextProvider)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Hook removeGpsStatusListener
|
||||
XposedHelpers.findAndHookMethod(
|
||||
LocationManager::class.java,
|
||||
"removeGpsStatusListener",
|
||||
GpsStatus.Listener::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val listener = param.args[0] as? GpsStatus.Listener ?: return
|
||||
synchronized(activeGpsListeners) {
|
||||
activeGpsListeners.remove(listener)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Hook getGpsStatus(GpsStatus status)
|
||||
XposedHelpers.findAndHookMethod(
|
||||
LocationManager::class.java,
|
||||
"getGpsStatus",
|
||||
GpsStatus::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
|
||||
val status = (param.result as? GpsStatus) ?: (param.args[0] as? GpsStatus) ?: return
|
||||
val status = (param.result as? GpsStatus) ?: (param.args.getOrNull(0) as? GpsStatus) ?: return
|
||||
try {
|
||||
XposedHelpers.setIntField(status, "mTimeToFirstFix", 1200)
|
||||
XposedHelpers.setIntField(status, "mTimeToFirstFix", 1000)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,222 +5,260 @@ import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
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.util.LocationSimulator
|
||||
import com.lzxnone.openloc.hook.model.GlobalMockMemory
|
||||
import de.robv.android.xposed.XC_MethodHook
|
||||
import de.robv.android.xposed.XC_MethodReplacement
|
||||
import de.robv.android.xposed.XposedBridge
|
||||
import de.robv.android.xposed.XposedHelpers
|
||||
import java.lang.reflect.Proxy
|
||||
import java.util.Collections
|
||||
import java.util.WeakHashMap
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/**
|
||||
* 原生定位服务 LocationManager 与 Location 实体拦截器
|
||||
* 客户端 LocationManager 拦截器(严格对齐 GhostMapX LYe/LXe 实现)
|
||||
*
|
||||
* 核心机制:
|
||||
* 1. 绝不盲目 Hook Location.getLatitude/getLongitude(避免破坏地图SDK投影测距与自身重置);
|
||||
* 2. 绝不 Hook Location.writeToParcel;
|
||||
* 3. 在客户端 LocationManager 的关键出口拦截:
|
||||
* - getLastKnownLocation / getLastLocation: afterHookedMethod 篡改或注入新 Location;
|
||||
* - getCurrentLocation (Android 11+): 拦截 Consumer 并立即交付虚拟坐标;
|
||||
* - requestLocationUpdates / requestSingleUpdate: 挂钩 Listener 并秒推首帧;
|
||||
* - 核心传输通道(GetCurrentLocationTransport / BatchedLocationCallbackWrapper / LocationListenerTransport):
|
||||
* 在其 onLocation / onLocationChanged 回调发生时就地修改 Location 实体。
|
||||
*/
|
||||
object LocationHook {
|
||||
|
||||
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
hookLocationEntity()
|
||||
hookLocationManager(classLoader, contextProvider)
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 拦截 Location 实体类中的 Mock 判定方法
|
||||
*/
|
||||
private fun hookLocationEntity() {
|
||||
try {
|
||||
// Hook isFromMockProvider 恒返回 false
|
||||
XposedHelpers.findAndHookMethod(
|
||||
Location::class.java,
|
||||
"isFromMockProvider",
|
||||
object : XC_MethodReplacement() {
|
||||
override fun replaceHookedMethod(param: MethodHookParam?): Any {
|
||||
return false
|
||||
}
|
||||
}
|
||||
)
|
||||
private fun refreshConfigIfPossible() {
|
||||
val ctx = currentContextProvider?.invoke() ?: return
|
||||
ConfigFetcher.getConfig(ctx)
|
||||
}
|
||||
|
||||
// Android 12 (API 31)+ isMock() 恒返回 false
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
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 {
|
||||
XposedHelpers.findAndHookMethod(
|
||||
Location::class.java,
|
||||
"isMock",
|
||||
object : XC_MethodReplacement() {
|
||||
override fun replaceHookedMethod(param: MethodHookParam?): Any {
|
||||
return false
|
||||
}
|
||||
}
|
||||
)
|
||||
val mockLoc = GlobalMockMemory.createLocation(provider)
|
||||
listener.onLocationChanged(mockLoc)
|
||||
TraceLogger.w("ClientHook", "[$pkg] Active push on config change -> ${TraceLogger.formatLocation(mockLoc)}")
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
XposedBridge.log("[OpenLoc] hookLocationEntity failed: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. 拦截 LocationManager 的核心定位获取方法
|
||||
*/
|
||||
private fun hookLocationManager(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
try {
|
||||
// (1) 拦截 getLastKnownLocation
|
||||
XposedHelpers.findAndHookMethod(
|
||||
LocationManager::class.java,
|
||||
"getLastKnownLocation",
|
||||
String::class.java,
|
||||
object : XC_MethodHook() {
|
||||
private fun hookClientLocationManager(classLoader: ClassLoader, packageName: String) {
|
||||
val lmClass = LocationManager::class.java
|
||||
|
||||
// 1. getLastKnownLocation 与 getLastLocation 拦截(GhostMapX 经典实现)
|
||||
val getLastMethods = listOf("getLastKnownLocation", "getLastLocation")
|
||||
for (methodName in getLastMethods) {
|
||||
try {
|
||||
XposedBridge.hookAllMethods(lmClass, methodName, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName)) return
|
||||
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")
|
||||
|
||||
val provider = param.args[0] as? String ?: LocationManager.GPS_PROVIDER
|
||||
param.result = LocationSimulator.createMockLocation(
|
||||
latitude = config.latitude,
|
||||
longitude = config.longitude,
|
||||
provider = provider,
|
||||
isJitterEnabled = config.isJitterEnabled
|
||||
)
|
||||
if (!shouldMock) return
|
||||
|
||||
val provider = param.args.firstOrNull { it is String } as? String ?: "gps"
|
||||
val mockLoc = GlobalMockMemory.createLocation(provider)
|
||||
param.result = mockLoc
|
||||
TraceLogger.w("ClientHook", "[$packageName] $methodName -> REPLACED with ${TraceLogger.formatLocation(mockLoc)}")
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// (2) 拦截 requestLocationUpdates 各重载中传入的 LocationListener
|
||||
val methods = LocationManager::class.java.declaredMethods
|
||||
for (method in methods) {
|
||||
if (method.name == "requestLocationUpdates") {
|
||||
val paramTypes = method.parameterTypes
|
||||
val listenerIndex = paramTypes.indexOfFirst {
|
||||
LocationListener::class.java.isAssignableFrom(it)
|
||||
}
|
||||
|
||||
if (listenerIndex != -1) {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val originalListener = param.args[listenerIndex] as? LocationListener ?: return
|
||||
// 拦截回调类并 Hook 其 onLocationChanged
|
||||
hookListenerClass(originalListener.javaClass, contextProvider)
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (3) Android 12+ 拦截 getCurrentLocation 异步单次定位
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
hookGetCurrentLocation(contextProvider)
|
||||
}
|
||||
|
||||
} catch (t: Throwable) {
|
||||
XposedBridge.log("[OpenLoc] hookLocationManager failed: ${t.message}")
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook 具体应用实现的 LocationListener.onLocationChanged
|
||||
*/
|
||||
private val hookedListenerClasses = mutableSetOf<String>()
|
||||
|
||||
private fun hookListenerClass(clazz: Class<*>, contextProvider: () -> Context?) {
|
||||
val className = clazz.name
|
||||
if (hookedListenerClasses.contains(className)) return
|
||||
hookedListenerClasses.add(className)
|
||||
|
||||
// 2. isProviderEnabled 恒返回 true
|
||||
try {
|
||||
// Hook onLocationChanged(Location)
|
||||
XposedHelpers.findAndHookMethod(
|
||||
clazz,
|
||||
"onLocationChanged",
|
||||
Location::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName)) return
|
||||
|
||||
val location = param.args[0] as? Location
|
||||
if (location != null) {
|
||||
LocationSimulator.applyMockData(location, config.latitude, config.longitude, config.isJitterEnabled)
|
||||
} else {
|
||||
param.args[0] = LocationSimulator.createMockLocation(
|
||||
config.latitude,
|
||||
config.longitude,
|
||||
isJitterEnabled = config.isJitterEnabled
|
||||
)
|
||||
XposedBridge.hookAllMethods(lmClass, "isProviderEnabled", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
val provider = param.args.firstOrNull { it is String } as? String
|
||||
if (provider == LocationManager.GPS_PROVIDER ||
|
||||
provider == LocationManager.NETWORK_PROVIDER ||
|
||||
provider == "fused") {
|
||||
param.result = true
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
|
||||
// Android 14 (API 34)+ 新增 onLocationChanged(List<Location>)
|
||||
try {
|
||||
XposedHelpers.findAndHookMethod(
|
||||
clazz,
|
||||
"onLocationChanged",
|
||||
List::class.java,
|
||||
object : XC_MethodHook() {
|
||||
// 3. requestLocationUpdates 与 requestSingleUpdate 拦截
|
||||
val requestMethods = listOf("requestLocationUpdates", "requestSingleUpdate")
|
||||
for (methodName in requestMethods) {
|
||||
try {
|
||||
XposedBridge.hookAllMethods(lmClass, methodName, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName)) return
|
||||
refreshConfigIfPossible()
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val list = param.args[0] as? List<Location> ?: return
|
||||
for (loc in list) {
|
||||
LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
|
||||
// 注册瞬间秒推首帧,消除冷启动无星等待
|
||||
val listener = param.args.firstOrNull { it is LocationListener } as? LocationListener ?: return
|
||||
val provider = param.args.firstOrNull { it is String } as? String ?: "gps"
|
||||
val mockLoc = GlobalMockMemory.createLocation(provider)
|
||||
|
||||
mainHandler.post {
|
||||
try {
|
||||
listener.onLocationChanged(mockLoc)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
})
|
||||
} 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) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Android 11+ / 12+ 单次定位 getCurrentLocation 拦截
|
||||
* 拦截系统 Binder 回调的传输层 Transport(GhostMapX 关键手段)
|
||||
*/
|
||||
private fun hookGetCurrentLocation(contextProvider: () -> Context?) {
|
||||
val methods = LocationManager::class.java.declaredMethods
|
||||
for (method in methods) {
|
||||
if (method.name == "getCurrentLocation") {
|
||||
private fun hookLocationTransports(classLoader: ClassLoader, packageName: String) {
|
||||
val transportClasses = listOf(
|
||||
"android.location.LocationManager\$GetCurrentLocationTransport",
|
||||
"android.location.LocationManager\$BatchedLocationCallbackWrapper",
|
||||
"android.location.LocationManager\$LocationListenerTransport"
|
||||
)
|
||||
|
||||
for (className in transportClasses) {
|
||||
try {
|
||||
val clazz = XposedHelpers.findClassIfExists(className, classLoader) ?: continue
|
||||
|
||||
// Hook onLocation
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
XposedBridge.hookAllMethods(clazz, "onLocation", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName)) return
|
||||
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")
|
||||
|
||||
// Consumer<Location> 通常位于最后一位
|
||||
val lastIndex = param.args.size - 1
|
||||
if (lastIndex >= 0) {
|
||||
val originalConsumer = param.args[lastIndex] ?: return
|
||||
val consumerInterface = originalConsumer.javaClass.interfaces.firstOrNull {
|
||||
it.name == "java.util.function.Consumer"
|
||||
} ?: return
|
||||
if (!shouldMock || loc == null) return
|
||||
val mockLoc = GlobalMockMemory.createLocation(loc.provider ?: "gps")
|
||||
TraceLogger.w("ClientTransport", "[$packageName] Transport.onLocation: REPLACED with ${TraceLogger.formatLocation(mockLoc)}")
|
||||
param.args[0] = mockLoc
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
|
||||
val proxy = Proxy.newProxyInstance(
|
||||
consumerInterface.classLoader,
|
||||
arrayOf(consumerInterface)
|
||||
) { _, m, args ->
|
||||
if (m.name == "accept" && args != null && args.isNotEmpty()) {
|
||||
val mockLoc = LocationSimulator.createMockLocation(
|
||||
config.latitude,
|
||||
config.longitude,
|
||||
isJitterEnabled = config.isJitterEnabled
|
||||
)
|
||||
m.invoke(originalConsumer, mockLoc)
|
||||
} else {
|
||||
m.invoke(originalConsumer, *(args ?: emptyArray()))
|
||||
}
|
||||
// Hook onLocationChanged
|
||||
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")
|
||||
|
||||
if (!shouldMock || arg == null) return
|
||||
if (arg is Location) {
|
||||
val mockLoc = GlobalMockMemory.createLocation(arg.provider ?: "gps")
|
||||
TraceLogger.w("ClientTransport", "[$packageName] Transport.onLocationChanged: REPLACED with ${TraceLogger.formatLocation(mockLoc)}")
|
||||
param.args[0] = mockLoc
|
||||
} else if (arg is List<*>) {
|
||||
val mockList = ArrayList<Location>(arg.size)
|
||||
for (item in arg) {
|
||||
val provider = (item as? Location)?.provider ?: "gps"
|
||||
mockList.add(GlobalMockMemory.createLocation(provider))
|
||||
}
|
||||
param.args[lastIndex] = proxy
|
||||
TraceLogger.w("ClientTransport", "[$packageName] Transport.onLocationChanged(List): REPLACED ${arg.size} items")
|
||||
param.args[0] = mockList
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
private fun hookLocationListenerClass(clazz: Class<*>, packageName: String) {
|
||||
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() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val arg = param.args.getOrNull(0)
|
||||
val shouldMock = GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)
|
||||
TraceLogger.d("ClientListener", "[$packageName] Listener.onLocationChanged: incoming=${if (arg is Location) TraceLogger.formatLocation(arg) else arg?.toString()}, shouldMock=$shouldMock")
|
||||
|
||||
if (!shouldMock || arg == null) return
|
||||
if (arg is Location) {
|
||||
val mockLoc = GlobalMockMemory.createLocation(arg.provider ?: "gps")
|
||||
TraceLogger.w("ClientListener", "[$packageName] Listener.onLocationChanged: REPLACED with ${TraceLogger.formatLocation(mockLoc)}")
|
||||
param.args[0] = mockLoc
|
||||
} else if (arg is List<*>) {
|
||||
val mockList = ArrayList<Location>(arg.size)
|
||||
for (item in arg) {
|
||||
val provider = (item as? Location)?.provider ?: "gps"
|
||||
mockList.add(GlobalMockMemory.createLocation(provider))
|
||||
}
|
||||
TraceLogger.w("ClientListener", "[$packageName] Listener.onLocationChanged(List): REPLACED ${arg.size} items")
|
||||
param.args[0] = mockList
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import android.telephony.CellLocation
|
||||
import android.telephony.PhoneStateListener
|
||||
import android.telephony.TelephonyManager
|
||||
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
|
||||
@@ -23,20 +24,22 @@ import de.robv.android.xposed.XposedHelpers
|
||||
* 1. 拦截 WifiManager 扫描列表与连接 BSSID/MAC,阻断高德/腾讯/百度云端 Wi-Fi 指纹库反查真实物理位置
|
||||
* 2. 拦截 TelephonyManager 基站小区信息与位置监听,杜绝基站 LAC/CID 反查
|
||||
* 3. 拦截 PhoneStateListener 与 Android 12+ TelephonyCallback 实时小区回调
|
||||
* 4. 彻底消除 contextProvider 冷启动时序漏洞:在启动第 0 毫秒优先判定 GlobalMockMemory,
|
||||
* 哪怕 Context 尚未初始化也坚决阻断真实 Wi-Fi/基站外泄!
|
||||
*/
|
||||
object NetworkLocationHook {
|
||||
|
||||
private const val ANONYMOUS_MAC = "02:00:00:00:00:00"
|
||||
|
||||
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
hookWifiManager(contextProvider)
|
||||
hookTelephonyManager(classLoader, contextProvider)
|
||||
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
|
||||
hookWifiManager(packageName, contextProvider)
|
||||
hookTelephonyManager(classLoader, packageName, contextProvider)
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 深度拦截 Wi-Fi 扫描结果与连接 BSSID / MAC
|
||||
*/
|
||||
private fun hookWifiManager(contextProvider: () -> Context?) {
|
||||
private fun hookWifiManager(packageName: String, contextProvider: () -> Context?) {
|
||||
try {
|
||||
// (1) 拦截 WifiManager.getScanResults()
|
||||
XposedHelpers.findAndHookMethod(
|
||||
@@ -44,9 +47,7 @@ object NetworkLocationHook {
|
||||
"getScanResults",
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
|
||||
if (shouldMockNetwork(packageName, contextProvider)) {
|
||||
param.result = emptyList<ScanResult>()
|
||||
}
|
||||
}
|
||||
@@ -59,9 +60,7 @@ object NetworkLocationHook {
|
||||
"getBSSID",
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
|
||||
if (shouldMockNetwork(packageName, contextProvider)) {
|
||||
param.result = ANONYMOUS_MAC
|
||||
}
|
||||
}
|
||||
@@ -74,9 +73,7 @@ object NetworkLocationHook {
|
||||
"getMacAddress",
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
|
||||
if (shouldMockNetwork(packageName, contextProvider)) {
|
||||
param.result = ANONYMOUS_MAC
|
||||
}
|
||||
}
|
||||
@@ -90,7 +87,7 @@ object NetworkLocationHook {
|
||||
/**
|
||||
* 2. 深度拦截基站塔信息(MCC/MNC/LAC/CID)与实时监听器
|
||||
*/
|
||||
private fun hookTelephonyManager(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
private fun hookTelephonyManager(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
|
||||
try {
|
||||
// (1) 拦截 getAllCellInfo
|
||||
XposedHelpers.findAndHookMethod(
|
||||
@@ -98,9 +95,7 @@ object NetworkLocationHook {
|
||||
"getAllCellInfo",
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
|
||||
if (shouldMockNetwork(packageName, contextProvider)) {
|
||||
param.result = emptyList<CellInfo>()
|
||||
}
|
||||
}
|
||||
@@ -113,9 +108,7 @@ object NetworkLocationHook {
|
||||
"getCellLocation",
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
|
||||
if (shouldMockNetwork(packageName, contextProvider)) {
|
||||
param.result = null
|
||||
}
|
||||
}
|
||||
@@ -131,14 +124,14 @@ object NetworkLocationHook {
|
||||
object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val listener = param.args[0] as? PhoneStateListener ?: return
|
||||
hookPhoneStateListenerClass(listener.javaClass, contextProvider)
|
||||
hookPhoneStateListenerClass(listener.javaClass, packageName, contextProvider)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// (4) Android 12+ TelephonyCallback 拦截
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
hookTelephonyCallback(classLoader, contextProvider)
|
||||
hookTelephonyCallback(classLoader, packageName, contextProvider)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
XposedBridge.log("[OpenLoc] hookTelephonyManager error: ${t.message}")
|
||||
@@ -147,7 +140,7 @@ object NetworkLocationHook {
|
||||
|
||||
private val hookedListenerClasses = mutableSetOf<String>()
|
||||
|
||||
private fun hookPhoneStateListenerClass(clazz: Class<*>, contextProvider: () -> Context?) {
|
||||
private fun hookPhoneStateListenerClass(clazz: Class<*>, packageName: String, contextProvider: () -> Context?) {
|
||||
val className = clazz.name
|
||||
if (hookedListenerClasses.contains(className)) return
|
||||
hookedListenerClasses.add(className)
|
||||
@@ -160,9 +153,7 @@ object NetworkLocationHook {
|
||||
CellLocation::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
|
||||
if (shouldMockNetwork(packageName, contextProvider)) {
|
||||
param.args[0] = null
|
||||
}
|
||||
}
|
||||
@@ -178,9 +169,7 @@ object NetworkLocationHook {
|
||||
List::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
|
||||
if (shouldMockNetwork(packageName, contextProvider)) {
|
||||
param.args[0] = emptyList<CellInfo>()
|
||||
}
|
||||
}
|
||||
@@ -189,7 +178,7 @@ object NetworkLocationHook {
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
private fun hookTelephonyCallback(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
private fun hookTelephonyCallback(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
|
||||
try {
|
||||
val callbackClass = XposedHelpers.findClass("android.telephony.TelephonyCallback", classLoader)
|
||||
val methods = TelephonyManager::class.java.declaredMethods
|
||||
@@ -198,7 +187,7 @@ object NetworkLocationHook {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val cb = param.args.firstOrNull { it != null && callbackClass.isAssignableFrom(it.javaClass) } ?: return
|
||||
hookTelephonyCallbackClass(cb.javaClass, contextProvider)
|
||||
hookTelephonyCallbackClass(cb.javaClass, packageName, contextProvider)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -206,7 +195,7 @@ object NetworkLocationHook {
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
private fun hookTelephonyCallbackClass(clazz: Class<*>, contextProvider: () -> Context?) {
|
||||
private fun hookTelephonyCallbackClass(clazz: Class<*>, packageName: String, contextProvider: () -> Context?) {
|
||||
val className = clazz.name
|
||||
if (hookedListenerClasses.contains(className)) return
|
||||
hookedListenerClasses.add(className)
|
||||
@@ -216,9 +205,7 @@ object NetworkLocationHook {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
|
||||
if (shouldMockNetwork(packageName, contextProvider)) {
|
||||
param.args[0] = emptyList<CellInfo>()
|
||||
}
|
||||
}
|
||||
@@ -228,9 +215,7 @@ object NetworkLocationHook {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
|
||||
if (shouldMockNetwork(packageName, contextProvider)) {
|
||||
param.args[0] = null
|
||||
}
|
||||
}
|
||||
@@ -239,4 +224,17 @@ object NetworkLocationHook {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun shouldMockNetwork(packageName: String, contextProvider: () -> Context?): Boolean {
|
||||
if (packageName == "com.lzxnone.openloc") return false
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
return true
|
||||
}
|
||||
val ctx = contextProvider()
|
||||
if (ctx != null) {
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
return config.shouldMock(packageName.ifBlank { ctx.packageName })
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -2,107 +2,263 @@ package com.lzxnone.openloc.hook.interceptor
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
|
||||
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 kotlin.random.Random
|
||||
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. 拦截 SensorManager.registerListener,捕获应用注册的传感器监听器
|
||||
* 2. 针对加速度计 (TYPE_ACCELEROMETER) 与重力传感器 (TYPE_GRAVITY),动态注入人体手持特有的生物力学生理颤动(Physiological Tremor)
|
||||
* 3. 防止加速度方差几乎为 0 导致被高精风控判定为“放置在桌面的静止刚体设备”
|
||||
* 4. 针对陀螺仪 (TYPE_GYROSCOPE) 注入极细微的手持角速度扰动
|
||||
* 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 hookedListenerClasses = mutableSetOf<String>()
|
||||
private val handleToType = ConcurrentHashMap<Int, Int>()
|
||||
private val isInitialized = AtomicBoolean(false)
|
||||
@Volatile private var catalogInitialized = false
|
||||
|
||||
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
hookSensorManager(contextProvider)
|
||||
// 低通滤波估算的重力方向向量(用于沿实际手持姿态方向叠加步态垂直冲击)
|
||||
@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 hookSensorManager(contextProvider: () -> Context?) {
|
||||
try {
|
||||
val methods = SensorManager::class.java.declaredMethods
|
||||
for (method in methods) {
|
||||
if (method.name == "registerListener") {
|
||||
val paramTypes = method.parameterTypes
|
||||
val listenerIndex = paramTypes.indexOfFirst {
|
||||
SensorEventListener::class.java.isAssignableFrom(it)
|
||||
}
|
||||
private fun hookSensorRegistration(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
val systemSensorManagerClass = try {
|
||||
XposedHelpers.findClassIfExists("android.hardware.SystemSensorManager", classLoader)
|
||||
?: SensorManager::class.java
|
||||
} catch (_: Throwable) {
|
||||
SensorManager::class.java
|
||||
}
|
||||
|
||||
if (listenerIndex != -1) {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val listener = param.args[listenerIndex] as? SensorEventListener ?: return
|
||||
hookSensorEventListenerClass(listener.javaClass, contextProvider)
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
XposedBridge.log("[OpenLoc] hookSensorManager error: ${t.message}")
|
||||
}
|
||||
|
||||
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) {}
|
||||
}
|
||||
}
|
||||
|
||||
private fun hookSensorEventListenerClass(clazz: Class<*>, contextProvider: () -> Context?) {
|
||||
val className = clazz.name
|
||||
if (hookedListenerClasses.contains(className)) return
|
||||
hookedListenerClasses.add(className)
|
||||
internal fun applySensorSimulation(sensorType: Int, values: FloatArray, speedMps: Float, nowNs: Long) {
|
||||
val timeSec = nowNs * 1e-9
|
||||
|
||||
try {
|
||||
XposedHelpers.findAndHookMethod(
|
||||
clazz,
|
||||
"onSensorChanged",
|
||||
SensorEvent::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val ctx = contextProvider() ?: return
|
||||
val config = ConfigFetcher.getConfig(ctx)
|
||||
if (!config.shouldMock(ctx.packageName) || !config.isSensorSimulationEnabled) return
|
||||
|
||||
val event = param.args[0] as? SensorEvent ?: return
|
||||
val sensorType = event.sensor?.type ?: return
|
||||
|
||||
when (sensorType) {
|
||||
// 1. 三轴加速度计(最核心):注入人体手持 ~0.05 m/s² 生理微颤
|
||||
Sensor.TYPE_ACCELEROMETER -> {
|
||||
if (event.values.size >= 3) {
|
||||
event.values[0] += (Random.nextFloat() - 0.5f) * 0.08f
|
||||
event.values[1] += (Random.nextFloat() - 0.5f) * 0.08f
|
||||
event.values[2] += (Random.nextFloat() - 0.5f) * 0.08f
|
||||
}
|
||||
}
|
||||
// 2. 重力传感器:微量波动维持向量模长
|
||||
Sensor.TYPE_GRAVITY -> {
|
||||
if (event.values.size >= 3) {
|
||||
event.values[0] += (Random.nextFloat() - 0.5f) * 0.04f
|
||||
event.values[1] += (Random.nextFloat() - 0.5f) * 0.04f
|
||||
event.values[2] += (Random.nextFloat() - 0.5f) * 0.04f
|
||||
}
|
||||
}
|
||||
// 3. 陀螺仪:手持微弱角速度波动 (rad/s)
|
||||
Sensor.TYPE_GYROSCOPE -> {
|
||||
if (event.values.size >= 3) {
|
||||
event.values[0] += (Random.nextFloat() - 0.5f) * 0.015f
|
||||
event.values[1] += (Random.nextFloat() - 0.5f) * 0.015f
|
||||
event.values[2] += (Random.nextFloat() - 0.5f) * 0.015f
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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()
|
||||
}
|
||||
)
|
||||
} catch (_: Throwable) {}
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,80 @@
|
||||
package com.lzxnone.openloc.hook.ipc
|
||||
|
||||
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
|
||||
import de.robv.android.xposed.XposedBridge
|
||||
|
||||
/**
|
||||
* 跨进程配置拉取与缓存器(运行在目标宿主进程)
|
||||
* 增强版:结合全局内存常驻 + 动态广播秒级同步 + ContentProvider 双重兜底
|
||||
*/
|
||||
object ConfigFetcher {
|
||||
|
||||
private val PROVIDER_URI = Uri.parse(ConfigContract.CONTENT_URI)
|
||||
|
||||
@Volatile
|
||||
private var isReceiverRegistered = false
|
||||
|
||||
@Volatile
|
||||
private var cachedConfig: MockConfig? = null
|
||||
|
||||
@Volatile
|
||||
private var lastFetchTime = 0L
|
||||
|
||||
private const val CACHE_DURATION_MS = 1500L // 缓存 1.5 秒,保证即时性同时兼顾性能
|
||||
private const val CACHE_DURATION_MS = 1500L
|
||||
|
||||
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)
|
||||
|
||||
val now = System.currentTimeMillis()
|
||||
if (!force && cachedConfig != null && (now - lastFetchTime < CACHE_DURATION_MS)) {
|
||||
return cachedConfig!!
|
||||
}
|
||||
|
||||
if (isFetching.get() == true) {
|
||||
return cachedConfig ?: MockConfig()
|
||||
}
|
||||
|
||||
isFetching.set(true)
|
||||
return try {
|
||||
// 优先走 system_server 内存隧道(携带实时推进坐标、speed 与 bearing),失败再回退 ContentProvider
|
||||
fetchFromSystemServer(context, now)?.let { return it }
|
||||
|
||||
val bundle = context.contentResolver.call(
|
||||
PROVIDER_URI,
|
||||
ConfigContract.METHOD_GET_CONFIG,
|
||||
@@ -43,37 +87,144 @@ object ConfigFetcher {
|
||||
val whitelistJson = bundle.getString(ConfigContract.KEY_WHITELIST_APPS, "[]") ?: "[]"
|
||||
val blacklistJson = bundle.getString(ConfigContract.KEY_BLACKLIST_APPS, "[]") ?: "[]"
|
||||
|
||||
val isJitter = bundle.getBoolean(ConfigContract.KEY_ENABLE_JITTER, true)
|
||||
val isGnss = bundle.getBoolean(ConfigContract.KEY_ENABLE_GNSS_SIMULATION, true)
|
||||
val isNetwork = bundle.getBoolean(ConfigContract.KEY_ENABLE_NETWORK_CAMOUFLAGE, true)
|
||||
val isSensor = bundle.getBoolean(ConfigContract.KEY_ENABLE_SENSOR_SIMULATION, true)
|
||||
val isStealth = bundle.getBoolean(ConfigContract.KEY_ENABLE_STEALTH, true)
|
||||
val isDevCamouflage = bundle.getBoolean(ConfigContract.KEY_ENABLE_DEV_CAMOUFLAGE, true)
|
||||
|
||||
val config = MockConfig(
|
||||
isEnabled = bundle.getBoolean(ConfigContract.KEY_ENABLED, false),
|
||||
latitude = bundle.getDouble(ConfigContract.KEY_LATITUDE, 39.908722),
|
||||
longitude = bundle.getDouble(ConfigContract.KEY_LONGITUDE, 116.397496),
|
||||
locationName = bundle.getString(ConfigContract.KEY_LOCATION_NAME, ""),
|
||||
altitude = bundle.getDouble("altitude", GlobalMockMemory.altitude),
|
||||
accuracy = bundle.getFloat("accuracy", GlobalMockMemory.accuracy),
|
||||
bearing = bundle.getFloat("bearing", GlobalMockMemory.bearing),
|
||||
speed = bundle.getFloat("speed", GlobalMockMemory.speed),
|
||||
mode = mode,
|
||||
whitelist = parseSet(whitelistJson),
|
||||
blacklist = parseSet(blacklistJson),
|
||||
isJitterEnabled = isJitter,
|
||||
isGnssSimulationEnabled = isGnss,
|
||||
isNetworkCamouflageEnabled = isNetwork,
|
||||
isSensorSimulationEnabled = isSensor,
|
||||
isStealthEnabled = isStealth,
|
||||
isDevCamouflageEnabled = isDevCamouflage
|
||||
enableSensorSimulation = bundle.getBoolean(ConfigContract.KEY_ENABLE_SENSOR_SIMULATION, true)
|
||||
)
|
||||
cachedConfig = config
|
||||
lastFetchTime = now
|
||||
|
||||
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
|
||||
GlobalMockMemory.altitude = config.altitude
|
||||
GlobalMockMemory.accuracy = config.accuracy
|
||||
GlobalMockMemory.bearing = config.bearing
|
||||
GlobalMockMemory.speed = config.speed
|
||||
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 (t: Throwable) {
|
||||
// 在目标尚未完全就绪或权限受限时的静默容错
|
||||
cachedConfig ?: MockConfig()
|
||||
} catch (_: Throwable) {
|
||||
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) {
|
||||
if (isReceiverRegistered) return
|
||||
try {
|
||||
val filter = IntentFilter("com.lzxnone.openloc.ACTION_SYNC_CONFIG")
|
||||
val receiver = object : BroadcastReceiver() {
|
||||
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) {
|
||||
regCtx.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED)
|
||||
} else {
|
||||
regCtx.registerReceiver(receiver, filter)
|
||||
}
|
||||
isReceiverRegistered = true
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.lzxnone.openloc.hook.model
|
||||
|
||||
import android.location.Location
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
|
||||
/**
|
||||
* 全局内存常驻配置中心(基于 GhostMapX 工业级架构)
|
||||
* 运行在 system_server 与各进程中
|
||||
*/
|
||||
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"
|
||||
const val EXTRA_LONGITUDE = "longitude"
|
||||
const val EXTRA_ALTITUDE = "altitude"
|
||||
const val EXTRA_ACCURACY = "accuracy"
|
||||
const val EXTRA_BEARING = "bearing"
|
||||
const val EXTRA_SPEED = "speed"
|
||||
const val EXTRA_LOCATION_NAME = "location_name"
|
||||
const val EXTRA_MODE = "mode"
|
||||
const val EXTRA_WHITELIST = "whitelist"
|
||||
const val EXTRA_BLACKLIST = "blacklist"
|
||||
const val EXTRA_SENSOR_SIMULATION = "enable_sensor_simulation"
|
||||
const val EXTRA_NOTIFICATION_ENABLED = "enable_notification"
|
||||
const val EXTRA_RUNNING_MODE_ENABLED = "running_mode_enabled"
|
||||
const val EXTRA_JITTER_ENABLED = "enable_jitter"
|
||||
|
||||
@Volatile var isEnabled: Boolean = false
|
||||
@Volatile var latitude: Double = 39.908722
|
||||
@Volatile var longitude: Double = 116.397496
|
||||
@Volatile var altitude: Double = 50.0
|
||||
@Volatile var accuracy: Float = 5.0f
|
||||
@Volatile var bearing: Float = 0.0f
|
||||
@Volatile var speed: Float = 0.0f
|
||||
@Volatile var mode: String = "GLOBAL"
|
||||
@Volatile var locationName: String = ""
|
||||
@Volatile var whitelist: Set<String> = emptySet()
|
||||
@Volatile var blacklist: Set<String> = emptySet()
|
||||
@Volatile var enableSensorSimulation: Boolean = true
|
||||
@Volatile var enableNotification: Boolean = false
|
||||
@Volatile var runningModeEnabled: Boolean = false
|
||||
@Volatile var enableJitter: Boolean = true
|
||||
|
||||
fun updateFromBundle(bundle: Bundle) {
|
||||
isEnabled = bundle.getBoolean(EXTRA_ENABLED, isEnabled)
|
||||
latitude = bundle.getDouble(EXTRA_LATITUDE, latitude)
|
||||
longitude = bundle.getDouble(EXTRA_LONGITUDE, longitude)
|
||||
altitude = bundle.getDouble(EXTRA_ALTITUDE, altitude)
|
||||
accuracy = bundle.getFloat(EXTRA_ACCURACY, accuracy)
|
||||
bearing = bundle.getFloat(EXTRA_BEARING, bearing)
|
||||
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)
|
||||
enableNotification = bundle.getBoolean(EXTRA_NOTIFICATION_ENABLED, enableNotification)
|
||||
runningModeEnabled = bundle.getBoolean(EXTRA_RUNNING_MODE_ENABLED, runningModeEnabled)
|
||||
enableJitter = bundle.getBoolean(EXTRA_JITTER_ENABLED, enableJitter)
|
||||
|
||||
val whiteListArray = bundle.getStringArrayList(EXTRA_WHITELIST)
|
||||
if (whiteListArray != null) {
|
||||
whitelist = whiteListArray.toSet()
|
||||
}
|
||||
|
||||
val blackListArray = bundle.getStringArrayList(EXTRA_BLACKLIST)
|
||||
if (blackListArray != null) {
|
||||
blacklist = blackListArray.toSet()
|
||||
}
|
||||
}
|
||||
|
||||
fun toBundle(): Bundle {
|
||||
return Bundle().apply {
|
||||
putBoolean(EXTRA_ENABLED, isEnabled)
|
||||
putDouble(EXTRA_LATITUDE, latitude)
|
||||
putDouble(EXTRA_LONGITUDE, longitude)
|
||||
putDouble(EXTRA_ALTITUDE, altitude)
|
||||
putFloat(EXTRA_ACCURACY, accuracy)
|
||||
putFloat(EXTRA_BEARING, bearing)
|
||||
putFloat(EXTRA_SPEED, speed)
|
||||
putString(EXTRA_MODE, mode)
|
||||
putString(EXTRA_LOCATION_NAME, locationName)
|
||||
putBoolean(EXTRA_SENSOR_SIMULATION, enableSensorSimulation)
|
||||
putBoolean(EXTRA_NOTIFICATION_ENABLED, enableNotification)
|
||||
putBoolean(EXTRA_RUNNING_MODE_ENABLED, runningModeEnabled)
|
||||
putBoolean(EXTRA_JITTER_ENABLED, enableJitter)
|
||||
putStringArrayList(EXTRA_WHITELIST, ArrayList(whitelist))
|
||||
putStringArrayList(EXTRA_BLACKLIST, ArrayList(blacklist))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定指定包名是否应被模拟
|
||||
* 严格豁免 OpenLoc 自身包名,以及系统服务与硬件 HAL 客户端,确保硬件底层不受任何污染
|
||||
*/
|
||||
fun shouldMock(packageName: String?): Boolean {
|
||||
if (!isEnabled) return false
|
||||
if (packageName.isNullOrBlank()) return false
|
||||
if (packageName == "com.lzxnone.openloc" || packageName == "android") return false
|
||||
|
||||
// 核心安全红线:系统底层服务、硬件芯片 HAL、系统级定位 Provider 绝不 Mock,避免底层硬件与网络参考点被篡改
|
||||
if (packageName.startsWith("com.android.server.") ||
|
||||
packageName.startsWith("android.") ||
|
||||
packageName.startsWith("com.qualcomm.") ||
|
||||
packageName.startsWith("com.qti.") ||
|
||||
packageName == "com.xiaomi.metoknlp" ||
|
||||
packageName == "com.xiaomi.location.fused" ||
|
||||
packageName.contains(".hal.") ||
|
||||
packageName.contains("Gpo4Client")) {
|
||||
return false
|
||||
}
|
||||
|
||||
return when (mode.uppercase()) {
|
||||
"WHITELIST" -> whitelist.contains(packageName)
|
||||
"BLACKLIST" -> !blacklist.contains(packageName)
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成标准可用的 Mock Location 对象
|
||||
*/
|
||||
fun createLocation(provider: String = "gps"): Location {
|
||||
val currentSpeed = this@GlobalMockMemory.speed
|
||||
val hasValidBearing = currentSpeed > 0.1f
|
||||
return Location(provider).apply {
|
||||
latitude = this@GlobalMockMemory.latitude
|
||||
longitude = this@GlobalMockMemory.longitude
|
||||
altitude = this@GlobalMockMemory.altitude
|
||||
accuracy = this@GlobalMockMemory.accuracy
|
||||
speed = currentSpeed
|
||||
if (hasValidBearing) {
|
||||
bearing = this@GlobalMockMemory.bearing
|
||||
}
|
||||
time = System.currentTimeMillis()
|
||||
elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
|
||||
|
||||
// 补充 GNSS 卫星定位精度属性(Android 8.0+)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
verticalAccuracyMeters = 1.5f
|
||||
speedAccuracyMetersPerSecond = 0.1f
|
||||
if (hasValidBearing) {
|
||||
bearingAccuracyDegrees = 1.0f
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,36 @@
|
||||
package com.lzxnone.openloc.hook.model
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* 虚拟定位配置实体
|
||||
*/
|
||||
data class MockConfig(
|
||||
val isEnabled: Boolean = false,
|
||||
val latitude: Double = 39.908722,
|
||||
val longitude: Double = 116.397496,
|
||||
val locationName: String = "",
|
||||
val altitude: Double = 50.0,
|
||||
val accuracy: Float = 5.0f,
|
||||
val bearing: Float = 0.0f,
|
||||
val speed: Float = 0.0f,
|
||||
val mode: String = "GLOBAL",
|
||||
val whitelist: Set<String> = emptySet(),
|
||||
val blacklist: Set<String> = emptySet(),
|
||||
val isJitterEnabled: Boolean = true,
|
||||
val isGnssSimulationEnabled: Boolean = true,
|
||||
val isNetworkCamouflageEnabled: Boolean = true,
|
||||
val isSensorSimulationEnabled: Boolean = true,
|
||||
val isStealthEnabled: Boolean = true,
|
||||
val isDevCamouflageEnabled: Boolean = true
|
||||
val enableSensorSimulation: Boolean = true
|
||||
) {
|
||||
/**
|
||||
* 判断指定应用包名是否应当生效虚拟定位
|
||||
*/
|
||||
fun shouldMock(packageName: String): Boolean {
|
||||
fun shouldMock(packageName: String?): Boolean {
|
||||
if (!isEnabled) return false
|
||||
return when (mode.uppercase(Locale.ROOT)) {
|
||||
if (packageName.isNullOrBlank()) return true
|
||||
if (packageName == "com.lzxnone.openloc" || packageName == "android") return false
|
||||
if (packageName.startsWith("com.android.server.") ||
|
||||
packageName.startsWith("android.") ||
|
||||
packageName.startsWith("com.qualcomm.") ||
|
||||
packageName.startsWith("com.qti.") ||
|
||||
packageName == "com.xiaomi.metoknlp" ||
|
||||
packageName == "com.xiaomi.location.fused" ||
|
||||
packageName.contains(".hal.") ||
|
||||
packageName.contains("Gpo4Client")) {
|
||||
return false
|
||||
}
|
||||
return when (mode.uppercase()) {
|
||||
"WHITELIST" -> whitelist.contains(packageName)
|
||||
"BLACKLIST" -> !blacklist.contains(packageName)
|
||||
else -> true // "GLOBAL"
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,141 @@
|
||||
package com.lzxnone.openloc.hook.system
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.os.Binder
|
||||
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
|
||||
|
||||
/**
|
||||
* 电话服务与基站注册核心拦截器(针对 com.android.phone)
|
||||
* 核心目标:
|
||||
* 阻断目标第三方应用获取真实物理基站塔数据 (MCC, MNC, LAC, CID),
|
||||
* 同时绝对放行系统核心服务与底层网络定位提供商,保证物理网络定位解算正常运作。
|
||||
*/
|
||||
object TelephonyRegistryHook {
|
||||
|
||||
@Volatile
|
||||
private var phoneContext: Context? = null
|
||||
|
||||
fun hook(classLoader: ClassLoader) {
|
||||
XposedBridge.log("[OpenLoc] Attaching TelephonyRegistryHook for com.android.phone...")
|
||||
|
||||
try {
|
||||
XposedHelpers.findAndHookMethod(
|
||||
Application::class.java,
|
||||
"attach",
|
||||
Context::class.java,
|
||||
object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (phoneContext == null) {
|
||||
phoneContext = param.args[0] as? Context
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (_: Throwable) {}
|
||||
|
||||
hookPhoneInterfaceManager(classLoader)
|
||||
}
|
||||
|
||||
private fun hookPhoneInterfaceManager(classLoader: ClassLoader) {
|
||||
val managerClass = try {
|
||||
XposedHelpers.findClass("com.android.phone.PhoneInterfaceManager", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: return
|
||||
|
||||
XposedBridge.log("[OpenLoc] Found PhoneInterfaceManager, hooking cell location APIs...")
|
||||
|
||||
for (method in managerClass.declaredMethods) {
|
||||
when (method.name) {
|
||||
"getAllCellInfo" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (shouldBlock(param)) {
|
||||
param.result = emptyList<Any>()
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getCellLocation" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (shouldBlock(param)) {
|
||||
param.result = null
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"getNeighboringCellInfo" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (shouldBlock(param)) {
|
||||
param.result = emptyList<Any>()
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"requestCellInfoUpdate", "requestCellInfoUpdateWithWorkSource" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (shouldBlock(param)) {
|
||||
param.result = null
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun shouldBlock(param: XC_MethodHook.MethodHookParam): Boolean {
|
||||
if (!GlobalMockMemory.isEnabled) return false
|
||||
val uid = Binder.getCallingUid()
|
||||
// 核心保护:UID<=1000(系统守护进程、系统NLP)绝对放行真实基站数据,确保能解算真实物理网络定位
|
||||
if (uid <= 1000) return false
|
||||
|
||||
val pkg = extractCallingPackage(param, uid)
|
||||
// 仅当明确识别为需要模拟的目标第三方 App 时才阻断基站数据
|
||||
return !pkg.isNullOrBlank() && GlobalMockMemory.shouldMock(pkg)
|
||||
}
|
||||
|
||||
private fun extractCallingPackage(param: XC_MethodHook.MethodHookParam, uid: Int): String? {
|
||||
for (arg in param.args) {
|
||||
if (arg is String && arg.contains(".") && !arg.contains("/")) {
|
||||
if (!arg.startsWith("android.") && !arg.startsWith("com.android.phone.") &&
|
||||
!arg.startsWith("com.android.internal.")) {
|
||||
return arg
|
||||
}
|
||||
}
|
||||
}
|
||||
val ctx = phoneContext
|
||||
if (ctx != null) {
|
||||
try {
|
||||
val packages = ctx.packageManager.getPackagesForUid(uid)
|
||||
val first = packages?.firstOrNull()
|
||||
if (!first.isNullOrBlank()) return first
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
return try {
|
||||
val appGlobalsClass = Class.forName("android.app.AppGlobals")
|
||||
val pm = XposedHelpers.callStaticMethod(appGlobalsClass, "getPackageManager")
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val packages = XposedHelpers.callMethod(pm, "getPackagesForUid", uid) as? Array<String>
|
||||
packages?.firstOrNull()
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package com.lzxnone.openloc.hook.util
|
||||
|
||||
import android.location.Location
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import de.robv.android.xposed.XposedHelpers
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sqrt
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* 虚拟位置模拟生成与洗白工具
|
||||
*/
|
||||
object LocationSimulator {
|
||||
|
||||
@Volatile
|
||||
private var driftOffsetX = 0.0 // meters (East-West)
|
||||
@Volatile
|
||||
private var driftOffsetY = 0.0 // meters (North-South)
|
||||
@Volatile
|
||||
private var lastDriftTime = 0L
|
||||
@Volatile
|
||||
private var currentBearing = 0.0f
|
||||
@Volatile
|
||||
private var currentSpeed = 0.0f
|
||||
|
||||
/**
|
||||
* 计算并获取经过自然微漂移(平滑布朗运动)后的实时坐标
|
||||
*/
|
||||
@Synchronized
|
||||
fun getSimulatedCoordinates(
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
isJitterEnabled: Boolean
|
||||
): Pair<Double, Double> {
|
||||
if (!isJitterEnabled) {
|
||||
return Pair(latitude, longitude)
|
||||
}
|
||||
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val dt = if (lastDriftTime == 0L) 1.0 else ((now - lastDriftTime).coerceIn(100L, 5000L) / 1000.0)
|
||||
lastDriftTime = now
|
||||
|
||||
// 随机步长(随时间平滑积累,约每秒 0.15~0.3m)
|
||||
val stepStdDev = 0.20 * sqrt(dt)
|
||||
val dX = (Random.nextDouble() - 0.5) * 2.0 * stepStdDev
|
||||
val dY = (Random.nextDouble() - 0.5) * 2.0 * stepStdDev
|
||||
|
||||
// 类似弹簧向中心回拉,确保长期稳定在一个极小的真实扰动圆圈内(半径约 1.5 米以内)
|
||||
val springFactor = 0.08 * dt
|
||||
driftOffsetX = (driftOffsetX + dX) * (1.0 - springFactor)
|
||||
driftOffsetY = (driftOffsetY + dY) * (1.0 - springFactor)
|
||||
|
||||
val dist = sqrt(driftOffsetX * driftOffsetX + driftOffsetY * driftOffsetY)
|
||||
val maxRadius = 1.8 // 最大漂移半径 1.8 米
|
||||
if (dist > maxRadius) {
|
||||
driftOffsetX = (driftOffsetX / dist) * maxRadius
|
||||
driftOffsetY = (driftOffsetY / dist) * maxRadius
|
||||
}
|
||||
|
||||
// 米转换为纬度与经度增量
|
||||
val metersPerLatDegree = 111132.92
|
||||
val latRad = Math.toRadians(latitude)
|
||||
val metersPerLngDegree = (111412.84 * cos(latRad)).coerceAtLeast(1.0)
|
||||
|
||||
val finalLat = latitude + (driftOffsetY / metersPerLatDegree)
|
||||
val finalLng = longitude + (driftOffsetX / metersPerLngDegree)
|
||||
|
||||
// 计算微弱的自然速度和方向
|
||||
currentSpeed = (dist * 0.04 + Random.nextDouble(0.01, 0.06)).toFloat()
|
||||
if (dist > 0.15) {
|
||||
currentBearing = ((Math.toDegrees(atan2(driftOffsetX, driftOffsetY)) + 360) % 360).toFloat()
|
||||
}
|
||||
|
||||
return Pair(finalLat, finalLng)
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成一个全新且各项指标逼真的 Location 实例
|
||||
*/
|
||||
fun createMockLocation(
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
provider: String = LocationManager.GPS_PROVIDER,
|
||||
isJitterEnabled: Boolean = true
|
||||
): Location {
|
||||
return Location(provider).apply {
|
||||
applyMockData(this, latitude, longitude, isJitterEnabled)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将虚拟数据注入到现有的 Location 实例中,并彻底抹除 Mock 标志
|
||||
*/
|
||||
fun applyMockData(
|
||||
location: Location,
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
isJitterEnabled: Boolean = true
|
||||
) {
|
||||
val (finalLat, finalLng) = getSimulatedCoordinates(latitude, longitude, isJitterEnabled)
|
||||
val dist = sqrt(driftOffsetX * driftOffsetX + driftOffsetY * driftOffsetY)
|
||||
|
||||
location.latitude = finalLat
|
||||
location.longitude = finalLng
|
||||
location.altitude = if (isJitterEnabled) {
|
||||
25.0 + (driftOffsetY * 0.1) + Random.nextDouble(-0.3, 0.3)
|
||||
} else {
|
||||
25.0
|
||||
}
|
||||
location.accuracy = if (isJitterEnabled) {
|
||||
3.5f + (dist * 0.6f).toFloat() + Random.nextFloat() * 0.5f // 3.5m ~ 5.5m 真实波动
|
||||
} else {
|
||||
3.5f
|
||||
}
|
||||
location.speed = if (isJitterEnabled) currentSpeed else 0.0f
|
||||
location.bearing = if (isJitterEnabled) currentBearing else 0.0f
|
||||
location.time = System.currentTimeMillis()
|
||||
location.elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
|
||||
|
||||
// 彻底洗白:抹除系统自带的 isFromMockProvider 标志
|
||||
stripMockFlags(location)
|
||||
}
|
||||
|
||||
/**
|
||||
* 抹除 Location 对象上的所有模拟位置痕迹
|
||||
*/
|
||||
fun stripMockFlags(location: Location) {
|
||||
try {
|
||||
// Android 12 (API 31)+ 官方新增属性
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
location.isMock = false
|
||||
}
|
||||
|
||||
// 针对各版本 Android 内部 mIsFromMockProvider 字段反射清洗
|
||||
try {
|
||||
XposedHelpers.setBooleanField(location, "mIsFromMockProvider", false)
|
||||
} catch (_: Throwable) {}
|
||||
|
||||
try {
|
||||
XposedHelpers.callMethod(location, "setIsFromMockProvider", false)
|
||||
} catch (_: Throwable) {}
|
||||
|
||||
// Android 9+ (API 28)+ 内部的 mFieldsMask 标志位清洗
|
||||
try {
|
||||
val fieldsMask = XposedHelpers.getIntField(location, "mFieldsMask")
|
||||
// 清除 HAS_MOCK_PROVIDER 标志位 (通常是 0x10 或类似)
|
||||
XposedHelpers.setIntField(location, "mFieldsMask", fieldsMask and 0x10.inv())
|
||||
} catch (_: Throwable) {}
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
package com.lzxnone.openloc.hook.util
|
||||
|
||||
import android.location.GnssStatus
|
||||
import android.os.Build
|
||||
import de.robv.android.xposed.XposedHelpers
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.TimeZone
|
||||
import kotlin.math.sin
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* 全真多星座 GNSS 虚拟卫星仿真引擎
|
||||
*
|
||||
* 1. 提供覆盖全球及中国主流芯片的多星座卫星池(GPS、北斗、GLONASS、Galileo,共 26 颗)
|
||||
* 2. 依据仰角几何球坐标动态生成符合物理传输衰减的载噪比 (C/N0, 18~42 dB-Hz) 与时变微弱抖动
|
||||
* 3. 动态构建原生系统级 GnssStatus 实例(支持 Android 11+ Builder 与反射双重兜底)
|
||||
* 4. 动态生成工业标准的 NMEA-0183 报文阵列($GNGGA, $GNRMC, $GNGSA, $BDGSA, $GPGSV, $BDGSV, $GLGSV)
|
||||
*/
|
||||
object VirtualGnssEngine {
|
||||
|
||||
data class VirtualSatellite(
|
||||
val constellationType: Int,
|
||||
val svid: Int,
|
||||
val elevation: Float,
|
||||
val azimuth: Float,
|
||||
val carrierFrequencyHz: Float,
|
||||
val usedInFix: Boolean
|
||||
)
|
||||
|
||||
// 预设全真多星座卫星池(分布在 0~360° 方位角与 10~85° 仰角的完整半球星空)
|
||||
private val SATELLITE_POOL = listOf(
|
||||
// GPS (Constellation 1) - 8 颗,6 颗参与 Fix
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 3, 68f, 120f, 1575420000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 7, 42f, 280f, 1575420000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 14, 81f, 45f, 1575420000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 16, 25f, 190f, 1575420000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 22, 14f, 330f, 1575420000f, false),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 27, 53f, 85f, 1575420000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 30, 32f, 240f, 1575420000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 31, 11f, 15f, 1575420000f, false),
|
||||
|
||||
// BDS 北斗 (Constellation 5) - 10 颗,8 颗参与 Fix (国内核心主力)
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 1, 40f, 140f, 1561098000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 6, 75f, 210f, 1561098000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 9, 58f, 60f, 1561098000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 13, 84f, 175f, 1561098000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 19, 30f, 310f, 1561098000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 21, 49f, 15f, 1561098000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 26, 63f, 105f, 1561098000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 33, 22f, 265f, 1561098000f, false),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 35, 37f, 195f, 1561098000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 37, 12f, 80f, 1561098000f, false),
|
||||
|
||||
// GLONASS (Constellation 3) - 5 颗,4 颗参与 Fix
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 66, 55f, 350f, 1602000000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 71, 70f, 135f, 1602000000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 74, 38f, 225f, 1602000000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 82, 18f, 95f, 1602000000f, false),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 88, 28f, 170f, 1602000000f, true),
|
||||
|
||||
// GALILEO (Constellation 6) - 3 颗,2 颗参与 Fix
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GALILEO, 4, 64f, 290f, 1575420000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GALILEO, 12, 45f, 50f, 1575420000f, true),
|
||||
VirtualSatellite(GnssStatus.CONSTELLATION_GALILEO, 19, 15f, 160f, 1575420000f, false)
|
||||
)
|
||||
|
||||
private val timeFormat = SimpleDateFormat("HHmmss.SS", Locale.US).apply {
|
||||
timeZone = TimeZone.getTimeZone("UTC")
|
||||
}
|
||||
private val dateFormat = SimpleDateFormat("ddMMyy", Locale.US).apply {
|
||||
timeZone = TimeZone.getTimeZone("UTC")
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据仰角计算符合真实物理衰减的 C/N0 载噪比(单位 dB-Hz)
|
||||
*/
|
||||
fun computeCn0(sat: VirtualSatellite): Float {
|
||||
val elevRad = Math.toRadians(sat.elevation.toDouble())
|
||||
val baseCn0 = 18.0 + 23.0 * sin(elevRad)
|
||||
val noise = (Random.nextDouble() - 0.5) * 1.5
|
||||
return (baseCn0 + noise).coerceIn(16.0, 42.5).toFloat()
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建或获取原生系统的 GnssStatus 实例
|
||||
*/
|
||||
fun createGnssStatus(): GnssStatus? {
|
||||
// 优先使用 Android 11+ (API 30+) 官方提供的 GnssStatus.Builder
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
try {
|
||||
val builder = GnssStatus.Builder()
|
||||
val addSatelliteMethod = builder.javaClass.methods.firstOrNull { it.name == "addSatellite" }
|
||||
if (addSatelliteMethod != null) {
|
||||
val paramCount = addSatelliteMethod.parameterTypes.size
|
||||
for (sat in SATELLITE_POOL) {
|
||||
val cn0 = computeCn0(sat)
|
||||
if (paramCount >= 12) {
|
||||
addSatelliteMethod.invoke(
|
||||
builder,
|
||||
sat.constellationType,
|
||||
sat.svid,
|
||||
cn0,
|
||||
sat.elevation,
|
||||
sat.azimuth,
|
||||
true, // hasEphemeris
|
||||
true, // hasAlmanac
|
||||
sat.usedInFix,
|
||||
true, // hasCarrierFrequency
|
||||
sat.carrierFrequencyHz,
|
||||
true, // hasBasebandCn0
|
||||
(cn0 - 2.0f).coerceAtLeast(10.0f) // basebandCn0
|
||||
)
|
||||
} else {
|
||||
addSatelliteMethod.invoke(
|
||||
builder,
|
||||
sat.constellationType,
|
||||
sat.svid,
|
||||
cn0,
|
||||
sat.elevation,
|
||||
sat.azimuth,
|
||||
true, // hasEphemeris
|
||||
true, // hasAlmanac
|
||||
sat.usedInFix,
|
||||
true, // hasCarrierFrequency
|
||||
sat.carrierFrequencyHz
|
||||
)
|
||||
}
|
||||
}
|
||||
return builder.build()
|
||||
}
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
// 低版本反射兜底(构造私有构造器)
|
||||
return try {
|
||||
val count = SATELLITE_POOL.size
|
||||
val svidWithFlags = IntArray(count)
|
||||
val cn0s = FloatArray(count)
|
||||
val elevations = FloatArray(count)
|
||||
val azimuths = FloatArray(count)
|
||||
val carrierFreqs = FloatArray(count)
|
||||
|
||||
for (i in 0 until count) {
|
||||
val sat = SATELLITE_POOL[i]
|
||||
// 编码 svidWithFlags (AOSP 规范)
|
||||
var flags = (sat.constellationType and 0x0F) shl 4
|
||||
flags = flags or (sat.svid shl 8)
|
||||
flags = flags or 1 // hasEphemeris
|
||||
flags = flags or 2 // hasAlmanac
|
||||
if (sat.usedInFix) flags = flags or 4
|
||||
flags = flags or 8 // hasCarrierFrequency
|
||||
|
||||
svidWithFlags[i] = flags
|
||||
cn0s[i] = computeCn0(sat)
|
||||
elevations[i] = sat.elevation
|
||||
azimuths[i] = sat.azimuth
|
||||
carrierFreqs[i] = sat.carrierFrequencyHz
|
||||
}
|
||||
|
||||
try {
|
||||
// Android 10+ 构造函数含 carrierFrequencies
|
||||
XposedHelpers.newInstance(
|
||||
GnssStatus::class.java,
|
||||
count,
|
||||
svidWithFlags,
|
||||
cn0s,
|
||||
elevations,
|
||||
azimuths,
|
||||
carrierFreqs
|
||||
) as? GnssStatus
|
||||
} catch (_: Throwable) {
|
||||
// Android 7~9 构造函数 5 参数
|
||||
XposedHelpers.newInstance(
|
||||
GnssStatus::class.java,
|
||||
count,
|
||||
svidWithFlags,
|
||||
cn0s,
|
||||
elevations,
|
||||
azimuths
|
||||
) as? GnssStatus
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成全套完整的工业级 NMEA-0183 报文序列(包含 GGA, RMC, GSA, GSV 多星座信标)
|
||||
*/
|
||||
fun generateFullNmeaSequence(lat: Double, lng: Double, time: Long): List<String> {
|
||||
val result = mutableListOf<String>()
|
||||
val utcTime = timeFormat.format(Date(time))
|
||||
val dateStr = dateFormat.format(Date(time))
|
||||
val latStr = formatToNmeaCoord(lat, true)
|
||||
val lngStr = formatToNmeaCoord(lng, false)
|
||||
|
||||
val totalUsedSats = SATELLITE_POOL.count { it.usedInFix }
|
||||
|
||||
// 1. $GNGGA 定位解数据
|
||||
val ggaContent = "GNGGA,$utcTime,$latStr,$lngStr,1,$totalUsedSats,0.8,25.0,M,0.0,M,,"
|
||||
result.add("\$$ggaContent*${calculateChecksum(ggaContent)}\r\n")
|
||||
|
||||
// 2. $GNRMC 推荐最小导航数据
|
||||
val rmcContent = "GNRMC,$utcTime,A,$latStr,$lngStr,0.0,0.0,$dateStr,,,A"
|
||||
result.add("\$$rmcContent*${calculateChecksum(rmcContent)}\r\n")
|
||||
|
||||
// 3. $GNGSA (GPS 精度因子与解算卫星)
|
||||
val gpsUsedSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_GPS && it.usedInFix }
|
||||
val gpsPrnSlots = (0 until 12).map { index ->
|
||||
if (index < gpsUsedSats.size) String.format(Locale.US, "%02d", gpsUsedSats[index].svid) else ""
|
||||
}.joinToString(",")
|
||||
val gsaGpsContent = "GNGSA,A,3,$gpsPrnSlots,1.2,0.8,0.9,1"
|
||||
result.add("\$$gsaGpsContent*${calculateChecksum(gsaGpsContent)}\r\n")
|
||||
|
||||
// 4. $BDGSA (北斗精度因子与解算卫星)
|
||||
val bdsUsedSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_BEIDOU && it.usedInFix }
|
||||
val bdsPrnSlots = (0 until 12).map { index ->
|
||||
if (index < bdsUsedSats.size) String.format(Locale.US, "%02d", bdsUsedSats[index].svid) else ""
|
||||
}.joinToString(",")
|
||||
val gsaBdsContent = "BDGSA,A,3,$bdsPrnSlots,1.2,0.8,0.9,4"
|
||||
result.add("\$$gsaBdsContent*${calculateChecksum(gsaBdsContent)}\r\n")
|
||||
|
||||
// 5. $GPGSV (GPS 可见卫星星标,每页至多 4 颗)
|
||||
val gpsSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_GPS }
|
||||
appendGsvSentences("GPGSV", gpsSats, result)
|
||||
|
||||
// 6. $BDGSV (北斗可见卫星星标,每页至多 4 颗)
|
||||
val bdsSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_BEIDOU }
|
||||
appendGsvSentences("BDGSV", bdsSats, result)
|
||||
|
||||
// 7. $GLGSV (GLONASS 可见卫星星标,每页至多 4 颗)
|
||||
val gloSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_GLONASS }
|
||||
appendGsvSentences("GLGSV", gloSats, result)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
private fun appendGsvSentences(talker: String, sats: List<VirtualSatellite>, target: MutableList<String>) {
|
||||
val totalSats = sats.size
|
||||
val totalPages = (totalSats + 3) / 4
|
||||
for (page in 1..totalPages) {
|
||||
val chunk = sats.drop((page - 1) * 4).take(4)
|
||||
val sb = java.lang.StringBuilder("$talker,$totalPages,$page,$totalSats")
|
||||
for (s in chunk) {
|
||||
val cn0 = computeCn0(s).toInt()
|
||||
sb.append(String.format(Locale.US, ",%02d,%02d,%03d,%02d", s.svid, s.elevation.toInt(), s.azimuth.toInt(), cn0))
|
||||
}
|
||||
sb.append(",1") // 信号 ID (L1/B1)
|
||||
val content = sb.toString()
|
||||
target.add("\$$content*${calculateChecksum(content)}\r\n")
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatToNmeaCoord(coord: Double, isLat: Boolean): String {
|
||||
val abs = Math.abs(coord)
|
||||
val degrees = abs.toInt()
|
||||
val minutes = (abs - degrees) * 60.0
|
||||
val direction = if (isLat) {
|
||||
if (coord >= 0) "N" else "S"
|
||||
} else {
|
||||
if (coord >= 0) "E" else "W"
|
||||
}
|
||||
val coordFormat = if (isLat) "%02d%07.4f" else "%03d%07.4f"
|
||||
return String.format(Locale.US, "$coordFormat,$direction", degrees, minutes)
|
||||
}
|
||||
|
||||
private fun calculateChecksum(sentence: String): String {
|
||||
var sum = 0
|
||||
for (ch in sentence) {
|
||||
sum = sum xor ch.code
|
||||
}
|
||||
return String.format(Locale.US, "%02X", sum)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package com.lzxnone.openloc.ui.components
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
@@ -18,6 +22,8 @@ import com.lzxnone.openloc.R
|
||||
@Composable
|
||||
fun OpenLocTopBar(
|
||||
title: String = stringResource(id = R.string.app_name),
|
||||
onAboutClick: () -> Unit = {},
|
||||
showAboutAction: Boolean = true,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
TopAppBar(
|
||||
@@ -29,6 +35,17 @@ fun OpenLocTopBar(
|
||||
)
|
||||
)
|
||||
},
|
||||
actions = {
|
||||
if (showAboutAction) {
|
||||
IconButton(onClick = onAboutClick) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Info,
|
||||
contentDescription = stringResource(id = R.string.section_about),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
colors = TopAppBarDefaults.topAppBarColors(
|
||||
containerColor = MaterialTheme.colorScheme.background,
|
||||
titleContentColor = MaterialTheme.colorScheme.onBackground
|
||||
|
||||
@@ -4,18 +4,13 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.NewReleases
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
@@ -34,27 +29,25 @@ import com.lzxnone.openloc.core.util.UpdateInfo
|
||||
@Composable
|
||||
fun UpdateDialog(
|
||||
updateInfo: UpdateInfo,
|
||||
onDismiss: () -> Unit
|
||||
onDismiss: () -> Unit,
|
||||
onDontShowAgain: (Long) -> Unit = {}
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scrollState = rememberScrollState()
|
||||
|
||||
val displayVersion = if (updateInfo.versionName.startsWith("v", ignoreCase = true)) {
|
||||
"V" + updateInfo.versionName.substring(1)
|
||||
} else {
|
||||
"V${updateInfo.versionName}"
|
||||
}
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.NewReleases,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(32.dp)
|
||||
)
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
text = stringResource(id = R.string.home_update_available_title, updateInfo.latestVersion),
|
||||
style = MaterialTheme.typography.titleLarge.copy(
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
text = stringResource(id = R.string.update_dialog_title_format, displayVersion),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
},
|
||||
text = {
|
||||
@@ -64,57 +57,47 @@ fun UpdateDialog(
|
||||
.heightIn(max = 280.dp)
|
||||
.verticalScroll(scrollState)
|
||||
) {
|
||||
if (updateInfo.releaseTitle.isNotBlank() && updateInfo.releaseTitle != updateInfo.latestVersion) {
|
||||
Text(
|
||||
text = updateInfo.releaseTitle,
|
||||
style = MaterialTheme.typography.titleMedium.copy(
|
||||
fontWeight = FontWeight.SemiBold
|
||||
),
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
if (updateInfo.changelog.isNotBlank()) {
|
||||
Text(
|
||||
text = updateInfo.changelog,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
text = stringResource(id = R.string.home_update_dialog_msg),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = updateInfo.changelog,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = {
|
||||
openBrowser(context, updateInfo.releaseUrl)
|
||||
openBrowser(context, updateInfo.downloadUrl)
|
||||
onDismiss()
|
||||
}
|
||||
) {
|
||||
Text(text = stringResource(id = R.string.home_update_btn_go))
|
||||
Text(text = stringResource(id = R.string.btn_download_update))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text(text = stringResource(id = R.string.home_update_btn_later))
|
||||
Row {
|
||||
TextButton(
|
||||
onClick = {
|
||||
onDontShowAgain(updateInfo.versionCode)
|
||||
onDismiss()
|
||||
}
|
||||
) {
|
||||
Text(text = stringResource(id = R.string.btn_dont_show_again))
|
||||
}
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text(text = stringResource(id = R.string.action_cancel))
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private fun openBrowser(context: Context, url: String) {
|
||||
try {
|
||||
val targetUri = Uri.parse(url.ifBlank { "https://github.com/lzxnone/openloc/releases" })
|
||||
val intent = Intent(Intent.ACTION_VIEW, targetUri).apply {
|
||||
if (url.isBlank()) return
|
||||
runCatching {
|
||||
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
context.startActivity(intent)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
@@ -1,49 +1,66 @@
|
||||
package com.lzxnone.openloc.ui.screens
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.lzxnone.openloc.core.util.HookStatus
|
||||
import com.lzxnone.openloc.data.preference.AppPreferences
|
||||
import com.lzxnone.openloc.ui.components.OpenLocBottomBar
|
||||
import com.lzxnone.openloc.ui.components.OpenLocTopBar
|
||||
import com.lzxnone.openloc.ui.navigation.NavTab
|
||||
import com.lzxnone.openloc.ui.screens.home.HomeScreen
|
||||
import com.lzxnone.openloc.ui.screens.location.LocationScreen
|
||||
import com.lzxnone.openloc.ui.screens.settings.SettingsScreen
|
||||
|
||||
import android.widget.Toast
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.lzxnone.openloc.BuildConfig
|
||||
import com.lzxnone.openloc.R
|
||||
import com.lzxnone.openloc.core.util.HookStatus
|
||||
import com.lzxnone.openloc.core.util.UpdateChecker
|
||||
import com.lzxnone.openloc.core.util.UpdateInfo
|
||||
import com.lzxnone.openloc.data.preference.AppMockMode
|
||||
import com.lzxnone.openloc.data.preference.AppPreferences
|
||||
import com.lzxnone.openloc.ui.components.OpenLocBottomBar
|
||||
import com.lzxnone.openloc.ui.components.OpenLocTopBar
|
||||
import com.lzxnone.openloc.ui.components.UpdateDialog
|
||||
import com.lzxnone.openloc.ui.navigation.NavTab
|
||||
import com.lzxnone.openloc.ui.screens.about.AboutScreen
|
||||
import com.lzxnone.openloc.ui.screens.apps.AppSelectionScreen
|
||||
import com.lzxnone.openloc.ui.screens.home.HomeScreen
|
||||
import com.lzxnone.openloc.ui.screens.location.LocationScreen
|
||||
import com.lzxnone.openloc.ui.screens.settings.SettingsScreen
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* 根容器页面:承载 TopAppBar、底部导航栏与各个 Tab 内容切换
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun MainScreen(
|
||||
modifier: Modifier = Modifier
|
||||
@@ -52,33 +69,62 @@ fun MainScreen(
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
|
||||
var currentTab by rememberSaveable { mutableStateOf(NavTab.HOME) }
|
||||
var isAboutViewOpen by rememberSaveable { mutableStateOf(false) }
|
||||
var activeAppSelectionMode by rememberSaveable { mutableStateOf<AppMockMode?>(null) }
|
||||
var updateInfoToDisplay by remember { mutableStateOf<UpdateInfo?>(null) }
|
||||
var isCheckingAppUpdate by remember { mutableStateOf(false) }
|
||||
|
||||
// 响应式的总开关状态与激活状态
|
||||
val isServiceEnabled = AppPreferences.isServiceEnabled
|
||||
val isModuleActive = remember { HookStatus.isModuleActive() }
|
||||
|
||||
// 每次进入软件,若开启了自动检查更新,则在后台静默检测,发现新版才弹窗
|
||||
// 自动权限申请:进入软件时,若没有定位权限,主动向用户申请
|
||||
val locationPermissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestMultiplePermissions()
|
||||
) { _ ->
|
||||
// 权限回调处理
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
val hasFine = ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
val hasCoarse = ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
if (!hasFine && !hasCoarse) {
|
||||
locationPermissionLauncher.launch(
|
||||
arrayOf(
|
||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 每次进入软件,若开启了自动检查更新,则在后台静默检测,发现新版且未被抑制才弹窗
|
||||
LaunchedEffect(Unit) {
|
||||
if (AppPreferences.isAutoCheckUpdateEnabled) {
|
||||
val result = UpdateChecker.checkUpdate(currentVersion = "v1.0.0")
|
||||
val result = UpdateChecker.checkUpdate()
|
||||
result.getOrNull()?.let { info ->
|
||||
if (info.hasUpdate) {
|
||||
if (info.hasUpdate && info.versionCode > AppPreferences.suppressedUpdateVersionCode) {
|
||||
updateInfoToDisplay = info
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val checkingUpdateText = stringResource(id = R.string.home_checking_update)
|
||||
val checkFailedText = stringResource(id = R.string.home_check_update_failed)
|
||||
val alreadyLatestText = stringResource(id = R.string.home_already_latest, "v1.0.0")
|
||||
val alreadyLatestText = stringResource(id = R.string.about_latest_version)
|
||||
|
||||
val performManualCheck: () -> Unit = {
|
||||
Toast.makeText(context, checkingUpdateText, Toast.LENGTH_SHORT).show()
|
||||
isCheckingAppUpdate = true
|
||||
coroutineScope.launch {
|
||||
val result = UpdateChecker.checkUpdate(currentVersion = "v1.0.0")
|
||||
val result = UpdateChecker.checkUpdate()
|
||||
isCheckingAppUpdate = false
|
||||
result.onSuccess { info ->
|
||||
if (info.hasUpdate) {
|
||||
updateInfoToDisplay = info
|
||||
@@ -91,69 +137,149 @@ fun MainScreen(
|
||||
}
|
||||
}
|
||||
|
||||
Box(modifier = modifier.fillMaxSize()) {
|
||||
if (isAboutViewOpen) {
|
||||
BackHandler {
|
||||
isAboutViewOpen = false
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||
topBar = {
|
||||
if (currentTab != NavTab.LOCATION) {
|
||||
OpenLocTopBar()
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
OpenLocBottomBar(
|
||||
currentTab = currentTab,
|
||||
onTabSelected = { currentTab = it }
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { isAboutViewOpen = false }) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = stringResource(R.string.btn_back)
|
||||
)
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
text = stringResource(R.string.section_about),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
},
|
||||
colors = TopAppBarDefaults.topAppBarColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
titleContentColor = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
)
|
||||
}
|
||||
) { innerPadding ->
|
||||
AnimatedContent(
|
||||
targetState = currentTab,
|
||||
transitionSpec = {
|
||||
fadeIn() togetherWith fadeOut()
|
||||
},
|
||||
label = "TabContentAnimation",
|
||||
AboutScreen(
|
||||
onCheckAppUpdate = performManualCheck,
|
||||
isCheckingUpdate = isCheckingAppUpdate,
|
||||
modifier = Modifier.padding(innerPadding)
|
||||
) { targetTab ->
|
||||
when (targetTab) {
|
||||
NavTab.HOME -> HomeScreen(
|
||||
isModuleActive = isModuleActive,
|
||||
isServiceEnabled = isServiceEnabled,
|
||||
onServiceEnabledChange = { enabled ->
|
||||
AppPreferences.updateServiceEnabled(enabled)
|
||||
},
|
||||
onOpenBlacklist = { activeAppSelectionMode = AppMockMode.BLACKLIST },
|
||||
onOpenWhitelist = { activeAppSelectionMode = AppMockMode.WHITELIST },
|
||||
onCheckUpdate = performManualCheck
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Box(modifier = modifier.fillMaxSize()) {
|
||||
Scaffold(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||
topBar = {
|
||||
if (currentTab != NavTab.LOCATION) {
|
||||
OpenLocTopBar(
|
||||
onAboutClick = { isAboutViewOpen = true }
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
OpenLocBottomBar(
|
||||
currentTab = currentTab,
|
||||
onTabSelected = { currentTab = it }
|
||||
)
|
||||
}
|
||||
) { innerPadding ->
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(bottom = innerPadding.calculateBottomPadding())
|
||||
) {
|
||||
// 1. 地图页面:一旦进入后始终常驻保活,切换 Tab 绝不销毁 MapView,零延迟、不重新加载
|
||||
var hasLoadedLocation by rememberSaveable { mutableStateOf(false) }
|
||||
if (currentTab == NavTab.LOCATION) {
|
||||
hasLoadedLocation = true
|
||||
}
|
||||
|
||||
if (hasLoadedLocation) {
|
||||
LocationScreen(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
isVisible = (currentTab == NavTab.LOCATION)
|
||||
)
|
||||
}
|
||||
|
||||
// 2. 首页 (当前 Tab 为 HOME 时展示)
|
||||
AnimatedVisibility(
|
||||
visible = currentTab == NavTab.HOME,
|
||||
enter = fadeIn(),
|
||||
exit = fadeOut(),
|
||||
modifier = Modifier.fillMaxSize()
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = innerPadding.calculateTopPadding()),
|
||||
color = MaterialTheme.colorScheme.background
|
||||
) {
|
||||
HomeScreen(
|
||||
isModuleActive = isModuleActive,
|
||||
isServiceEnabled = isServiceEnabled,
|
||||
onServiceEnabledChange = { enabled ->
|
||||
AppPreferences.updateServiceEnabled(enabled)
|
||||
},
|
||||
onOpenBlacklist = { activeAppSelectionMode = AppMockMode.BLACKLIST },
|
||||
onOpenWhitelist = { activeAppSelectionMode = AppMockMode.WHITELIST }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 设置页 (当前 Tab 为 SETTINGS 时展示)
|
||||
AnimatedVisibility(
|
||||
visible = currentTab == NavTab.SETTINGS,
|
||||
enter = fadeIn(),
|
||||
exit = fadeOut(),
|
||||
modifier = Modifier.fillMaxSize()
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = innerPadding.calculateTopPadding()),
|
||||
color = MaterialTheme.colorScheme.background
|
||||
) {
|
||||
SettingsScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 应用选择全屏浮层(黑名单 / 白名单独立管理)
|
||||
AnimatedVisibility(
|
||||
visible = activeAppSelectionMode != null,
|
||||
enter = slideInHorizontally(initialOffsetX = { it }) + fadeIn(),
|
||||
exit = slideOutHorizontally(targetOffsetX = { it }) + fadeOut(),
|
||||
modifier = Modifier.fillMaxSize()
|
||||
) {
|
||||
activeAppSelectionMode?.let { mode ->
|
||||
AppSelectionScreen(
|
||||
mode = mode,
|
||||
onNavigateBack = { activeAppSelectionMode = null }
|
||||
)
|
||||
NavTab.LOCATION -> LocationScreen()
|
||||
NavTab.SETTINGS -> SettingsScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 应用选择全屏浮层(黑名单 / 白名单独立管理)
|
||||
AnimatedVisibility(
|
||||
visible = activeAppSelectionMode != null,
|
||||
enter = slideInHorizontally(initialOffsetX = { it }) + fadeIn(),
|
||||
exit = slideOutHorizontally(targetOffsetX = { it }) + fadeOut(),
|
||||
modifier = Modifier.fillMaxSize()
|
||||
) {
|
||||
activeAppSelectionMode?.let { mode ->
|
||||
AppSelectionScreen(
|
||||
mode = mode,
|
||||
onNavigateBack = { activeAppSelectionMode = null }
|
||||
)
|
||||
// 新版本更新弹窗(全局层级)
|
||||
updateInfoToDisplay?.let { info ->
|
||||
UpdateDialog(
|
||||
updateInfo = info,
|
||||
onDismiss = { updateInfoToDisplay = null },
|
||||
onDontShowAgain = { suppressedCode ->
|
||||
AppPreferences.updateSuppressedVersionCode(suppressedCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 新版本更新弹窗
|
||||
updateInfoToDisplay?.let { info ->
|
||||
UpdateDialog(
|
||||
updateInfo = info,
|
||||
onDismiss = { updateInfoToDisplay = null }
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.lzxnone.openloc.ui.screens.about
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.lzxnone.openloc.BuildConfig
|
||||
import com.lzxnone.openloc.R
|
||||
|
||||
@Composable
|
||||
fun AboutScreen(
|
||||
onCheckAppUpdate: () -> Unit = {},
|
||||
isCheckingUpdate: Boolean = false,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Spacer(modifier = Modifier.height(48.dp))
|
||||
|
||||
// 软件图标
|
||||
Image(
|
||||
painter = painterResource(id = R.drawable.app_logo),
|
||||
contentDescription = stringResource(R.string.app_name),
|
||||
modifier = Modifier
|
||||
.size(100.dp)
|
||||
.clip(RoundedCornerShape(22.dp))
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(18.dp))
|
||||
|
||||
// 软件名称
|
||||
Text(
|
||||
text = stringResource(R.string.app_name),
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
|
||||
// 作者
|
||||
Text(
|
||||
text = stringResource(R.string.about_author, "lzxnone"),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(36.dp))
|
||||
|
||||
// 版本与检查更新卡片
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
),
|
||||
elevation = CardDefaults.cardElevation(
|
||||
defaultElevation = 1.dp
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(vertical = 4.dp)) {
|
||||
// 版本
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Info,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.about_app_version),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
Text(
|
||||
text = "v${BuildConfig.VERSION_NAME}",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider(
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
|
||||
)
|
||||
|
||||
// 检查更新
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(enabled = !isCheckingUpdate) {
|
||||
onCheckAppUpdate()
|
||||
}
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Sync,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.about_check_updates),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
if (isCheckingUpdate) {
|
||||
Text(
|
||||
text = stringResource(R.string.checking_updates),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,23 +146,38 @@ fun AppSelectionScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// 关联当前名单选中的包名集合
|
||||
// 关联当前名单选中的包名集合(用于实时响应勾选状态与计数展示)
|
||||
val selectedPackages = if (mode == AppMockMode.BLACKLIST) {
|
||||
AppPreferences.blacklistApps
|
||||
} else {
|
||||
AppPreferences.whitelistApps
|
||||
}
|
||||
|
||||
// 根据搜索词和系统应用开关进行过滤
|
||||
val filteredApps = remember(installedApps, searchQuery, showSystemApps) {
|
||||
installedApps.filter { app ->
|
||||
(showSystemApps || !app.isSystemApp) &&
|
||||
(searchQuery.isBlank() ||
|
||||
app.appName.contains(searchQuery, ignoreCase = true) ||
|
||||
app.packageName.contains(searchQuery, ignoreCase = true))
|
||||
// 记录进入页面时的初始选中集合:排序仅基于此快照,选中/取消不立即触发重排,只有用户下一次进入页面时才重新排序
|
||||
val initialSelectedPackages = remember {
|
||||
if (mode == AppMockMode.BLACKLIST) {
|
||||
AppPreferences.blacklistApps
|
||||
} else {
|
||||
AppPreferences.whitelistApps
|
||||
}
|
||||
}
|
||||
|
||||
// 根据搜索词、系统应用开关过滤,基于进入页面时的 initialSelectedPackages 稳定排序
|
||||
val filteredApps = remember(installedApps, searchQuery, showSystemApps, initialSelectedPackages) {
|
||||
installedApps
|
||||
.filter { app ->
|
||||
(showSystemApps || !app.isSystemApp) &&
|
||||
(searchQuery.isBlank() ||
|
||||
app.appName.contains(searchQuery, ignoreCase = true) ||
|
||||
app.packageName.contains(searchQuery, ignoreCase = true))
|
||||
}
|
||||
.sortedWith(
|
||||
compareByDescending<InstalledAppItem> { initialSelectedPackages.contains(it.packageName) }
|
||||
.thenBy { it.isSystemApp }
|
||||
.thenBy { it.appName.lowercase(Locale.ROOT) }
|
||||
)
|
||||
}
|
||||
|
||||
// 标题与说明
|
||||
val titleText = if (mode == AppMockMode.BLACKLIST) {
|
||||
stringResource(id = R.string.apps_blacklist_title)
|
||||
@@ -374,6 +389,7 @@ fun AppSelectionScreen(
|
||||
items(filteredApps, key = { it.packageName }) { app ->
|
||||
val isChecked = selectedPackages.contains(app.packageName)
|
||||
AppItemCard(
|
||||
modifier = Modifier.animateItem(),
|
||||
app = app,
|
||||
isChecked = isChecked,
|
||||
onToggle = {
|
||||
|
||||
@@ -22,7 +22,6 @@ fun HomeScreen(
|
||||
onServiceEnabledChange: (Boolean) -> Unit,
|
||||
onOpenBlacklist: () -> Unit,
|
||||
onOpenWhitelist: () -> Unit,
|
||||
onCheckUpdate: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val scrollState = rememberScrollState()
|
||||
@@ -55,15 +54,5 @@ fun HomeScreen(
|
||||
onOpenBlacklist = onOpenBlacklist,
|
||||
onOpenWhitelist = onOpenWhitelist
|
||||
)
|
||||
|
||||
// 4. 版本与更新模块卡片
|
||||
VersionCard(
|
||||
versionName = "v1.0.0",
|
||||
isAutoCheckEnabled = AppPreferences.isAutoCheckUpdateEnabled,
|
||||
onAutoCheckChange = { AppPreferences.updateAutoCheckUpdateEnabled(it) },
|
||||
onCheckUpdate = onCheckUpdate
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
package com.lzxnone.openloc.ui.screens.home
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material.icons.outlined.Refresh
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.lzxnone.openloc.R
|
||||
import com.lzxnone.openloc.data.preference.AppPreferences
|
||||
|
||||
/**
|
||||
* 主页底部版本模块卡片
|
||||
* 显示应用当前版本(如 v1.0.0)、“检查更新”按钮,以及“启动时自动检查更新”开关
|
||||
*/
|
||||
@Composable
|
||||
fun VersionCard(
|
||||
versionName: String = stringResource(id = R.string.home_version_name),
|
||||
isAutoCheckEnabled: Boolean = AppPreferences.isAutoCheckUpdateEnabled,
|
||||
onAutoCheckChange: (Boolean) -> Unit = { AppPreferences.updateAutoCheckUpdateEnabled(it) },
|
||||
onCheckUpdate: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
),
|
||||
elevation = CardDefaults.cardElevation(
|
||||
defaultElevation = 1.dp
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth()) {
|
||||
// 上半部分:版本信息与手动检查更新按钮
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Surface(
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f),
|
||||
modifier = Modifier.size(40.dp)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Info,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(22.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(14.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = stringResource(id = R.string.home_version_card_title),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
Text(
|
||||
text = versionName,
|
||||
style = MaterialTheme.typography.titleMedium.copy(
|
||||
fontWeight = FontWeight.Bold
|
||||
),
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
FilledTonalButton(
|
||||
onClick = onCheckUpdate,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.filledTonalButtonColors(
|
||||
containerColor = MaterialTheme.colorScheme.secondaryContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Refresh,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = stringResource(id = R.string.home_check_updates_btn),
|
||||
style = MaterialTheme.typography.labelLarge.copy(
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider(
|
||||
modifier = Modifier.padding(horizontal = 20.dp),
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f)
|
||||
)
|
||||
|
||||
// 下半部分:自动检查更新选项(默认开启)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(id = R.string.home_auto_check_update_title),
|
||||
style = MaterialTheme.typography.titleSmall.copy(
|
||||
fontWeight = FontWeight.SemiBold
|
||||
),
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
Text(
|
||||
text = stringResource(id = R.string.home_auto_check_update_desc),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
|
||||
Switch(
|
||||
checked = isAutoCheckEnabled,
|
||||
onCheckedChange = onAutoCheckChange
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import android.location.LocationManager
|
||||
import android.os.Bundle
|
||||
import android.os.Looper
|
||||
import android.widget.Toast
|
||||
import com.lzxnone.openloc.createLocalizedContext
|
||||
import com.lzxnone.openloc.core.util.TraceLogger
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -156,7 +158,8 @@ val AMapVectorTileSource = object : OnlineTileSourceBase(
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun LocationScreen(
|
||||
modifier: Modifier = Modifier
|
||||
modifier: Modifier = Modifier,
|
||||
isVisible: Boolean = true
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
@@ -173,8 +176,12 @@ fun LocationScreen(
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
val searchHistory = AppPreferences.searchHistory
|
||||
|
||||
// 当前展示在地图上的点 (GCJ-02 火星坐标,用于 OSMDroid 高德底图渲染)
|
||||
val isServiceEnabled = AppPreferences.isServiceEnabled
|
||||
var currentGeoPoint by remember {
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(AppPreferences.mockLatitude, AppPreferences.mockLongitude)
|
||||
val initialWgsLat = AppPreferences.mockLatitude
|
||||
val initialWgsLng = AppPreferences.mockLongitude
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(initialWgsLat, initialWgsLng)
|
||||
mutableStateOf(GeoPoint(gcj[0], gcj[1]))
|
||||
}
|
||||
var currentZoom by remember { mutableDoubleStateOf(15.0) }
|
||||
@@ -185,6 +192,141 @@ fun LocationScreen(
|
||||
var mapViewRef by remember { mutableStateOf<MapView?>(null) }
|
||||
var currentMarker by remember { mutableStateOf<Marker?>(null) }
|
||||
|
||||
// 真实设备物理定位监听器(仅在总开关关闭时启动,总开关开启时严格注销)
|
||||
val realLocationListener = remember {
|
||||
object : LocationListener {
|
||||
override fun onLocationChanged(loc: Location) {
|
||||
TraceLogger.i("AppUI-Listener", "realLocationListener received: ${TraceLogger.formatLocation(loc)}, isServiceEnabled=${AppPreferences.isServiceEnabled}")
|
||||
// 仅当总开关处于关闭状态时,才响应物理定位更新并移动地图
|
||||
if (!AppPreferences.isServiceEnabled) {
|
||||
// 防脏缓存校验:确保不是残留的虚拟坐标
|
||||
val isMockSuspicious = kotlin.math.abs(loc.latitude - AppPreferences.mockLatitude) < 1e-5 &&
|
||||
kotlin.math.abs(loc.longitude - AppPreferences.mockLongitude) < 1e-5
|
||||
if (isMockSuspicious) {
|
||||
TraceLogger.w("AppUI-Listener", "Ignored suspicious mock match coordinate: ${loc.latitude}, ${loc.longitude}")
|
||||
return
|
||||
}
|
||||
|
||||
// Android 官方规范:所有 Provider 吐出的原始定位数据全部为 WGS-84
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(loc.latitude, loc.longitude)
|
||||
val p = GeoPoint(gcj[0], gcj[1])
|
||||
currentGeoPoint = p
|
||||
currentMarker?.position = p
|
||||
mapViewRef?.invalidate()
|
||||
coroutineScope.launch {
|
||||
val resolved = LocationResolver.resolveLocationName(context, loc.latitude, loc.longitude)
|
||||
locationName = resolved
|
||||
currentMarker?.title = resolved
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun onProviderEnabled(provider: String) {
|
||||
TraceLogger.d("AppUI-Listener", "Provider enabled: $provider")
|
||||
}
|
||||
override fun onProviderDisabled(provider: String) {
|
||||
TraceLogger.w("AppUI-Listener", "Provider disabled: $provider")
|
||||
}
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
|
||||
}
|
||||
}
|
||||
|
||||
// 单次主动获取真机物理真实定位(统一按 WGS-84 返回,绝不污染虚拟定位存储)
|
||||
fun fetchRealLocationOnce(
|
||||
lm: LocationManager,
|
||||
onLocation: (wgsLat: Double, wgsLng: Double) -> Unit
|
||||
) {
|
||||
TraceLogger.i("AppUI-FetchReal", "fetchRealLocationOnce initiated. CurrentMock=(${AppPreferences.mockLatitude}, ${AppPreferences.mockLongitude}), isServiceEnabled=${AppPreferences.isServiceEnabled}")
|
||||
|
||||
// 1. 优先读取系统缓存最新真实坐标 (0ms 即刻响应)
|
||||
val gpsLoc = try { lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) } catch (t: Throwable) {
|
||||
TraceLogger.e("AppUI-FetchReal", "getLastKnownLocation(GPS) error: ${t.message}")
|
||||
null
|
||||
}
|
||||
val netLoc = try { lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) } catch (t: Throwable) {
|
||||
TraceLogger.e("AppUI-FetchReal", "getLastKnownLocation(NETWORK) error: ${t.message}")
|
||||
null
|
||||
}
|
||||
val fusedLoc = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
|
||||
try { lm.getLastKnownLocation(LocationManager.FUSED_PROVIDER) } catch (t: Throwable) {
|
||||
TraceLogger.e("AppUI-FetchReal", "getLastKnownLocation(FUSED) error: ${t.message}")
|
||||
null
|
||||
}
|
||||
} else null
|
||||
|
||||
TraceLogger.d("AppUI-FetchReal", "System cached locations: GPS=${TraceLogger.formatLocation(gpsLoc)}, NET=${TraceLogger.formatLocation(netLoc)}, FUSED=${TraceLogger.formatLocation(fusedLoc)}")
|
||||
|
||||
val candidates = listOfNotNull(gpsLoc, netLoc, fusedLoc)
|
||||
val bestLoc = candidates.maxByOrNull { it.time }
|
||||
if (bestLoc != null) {
|
||||
// 防污染校验:若当前虚拟服务开启且缓存坐标与当前虚拟坐标一致,视为受污染残留缓存予以过滤
|
||||
val isMockSuspicious = AppPreferences.isServiceEnabled &&
|
||||
kotlin.math.abs(bestLoc.latitude - AppPreferences.mockLatitude) < 1e-5 &&
|
||||
kotlin.math.abs(bestLoc.longitude - AppPreferences.mockLongitude) < 1e-5
|
||||
TraceLogger.i("AppUI-FetchReal", "Selected best cache: ${TraceLogger.formatLocation(bestLoc)}, isMockSuspicious=$isMockSuspicious")
|
||||
|
||||
if (!isMockSuspicious) {
|
||||
onLocation(bestLoc.latitude, bestLoc.longitude)
|
||||
} else {
|
||||
TraceLogger.w("AppUI-FetchReal", "Skipping best cache because it matches active mock coordinates exactly!")
|
||||
}
|
||||
} else {
|
||||
TraceLogger.w("AppUI-FetchReal", "No system cached location found in any provider.")
|
||||
}
|
||||
|
||||
// 2. 异步请求一次高精度真实单次定位更新(直达底层硬件芯片,获取纯净物理坐标)
|
||||
try {
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
|
||||
val provider = when {
|
||||
android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S && lm.isProviderEnabled(LocationManager.FUSED_PROVIDER) -> LocationManager.FUSED_PROVIDER
|
||||
lm.isProviderEnabled(LocationManager.GPS_PROVIDER) -> LocationManager.GPS_PROVIDER
|
||||
lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) -> LocationManager.NETWORK_PROVIDER
|
||||
else -> LocationManager.PASSIVE_PROVIDER
|
||||
}
|
||||
TraceLogger.i("AppUI-FetchReal", "Requesting getCurrentLocation with provider=$provider")
|
||||
lm.getCurrentLocation(provider, null, context.mainExecutor) { loc ->
|
||||
TraceLogger.i("AppUI-FetchReal", "getCurrentLocation callback received: ${TraceLogger.formatLocation(loc)}")
|
||||
if (loc != null) {
|
||||
val isMockSuspicious = AppPreferences.isServiceEnabled &&
|
||||
kotlin.math.abs(loc.latitude - AppPreferences.mockLatitude) < 1e-5 &&
|
||||
kotlin.math.abs(loc.longitude - AppPreferences.mockLongitude) < 1e-5
|
||||
if (!isMockSuspicious) {
|
||||
TraceLogger.i("AppUI-FetchReal", "Delivering valid physical location: (${loc.latitude}, ${loc.longitude})")
|
||||
onLocation(loc.latitude, loc.longitude)
|
||||
} else {
|
||||
TraceLogger.w("AppUI-FetchReal", "getCurrentLocation returned exact mock coordinates! Filtered.")
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val singleListener = object : LocationListener {
|
||||
override fun onLocationChanged(loc: Location) {
|
||||
TraceLogger.i("AppUI-FetchReal", "requestSingleUpdate callback: ${TraceLogger.formatLocation(loc)}")
|
||||
val isMockSuspicious = AppPreferences.isServiceEnabled &&
|
||||
kotlin.math.abs(loc.latitude - AppPreferences.mockLatitude) < 1e-5 &&
|
||||
kotlin.math.abs(loc.longitude - AppPreferences.mockLongitude) < 1e-5
|
||||
if (!isMockSuspicious) {
|
||||
onLocation(loc.latitude, loc.longitude)
|
||||
} else {
|
||||
TraceLogger.w("AppUI-FetchReal", "requestSingleUpdate returned exact mock coordinates! Filtered.")
|
||||
}
|
||||
try { lm.removeUpdates(this) } catch (_: Throwable) {}
|
||||
}
|
||||
override fun onProviderDisabled(p: String) {}
|
||||
override fun onProviderEnabled(p: String) {}
|
||||
override fun onStatusChanged(p: String?, s: Int, e: Bundle?) {}
|
||||
}
|
||||
val provider = if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) LocationManager.GPS_PROVIDER else LocationManager.NETWORK_PROVIDER
|
||||
TraceLogger.i("AppUI-FetchReal", "Requesting requestSingleUpdate with provider=$provider")
|
||||
@Suppress("DEPRECATION")
|
||||
lm.requestSingleUpdate(provider, singleListener, Looper.getMainLooper())
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
TraceLogger.e("AppUI-FetchReal", "Async real location request failed: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化 OSMDroid 配置(强制指定内部私有目录,避免外置存储权限异常)
|
||||
DisposableEffect(Unit) {
|
||||
val basePath = java.io.File(context.cacheDir, "osmdroid")
|
||||
@@ -192,10 +334,90 @@ fun LocationScreen(
|
||||
Configuration.getInstance().osmdroidTileCache = java.io.File(basePath, "tiles")
|
||||
Configuration.getInstance().userAgentValue = context.packageName
|
||||
onDispose {
|
||||
val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
|
||||
try { lm?.removeUpdates(realLocationListener) } catch (_: Throwable) {}
|
||||
mapViewRef?.onDetach()
|
||||
}
|
||||
}
|
||||
|
||||
// 核心二元状态机:根据虚拟定位总开关 (isServiceEnabled) 与页面可见性 (isVisible) 切换定位模式
|
||||
LaunchedEffect(isServiceEnabled, isVisible) {
|
||||
val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return@LaunchedEffect
|
||||
val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
if (isServiceEnabled || !isVisible) {
|
||||
// 当总开关开启或页面处于不可见状态时,彻底注销物理真实定位监听,节省电量与硬件开销
|
||||
try {
|
||||
lm.removeUpdates(realLocationListener)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
if (isServiceEnabled) {
|
||||
// ================= 【总开关开启】 =================
|
||||
// 检查是否为首次开启且从未手动选过点:若无历史选点,主动取一次真实定位作为初始点
|
||||
if (!AppPreferences.hasUserSetLocation && (hasFine || hasCoarse)) {
|
||||
fetchRealLocationOnce(lm) { realWgsLat, realWgsLng ->
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(realWgsLat, realWgsLng)
|
||||
val p = GeoPoint(gcj[0], gcj[1])
|
||||
currentGeoPoint = p
|
||||
currentMarker?.position = p
|
||||
mapViewRef?.controller?.setCenter(p)
|
||||
mapViewRef?.invalidate()
|
||||
coroutineScope.launch {
|
||||
val resolved = LocationResolver.resolveLocationName(context, realWgsLat, realWgsLng)
|
||||
locationName = resolved
|
||||
currentMarker?.title = resolved
|
||||
AppPreferences.updateMockLocation(realWgsLat, realWgsLng, name = resolved, isUserManual = false)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 3. 正常状态:地图上的位置就是我们 hook 的虚拟位置,锁定不变
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(AppPreferences.mockLatitude, AppPreferences.mockLongitude)
|
||||
val p = GeoPoint(gcj[0], gcj[1])
|
||||
currentGeoPoint = p
|
||||
currentMarker?.position = p
|
||||
locationName = AppPreferences.mockLocationName.ifEmpty {
|
||||
String.format(Locale.getDefault(), "%.5f, %.5f", AppPreferences.mockLatitude, AppPreferences.mockLongitude)
|
||||
}
|
||||
currentMarker?.title = locationName
|
||||
mapViewRef?.controller?.setCenter(p)
|
||||
mapViewRef?.invalidate()
|
||||
}
|
||||
} else if (isVisible) {
|
||||
// ================= 【总开关关闭 & 页面可见】 =================
|
||||
// 1. 关闭的一瞬间,立马主动获取一次真机真实坐标,拉回当前设备物理原位
|
||||
if (hasFine || hasCoarse) {
|
||||
fetchRealLocationOnce(lm) { realWgsLat, realWgsLng ->
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(realWgsLat, realWgsLng)
|
||||
val p = GeoPoint(gcj[0], gcj[1])
|
||||
currentGeoPoint = p
|
||||
currentMarker?.position = p
|
||||
mapViewRef?.controller?.setCenter(p)
|
||||
mapViewRef?.invalidate()
|
||||
coroutineScope.launch {
|
||||
val resolved = LocationResolver.resolveLocationName(context, realWgsLat, realWgsLng)
|
||||
locationName = resolved
|
||||
currentMarker?.title = resolved
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 开启实时监听真实物理位置并在地图上显示(绝不调用 updateMockLocation 覆盖虚拟选点)
|
||||
try {
|
||||
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
|
||||
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 1.0f, realLocationListener, Looper.getMainLooper())
|
||||
}
|
||||
if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
|
||||
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 1.0f, realLocationListener, Looper.getMainLooper())
|
||||
}
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S && lm.isProviderEnabled(LocationManager.FUSED_PROVIDER)) {
|
||||
lm.requestLocationUpdates(LocationManager.FUSED_PROVIDER, 1000L, 1.0f, realLocationListener, Looper.getMainLooper())
|
||||
}
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 搜索输入防抖监听 (400ms,感知搜索引擎和各Key的变化)
|
||||
LaunchedEffect(
|
||||
searchQuery,
|
||||
@@ -280,95 +502,52 @@ fun LocationScreen(
|
||||
|
||||
currentGeoPoint = mapPoint
|
||||
currentMarker?.position = mapPoint
|
||||
mapViewRef?.controller?.animateTo(mapPoint)
|
||||
mapViewRef?.controller?.setCenter(mapPoint)
|
||||
mapViewRef?.invalidate()
|
||||
|
||||
locationName = result.name
|
||||
currentMarker?.title = result.name
|
||||
AppPreferences.updateMockLocation(result.latitude, result.longitude, name = result.name, isUserManual = true)
|
||||
}
|
||||
|
||||
// 定位到设备当前真实物理位置逻辑(例如在武汉则精确定位到武汉)
|
||||
fun locateToDeviceRealPosition(animate: Boolean = true) {
|
||||
val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return
|
||||
val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
if (hasFine || hasCoarse) {
|
||||
val gpsLoc = try { lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) } catch (_: SecurityException) { null }
|
||||
val netLoc = try { lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) } catch (_: SecurityException) { null }
|
||||
|
||||
val bestLoc = when {
|
||||
gpsLoc != null && netLoc != null -> if (gpsLoc.time > netLoc.time) gpsLoc else netLoc
|
||||
gpsLoc != null -> gpsLoc
|
||||
netLoc != null -> netLoc
|
||||
else -> null
|
||||
}
|
||||
|
||||
if (bestLoc != null) {
|
||||
// 真实硬件 GPS 返回 WGS-84,转换为 GCJ-02 精准标在高德瓦片上
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(bestLoc.latitude, bestLoc.longitude)
|
||||
updatePositionAndResolveName(
|
||||
pointOnMap = GeoPoint(gcj[0], gcj[1]),
|
||||
isUserManual = false,
|
||||
centerMap = true,
|
||||
animate = animate
|
||||
)
|
||||
}
|
||||
|
||||
// 异步刷新获取最新单次定位
|
||||
try {
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
|
||||
lm.getCurrentLocation(
|
||||
LocationManager.NETWORK_PROVIDER,
|
||||
null,
|
||||
context.mainExecutor
|
||||
) { loc ->
|
||||
if (loc != null) {
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(loc.latitude, loc.longitude)
|
||||
updatePositionAndResolveName(
|
||||
pointOnMap = GeoPoint(gcj[0], gcj[1]),
|
||||
isUserManual = false,
|
||||
centerMap = true,
|
||||
animate = true
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val singleListener = object : LocationListener {
|
||||
override fun onLocationChanged(loc: Location) {
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(loc.latitude, loc.longitude)
|
||||
updatePositionAndResolveName(
|
||||
pointOnMap = GeoPoint(gcj[0], gcj[1]),
|
||||
isUserManual = false,
|
||||
centerMap = true,
|
||||
animate = true
|
||||
)
|
||||
try { lm.removeUpdates(this) } catch (_: Throwable) {}
|
||||
}
|
||||
override fun onProviderDisabled(p: String) {}
|
||||
override fun onProviderEnabled(p: String) {}
|
||||
override fun onStatusChanged(p: String?, s: Int, e: Bundle?) {}
|
||||
}
|
||||
|
||||
if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
|
||||
@Suppress("DEPRECATION")
|
||||
lm.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, singleListener, Looper.getMainLooper())
|
||||
}
|
||||
}
|
||||
} catch (_: SecurityException) {}
|
||||
if (!AppPreferences.isServiceEnabled) {
|
||||
AppPreferences.updateServiceEnabled(true)
|
||||
}
|
||||
}
|
||||
|
||||
// 权限请求器(仅在用户点击“回到原位”按钮时按需触发)
|
||||
// 点击“回到原位”按钮处理逻辑
|
||||
val onResetToRealLocation: () -> Unit = {
|
||||
val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
|
||||
TraceLogger.i("AppUI-Reset", "User clicked 'Reset to Real Location' button. CurrentServiceEnabled=${AppPreferences.isServiceEnabled}, Mock=(${AppPreferences.mockLatitude}, ${AppPreferences.mockLongitude})")
|
||||
if (lm != null) {
|
||||
fetchRealLocationOnce(lm) { realWgsLat, realWgsLng ->
|
||||
TraceLogger.i("AppUI-Reset", "fetchRealLocationOnce SUCCESS: realWgs=($realWgsLat, $realWgsLng)")
|
||||
val gcj = CoordinateConverter.wgs84ToGcj02(realWgsLat, realWgsLng)
|
||||
val p = GeoPoint(gcj[0], gcj[1])
|
||||
currentGeoPoint = p
|
||||
currentMarker?.position = p
|
||||
mapViewRef?.controller?.animateTo(p)
|
||||
mapViewRef?.invalidate()
|
||||
coroutineScope.launch {
|
||||
val resolved = LocationResolver.resolveLocationName(context, realWgsLat, realWgsLng)
|
||||
locationName = resolved
|
||||
currentMarker?.title = resolved
|
||||
// 若当前总开关开启,点击回到原位意味着用户希望将虚拟位置设定为当前真实物理位置
|
||||
if (AppPreferences.isServiceEnabled) {
|
||||
TraceLogger.w("AppUI-Reset", "Updating mock location to newly acquired real position: ($realWgsLat, $realWgsLng)")
|
||||
AppPreferences.updateMockLocation(realWgsLat, realWgsLng, name = resolved, isUserManual = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 权限请求器(用户点击“回到原位”按钮按需触发)
|
||||
val permissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestMultiplePermissions()
|
||||
) { permissions ->
|
||||
val granted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true ||
|
||||
permissions[Manifest.permission.ACCESS_COARSE_LOCATION] == true
|
||||
if (granted) {
|
||||
locateToDeviceRealPosition(animate = true)
|
||||
onResetToRealLocation()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,6 +577,15 @@ fun LocationScreen(
|
||||
// 点击即移动位置(无需确认)
|
||||
val tapOverlay = MapEventsOverlay(object : MapEventsReceiver {
|
||||
override fun singleTapConfirmedHelper(p: GeoPoint): Boolean {
|
||||
if (!AppPreferences.isServiceEnabled) {
|
||||
val localizedContext = createLocalizedContext(context, AppPreferences.appLanguage)
|
||||
Toast.makeText(
|
||||
localizedContext,
|
||||
localizedContext.getString(R.string.location_mock_disabled_prompt),
|
||||
Toast.LENGTH_SHORT
|
||||
).show()
|
||||
return true
|
||||
}
|
||||
// 点击地图位置时,只移动标记,不把点击位置强制作为视图中心
|
||||
updatePositionAndResolveName(
|
||||
pointOnMap = p,
|
||||
@@ -417,12 +605,24 @@ fun LocationScreen(
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
update = { mapView ->
|
||||
currentMarker?.position = currentGeoPoint
|
||||
mapView.invalidate()
|
||||
if (isVisible) {
|
||||
if (mapView.visibility != android.view.View.VISIBLE) {
|
||||
mapView.visibility = android.view.View.VISIBLE
|
||||
mapView.onResume()
|
||||
}
|
||||
currentMarker?.position = currentGeoPoint
|
||||
mapView.invalidate()
|
||||
} else {
|
||||
if (mapView.visibility != android.view.View.GONE) {
|
||||
mapView.onPause()
|
||||
mapView.visibility = android.view.View.GONE
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// ------------------ 2. 顶部未激活时的浮动搜索胶囊 ------------------
|
||||
if (isVisible) {
|
||||
// ------------------ 2. 顶部未激活时的浮动搜索胶囊 ------------------
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -469,7 +669,7 @@ fun LocationScreen(
|
||||
val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
if (hasFine || hasCoarse) {
|
||||
locateToDeviceRealPosition(animate = true)
|
||||
onResetToRealLocation()
|
||||
} else {
|
||||
permissionLauncher.launch(
|
||||
arrayOf(
|
||||
@@ -1104,7 +1304,7 @@ fun LocationScreen(
|
||||
pointOnMap = targetPoint,
|
||||
isUserManual = true,
|
||||
centerMap = true,
|
||||
animate = true
|
||||
animate = false
|
||||
)
|
||||
locationName = favorite.name
|
||||
showFavoritesScreen = false
|
||||
@@ -1376,6 +1576,7 @@ fun LocationScreen(
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
package com.lzxnone.openloc.ui.screens.settings
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -33,6 +38,7 @@ import androidx.compose.material.icons.filled.DarkMode
|
||||
import androidx.compose.material.icons.filled.DeveloperMode
|
||||
import androidx.compose.material.icons.filled.Explore
|
||||
import androidx.compose.material.icons.filled.Key
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.SatelliteAlt
|
||||
import androidx.compose.material.icons.filled.Security
|
||||
import androidx.compose.material.icons.filled.Translate
|
||||
@@ -81,7 +87,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
|
||||
@@ -94,6 +102,11 @@ fun SettingsScreen(
|
||||
val scrollState = rememberScrollState()
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
val context = LocalContext.current
|
||||
val notificationPermissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission()
|
||||
) { granted ->
|
||||
AppPreferences.updateNotificationEnabled(granted)
|
||||
}
|
||||
|
||||
// 控制各个面板显示状态
|
||||
var showLanguageSheet by remember { mutableStateOf(false) }
|
||||
@@ -298,6 +311,150 @@ 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),
|
||||
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),
|
||||
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()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ 2.6 通知设置板块 ------------------
|
||||
Text(
|
||||
text = stringResource(id = R.string.settings_category_notification),
|
||||
style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(start = 4.dp, top = 4.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_notification_enabled_title),
|
||||
icon = Icons.Default.Notifications,
|
||||
checked = AppPreferences.isNotificationEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
AppPreferences.updateNotificationEnabled(enabled)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------ 3. 地图与搜索服务板块 ------------------
|
||||
Text(
|
||||
text = stringResource(id = R.string.settings_category_map_service),
|
||||
@@ -400,102 +557,6 @@ fun SettingsScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ 4. 防检测与真实度增强板块 ------------------
|
||||
Text(
|
||||
text = stringResource(id = R.string.settings_category_anti_detection),
|
||||
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)
|
||||
) {
|
||||
Column {
|
||||
// (1) 位置自然微漂移
|
||||
SettingSwitchItem(
|
||||
title = stringResource(id = R.string.settings_anti_jitter_title),
|
||||
description = stringResource(id = R.string.settings_anti_jitter_desc),
|
||||
icon = Icons.Filled.Explore,
|
||||
checked = AppPreferences.isJitterEnabled,
|
||||
onCheckedChange = { AppPreferences.updateJitterEnabled(it) }
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
|
||||
modifier = Modifier.padding(horizontal = 16.dp)
|
||||
)
|
||||
|
||||
// (2) 全真多星座卫星仿真
|
||||
SettingSwitchItem(
|
||||
title = stringResource(id = R.string.settings_anti_gnss_title),
|
||||
description = stringResource(id = R.string.settings_anti_gnss_desc),
|
||||
icon = Icons.Filled.SatelliteAlt,
|
||||
checked = AppPreferences.isGnssSimulationEnabled,
|
||||
onCheckedChange = { AppPreferences.updateGnssSimulationEnabled(it) }
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
|
||||
modifier = Modifier.padding(horizontal = 16.dp)
|
||||
)
|
||||
|
||||
// (3) 基站与 Wi-Fi 防反查
|
||||
SettingSwitchItem(
|
||||
title = stringResource(id = R.string.settings_anti_network_title),
|
||||
description = stringResource(id = R.string.settings_anti_network_desc),
|
||||
icon = Icons.Filled.CellTower,
|
||||
checked = AppPreferences.isNetworkCamouflageEnabled,
|
||||
onCheckedChange = { AppPreferences.updateNetworkCamouflageEnabled(it) }
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
|
||||
modifier = Modifier.padding(horizontal = 16.dp)
|
||||
)
|
||||
|
||||
// (4) 传感器手持生理拟真
|
||||
SettingSwitchItem(
|
||||
title = stringResource(id = R.string.settings_anti_sensor_title),
|
||||
description = stringResource(id = R.string.settings_anti_sensor_desc),
|
||||
icon = Icons.Filled.Vibration,
|
||||
checked = AppPreferences.isSensorSimulationEnabled,
|
||||
onCheckedChange = { AppPreferences.updateSensorSimulationEnabled(it) }
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
|
||||
modifier = Modifier.padding(horizontal = 16.dp)
|
||||
)
|
||||
|
||||
// (5) 堆栈与模块自隐匿
|
||||
SettingSwitchItem(
|
||||
title = stringResource(id = R.string.settings_anti_stealth_title),
|
||||
description = stringResource(id = R.string.settings_anti_stealth_desc),
|
||||
icon = Icons.Filled.Security,
|
||||
checked = AppPreferences.isStealthEnabled,
|
||||
onCheckedChange = { AppPreferences.updateStealthEnabled(it) }
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
|
||||
modifier = Modifier.padding(horizontal = 16.dp)
|
||||
)
|
||||
|
||||
// (6) 开发者选项伪装
|
||||
SettingSwitchItem(
|
||||
title = stringResource(id = R.string.settings_anti_dev_title),
|
||||
description = stringResource(id = R.string.settings_anti_dev_desc),
|
||||
icon = Icons.Filled.DeveloperMode,
|
||||
checked = AppPreferences.isDevCamouflageEnabled,
|
||||
onCheckedChange = { AppPreferences.updateDevCamouflageEnabled(it) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ 搜索引擎提供商选择底部抽屉 (ModalBottomSheet) ------------------
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.6 KiB |
@@ -0,0 +1,224 @@
|
||||
<resources>
|
||||
<string name="app_name">OpenLoc</string>
|
||||
<string name="xposed_description">OpenLoc virtual location hook module</string>
|
||||
|
||||
<!-- Bottom Navigation -->
|
||||
<string name="nav_home">Home</string>
|
||||
<string name="nav_location">Location</string>
|
||||
<string name="nav_settings">Settings</string>
|
||||
|
||||
<!-- Home Screen - Module Status Card -->
|
||||
<string name="module_status_title">Module Status</string>
|
||||
<string name="module_status_activated">Activated</string>
|
||||
<string name="module_status_inactive">Inactive</string>
|
||||
|
||||
<!-- Master Switch Card -->
|
||||
<string name="service_switch_title">Master Switch</string>
|
||||
<string name="service_switch_desc_enabled">Virtual location is running</string>
|
||||
<string name="service_switch_desc_disabled">Virtual location is paused</string>
|
||||
<string name="service_switch_disabled_hint">Module inactive, switch is disabled</string>
|
||||
|
||||
<!-- Settings - Categories -->
|
||||
<string name="settings_category_language">Language</string>
|
||||
<string name="settings_category_appearance">Appearance</string>
|
||||
|
||||
<!-- Settings - Language -->
|
||||
<string name="settings_language_title">App Language</string>
|
||||
<string name="settings_language_sheet_title">Select Language</string>
|
||||
<string name="settings_language_system">Follow System</string>
|
||||
<string name="settings_language_zh">简体中文 (Chinese)</string>
|
||||
<string name="settings_language_en">English</string>
|
||||
|
||||
<!-- Settings - Appearance -->
|
||||
<string name="settings_theme_mode_title">Theme Mode</string>
|
||||
<string name="settings_theme_mode_sheet_title">Select Theme Mode</string>
|
||||
<string name="settings_theme_mode_system">Follow System</string>
|
||||
<string name="settings_theme_mode_light">Light Mode</string>
|
||||
<string name="settings_theme_mode_dark">Dark Mode</string>
|
||||
|
||||
<string name="settings_dynamic_color_title">System Theme Color</string>
|
||||
<string name="settings_dynamic_color_desc">Follow system wallpaper dynamic colors (Android 12+)</string>
|
||||
|
||||
<string name="settings_theme_color_title">Theme Color</string>
|
||||
<string name="settings_theme_color_dialog_title">Choose Palette</string>
|
||||
|
||||
<string name="action_cancel">Cancel</string>
|
||||
<string name="action_confirm">Confirm</string>
|
||||
|
||||
<!-- Location Screen -->
|
||||
<string name="location_search_hint">Search location / address…</string>
|
||||
<string name="location_default_name">Selected Location</string>
|
||||
<string name="location_latitude_format">Lat: %1$.6f</string>
|
||||
<string name="location_longitude_format">Lng: %1$.6f</string>
|
||||
<string name="location_copy_coords">Copy Coordinates</string>
|
||||
<string name="location_coords_copied">Coordinates copied to clipboard</string>
|
||||
<string name="location_reset_current">Reset to current location</string>
|
||||
<string name="location_located_to_real">Located to current position</string>
|
||||
<string name="location_mock_disabled_prompt">Virtual location is not enabled, please enable it first</string>
|
||||
<string name="location_search_back">Back</string>
|
||||
<string name="location_search_clear">Clear</string>
|
||||
<string name="location_search_history">Recent Searches</string>
|
||||
<string name="location_search_clear_history">Clear History</string>
|
||||
<string name="location_search_no_results">No matching places found</string>
|
||||
<string name="location_search_empty_hint">Enter place name or coordinates to search</string>
|
||||
<string name="location_search_coord_jump">Jump to coordinates</string>
|
||||
|
||||
<!-- Map & Search Service Settings -->
|
||||
<string name="settings_category_map_service">Map & Search Service</string>
|
||||
<string name="settings_search_provider_title">Search Engine Provider</string>
|
||||
<string name="settings_search_provider_sheet_title">Select Search Provider</string>
|
||||
<string name="search_provider_amap">AMap</string>
|
||||
<string name="search_provider_baidu">Baidu</string>
|
||||
<string name="search_provider_photon">Photon</string>
|
||||
<string name="search_provider_nominatim">Nominatim</string>
|
||||
<string name="search_provider_badge_requires_key">Key Required</string>
|
||||
<string name="search_provider_badge_free">Free / No Key</string>
|
||||
|
||||
<string name="settings_api_key_title">API Key</string>
|
||||
<string name="settings_api_key_free_value">Not Required</string>
|
||||
<string name="settings_api_key_placeholder">Enter Key / AK</string>
|
||||
<string name="settings_api_key_empty">Key cannot be empty</string>
|
||||
<string name="error_unknown">Unknown error</string>
|
||||
<string name="location_search_coord_format">Lng: %1$.6f, Lat: %2$.6f</string>
|
||||
<string name="settings_api_key_test">Test</string>
|
||||
<string name="settings_api_key_testing">Testing...</string>
|
||||
<string name="settings_api_key_test_success">Test passed! Key is valid.</string>
|
||||
<string name="settings_api_key_test_failed">Test failed: %1$s</string>
|
||||
|
||||
<string name="settings_amap_key_dialog_title">Configure AMap Key</string>
|
||||
<string name="settings_amap_key_hint">Get Web Service Key from lbs.amap.com</string>
|
||||
<string name="settings_baidu_key_dialog_title">Configure Baidu AK</string>
|
||||
<string name="settings_baidu_key_hint">Get Server AK from lbsyun.baidu.com</string>
|
||||
<string name="settings_amap_key_configured">Configured</string>
|
||||
<string name="settings_amap_key_not_configured">Not Configured</string>
|
||||
<string name="settings_amap_key_clear">Clear</string>
|
||||
<string name="settings_amap_key_save">Save</string>
|
||||
|
||||
<string name="search_no_api_key_title_dynamic">%1$s Key Not Configured</string>
|
||||
<string name="search_no_api_key_desc_dynamic">This engine requires an API Key. You can configure it or switch to a free engine.</string>
|
||||
<string name="search_configure_key_button">Configure Key</string>
|
||||
<string name="search_switch_provider_button">Switch Provider</string>
|
||||
<string name="search_key_invalid_title_dynamic">Invalid %1$s Key</string>
|
||||
<string name="search_key_invalid_desc">Key verification failed (%1$s). Please check platform type or re-enter.</string>
|
||||
<string name="search_edit_key_button">Edit Key</string>
|
||||
<string name="search_network_error">Network request failed, please check connection</string>
|
||||
<string name="location_card_collapse">Collapse</string>
|
||||
<string name="location_card_expand">Expand</string>
|
||||
|
||||
<!-- Favorites -->
|
||||
<string name="favorites_title">Favorites</string>
|
||||
<string name="favorite_add_title">Add Favorite Location</string>
|
||||
<string name="favorite_name_label">Name</string>
|
||||
<string name="favorite_name_hint">e.g. Home / Company</string>
|
||||
<string name="favorite_address_label">Area / Address</string>
|
||||
<string name="favorite_address_deriving">Deriving area name…</string>
|
||||
<string name="favorite_latitude_label">Latitude (WGS-84)</string>
|
||||
<string name="favorite_longitude_label">Longitude (WGS-84)</string>
|
||||
<string name="favorite_search_hint">Search name or area…</string>
|
||||
<string name="favorite_empty_list">No favorites yet. Tap + to add.</string>
|
||||
<string name="favorite_search_empty">No matching favorites found</string>
|
||||
<string name="favorite_delete_confirm_title">Delete Favorite</string>
|
||||
<string name="favorite_delete_confirm_msg">Are you sure you want to delete \"%1$s\"?</string>
|
||||
<string name="favorite_added_success">Added to favorites</string>
|
||||
<string name="favorite_deleted_success">Favorite deleted</string>
|
||||
<string name="favorite_applied_success">Moved to: %1$s</string>
|
||||
<string name="favorite_invalid_coords">Please enter valid latitude (-90~90) and longitude (-180~180)</string>
|
||||
<string name="favorite_invalid_name">Name cannot be empty</string>
|
||||
<string name="favorite_delete">Delete</string>
|
||||
<string name="favorite_drag_handle">Drag to reorder</string>
|
||||
<string name="location_unknown_address">Unknown address</string>
|
||||
|
||||
<!-- App Management / Scope -->
|
||||
<string name="apps_management_title">App Scope Management</string>
|
||||
<string name="apps_management_desc">Configure target apps and mock rules</string>
|
||||
<string name="apps_mode_title">Mock Mode</string>
|
||||
<string name="apps_mode_global">Global</string>
|
||||
<string name="apps_mode_blacklist">Blacklist</string>
|
||||
<string name="apps_mode_whitelist">Whitelist</string>
|
||||
<string name="apps_mode_global_desc">All applications on this device will receive mocked location.</string>
|
||||
<string name="apps_mode_blacklist_desc">Apps in the blacklist keep real location, while all other apps receive mocked location.</string>
|
||||
<string name="apps_mode_whitelist_desc">Only apps in the whitelist receive mocked location, while other apps keep real location.</string>
|
||||
<string name="apps_blacklist_title">Blacklist Apps</string>
|
||||
<string name="apps_whitelist_title">Whitelist Apps</string>
|
||||
<string name="apps_blacklist_subtitle">%1$d apps excluded</string>
|
||||
<string name="apps_whitelist_subtitle">%1$d apps enabled</string>
|
||||
<string name="apps_search_hint">Search app name or package…</string>
|
||||
<string name="apps_select_all">Select All</string>
|
||||
<string name="apps_deselect_all">Deselect All</string>
|
||||
<string name="apps_show_system_apps">Show system apps</string>
|
||||
<string name="apps_hide_system_apps">Hide system apps</string>
|
||||
<string name="apps_system_app_tag">System</string>
|
||||
<string name="apps_loading">Loading installed applications…</string>
|
||||
<string name="apps_empty_search">No matching applications found</string>
|
||||
<string name="apps_empty_installed">No applications found</string>
|
||||
<string name="apps_selected_count">%1$d / %2$d selected</string>
|
||||
|
||||
<!-- Anti-Detection & Realism Settings -->
|
||||
<string name="settings_category_anti_detection">Anti-Detection & Realism</string>
|
||||
<string name="settings_anti_jitter_title">Natural Location Drift</string>
|
||||
<string name="settings_anti_jitter_desc">Simulate smooth Brownian motion / Gaussian GNSS noise to prevent static location detection</string>
|
||||
<string name="settings_anti_gnss_title">Full Constellation GNSS Simulation</string>
|
||||
<string name="settings_anti_gnss_desc">Simulate realistic multi-constellation satellites (GPS, BeiDou, GLONASS, Galileo) with physical C/N0 noise and NMEA GSV/GSA sentences</string>
|
||||
<string name="settings_anti_network_title">Cell Tower & Wi-Fi Camouflage</string>
|
||||
<string name="settings_anti_network_desc">Camouflage cell tower and Wi-Fi BSSID to prevent cloud reverse geolocation lookup</string>
|
||||
<string name="settings_anti_sensor_title">Handheld Motion Sensor Simulation</string>
|
||||
<string name="settings_anti_sensor_desc">Inject subtle physiological micro-tremor into accelerometer readings to mimic active human hand-holding</string>
|
||||
<string name="settings_anti_stealth_title">Module Package Stealth</string>
|
||||
<string name="settings_anti_stealth_desc">Hide OpenLoc package from target apps to prevent package scanning detection</string>
|
||||
<string name="settings_anti_dev_title">Mock Flag Sanitization</string>
|
||||
<string name="settings_anti_dev_desc">Sanitize isMock and mIsFromMockProvider flags in Location objects</string>
|
||||
|
||||
|
||||
<!-- Version & Updates -->
|
||||
<string name="home_version_card_title">Current Version</string>
|
||||
<string name="home_version_name">v1.2.2</string>
|
||||
<string name="home_check_updates_btn">Check for Updates</string>
|
||||
<string name="home_auto_check_update_title">Auto Check on Launch</string>
|
||||
<string name="home_auto_check_update_desc">Automatically check for new releases when opening the app</string>
|
||||
<string name="home_checking_update">Checking for updates…</string>
|
||||
<string name="home_update_available_title">New Version Available: %1$s</string>
|
||||
<string name="home_update_dialog_msg">A new version of OpenLoc has been released.</string>
|
||||
<string name="home_update_btn_go">Go to Update</string>
|
||||
<string name="home_update_btn_later">Later</string>
|
||||
<string name="home_check_update_failed">Failed to check for updates, please check network</string>
|
||||
<string name="home_already_latest">Already the latest version (%1$s)</string>
|
||||
|
||||
<!-- About & Updates -->
|
||||
<string name="section_about">About</string>
|
||||
<string name="btn_back">Back</string>
|
||||
<string name="about_author">Author: %1$s</string>
|
||||
<string name="about_app_version">Version</string>
|
||||
<string name="about_check_updates">Check for Updates</string>
|
||||
<string name="about_latest_version">Already up to date</string>
|
||||
<string name="checking_updates">Checking for updates…</string>
|
||||
<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>
|
||||
|
||||
<!-- Notification Settings -->
|
||||
<string name="settings_category_notification">Notification Settings</string>
|
||||
<string name="settings_notification_enabled_title">Status Bar Notification</string>
|
||||
<string name="settings_notification_enabled_desc">Show app icon, mock location, and motion parameters in a persistent notification while mock location is active</string>
|
||||
<string name="notification_title_format">OpenLoc · %1$s</string>
|
||||
<string name="notification_mode_running">Running Mode</string>
|
||||
<string name="notification_mode_static">Static Mock</string>
|
||||
<string name="notification_location_unnamed">Custom Point</string>
|
||||
<string name="notification_coord_line">Lat: %1$.5f Lng: %2$.5f</string>
|
||||
<string name="notification_speed_bearing_line">Speed: %1$.2f m/s Bearing: %2$.0f°</string>
|
||||
<string name="notification_accel_line">X Accel: %1$.2f Y Accel: %2$.2f Z Accel: %3$.2f</string>
|
||||
</resources>
|
||||
@@ -54,6 +54,7 @@
|
||||
<string name="location_coords_copied">已复制坐标到剪贴板</string>
|
||||
<string name="location_reset_current">回到原位</string>
|
||||
<string name="location_located_to_real">已定位到当前真实位置</string>
|
||||
<string name="location_mock_disabled_prompt">虚拟定位未开启,请先开启虚拟定位</string>
|
||||
<string name="location_search_back">返回</string>
|
||||
<string name="location_search_clear">清空</string>
|
||||
<string name="location_search_history">搜索历史</string>
|
||||
@@ -162,24 +163,64 @@
|
||||
<string name="settings_anti_network_desc">脱敏基站小区与 Wi-Fi BSSID,拦截运营商基站监听,杜绝云端指纹库反查真实物理地址</string>
|
||||
<string name="settings_anti_sensor_title">传感器手持生理拟真</string>
|
||||
<string name="settings_anti_sensor_desc">向加速度计注入生物力学生理微颤,打破桌面绝对静止特征,满足步态与姿态校验</string>
|
||||
<string name="settings_anti_stealth_title">堆栈与模块自隐匿</string>
|
||||
<string name="settings_anti_stealth_desc">过滤调用栈中的 Xposed 与 OpenLoc 栈帧,并对目标应用隐藏模块包名</string>
|
||||
<string name="settings_anti_dev_title">开发者选项伪装</string>
|
||||
<string name="settings_anti_dev_desc">对目标应用伪装为未开启开发者模式、未开启 USB 调试与未开启模拟位置</string>
|
||||
<string name="settings_anti_stealth_title">模块包名自隐匿</string>
|
||||
<string name="settings_anti_stealth_desc">对目标应用隐藏 OpenLoc 安装包名,防止通过 PackageManager 探测模块存在</string>
|
||||
<string name="settings_anti_dev_title">底层模拟标志脱敏</string>
|
||||
<string name="settings_anti_dev_desc">在对象内存中实时抹除 isMock 与 mIsFromMockProvider 标志,消除模拟痕迹</string>
|
||||
|
||||
|
||||
<!-- 版本与更新 -->
|
||||
<string name="home_version_card_title">当前版本</string>
|
||||
<string name="home_version_name">v1.0.0</string>
|
||||
<string name="home_version_name">v1.2.2</string>
|
||||
<string name="home_check_updates_btn">检查更新</string>
|
||||
<string name="home_auto_check_update_title">启动时自动检查更新</string>
|
||||
<string name="home_auto_check_update_desc">每次进入软件自动联网检测 GitHub 最新版本</string>
|
||||
<string name="home_auto_check_update_desc">每次进入软件自动联网检测最新版本</string>
|
||||
<string name="home_checking_update">正在检查更新…</string>
|
||||
<string name="home_update_available_title">发现新版本: %1$s</string>
|
||||
<string name="home_update_dialog_msg">OpenLoc 已在 GitHub 发布最新版本,欢迎前往下载更新。</string>
|
||||
<string name="home_update_dialog_msg">OpenLoc 已发布最新版本,欢迎前往下载更新。</string>
|
||||
<string name="home_update_btn_go">前往更新</string>
|
||||
<string name="home_update_btn_later">稍后</string>
|
||||
<string name="home_check_update_failed">检查更新失败,请检查网络</string>
|
||||
<string name="home_already_latest">当前已是最新版本 (%1$s)</string>
|
||||
|
||||
<!-- 关于与更新 -->
|
||||
<string name="section_about">关于</string>
|
||||
<string name="btn_back">返回</string>
|
||||
<string name="about_author">作者:%1$s</string>
|
||||
<string name="about_app_version">版本</string>
|
||||
<string name="about_check_updates">检查更新</string>
|
||||
<string name="about_latest_version">当前已是最新版本</string>
|
||||
<string name="checking_updates">正在检查更新…</string>
|
||||
<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>
|
||||
|
||||
<!-- 通知设置 -->
|
||||
<string name="settings_category_notification">通知设置</string>
|
||||
<string name="settings_notification_enabled_title">状态栏常驻通知</string>
|
||||
<string name="settings_notification_enabled_desc">开启后,虚拟定位运行时将在任务栏常驻显示软件图标、名称、当前位置及运动参数</string>
|
||||
<string name="notification_title_format">OpenLoc · %1$s</string>
|
||||
<string name="notification_mode_running">跑步模式</string>
|
||||
<string name="notification_mode_static">定点模拟</string>
|
||||
<string name="notification_location_unnamed">自定义坐标</string>
|
||||
<string name="notification_coord_line">纬度: %1$.5f 经度: %2$.5f</string>
|
||||
<string name="notification_speed_bearing_line">速度: %1$.2f m/s 航向: %2$.0f°</string>
|
||||
<string name="notification_accel_line">X加速度: %1$.2f Y加速度: %2$.2f Z加速度: %3$.2f</string>
|
||||
</resources>
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@
|
||||
<string name="location_coords_copied">已复制坐标到剪贴板</string>
|
||||
<string name="location_reset_current">回到原位</string>
|
||||
<string name="location_located_to_real">已定位到当前真实位置</string>
|
||||
<string name="location_mock_disabled_prompt">虚拟定位未开启,请先开启虚拟定位</string>
|
||||
<string name="location_search_back">返回</string>
|
||||
<string name="location_search_clear">清空</string>
|
||||
<string name="location_search_history">搜索历史</string>
|
||||
@@ -162,24 +163,64 @@
|
||||
<string name="settings_anti_network_desc">脱敏基站小区与 Wi-Fi BSSID,拦截运营商基站监听,杜绝云端指纹库反查真实物理地址</string>
|
||||
<string name="settings_anti_sensor_title">传感器手持生理拟真</string>
|
||||
<string name="settings_anti_sensor_desc">向加速度计注入生物力学生理微颤,打破桌面绝对静止特征,满足步态与姿态校验</string>
|
||||
<string name="settings_anti_stealth_title">堆栈与模块自隐匿</string>
|
||||
<string name="settings_anti_stealth_desc">过滤调用栈中的 Xposed 与 OpenLoc 栈帧,并对目标应用隐藏模块包名</string>
|
||||
<string name="settings_anti_dev_title">开发者选项伪装</string>
|
||||
<string name="settings_anti_dev_desc">对目标应用伪装为未开启开发者模式、未开启 USB 调试与未开启模拟位置</string>
|
||||
<string name="settings_anti_stealth_title">模块包名自隐匿</string>
|
||||
<string name="settings_anti_stealth_desc">对目标应用隐藏 OpenLoc 安装包名,防止通过 PackageManager 探测模块存在</string>
|
||||
<string name="settings_anti_dev_title">底层模拟标志脱敏</string>
|
||||
<string name="settings_anti_dev_desc">在对象内存中实时抹除 isMock 与 mIsFromMockProvider 标志,消除模拟痕迹</string>
|
||||
|
||||
|
||||
<!-- 版本与更新 -->
|
||||
<string name="home_version_card_title">当前版本</string>
|
||||
<string name="home_version_name">v1.0.0</string>
|
||||
<string name="home_version_name">v1.2.2</string>
|
||||
<string name="home_check_updates_btn">检查更新</string>
|
||||
<string name="home_auto_check_update_title">启动时自动检查更新</string>
|
||||
<string name="home_auto_check_update_desc">每次进入软件自动联网检测 GitHub 最新版本</string>
|
||||
<string name="home_auto_check_update_desc">每次进入软件自动联网检测最新版本</string>
|
||||
<string name="home_checking_update">正在检查更新…</string>
|
||||
<string name="home_update_available_title">发现新版本: %1$s</string>
|
||||
<string name="home_update_dialog_msg">OpenLoc 已在 GitHub 发布最新版本,欢迎前往下载更新。</string>
|
||||
<string name="home_update_dialog_msg">OpenLoc 已发布最新版本,欢迎前往下载更新。</string>
|
||||
<string name="home_update_btn_go">前往更新</string>
|
||||
<string name="home_update_btn_later">稍后</string>
|
||||
<string name="home_check_update_failed">检查更新失败,请检查网络</string>
|
||||
<string name="home_already_latest">当前已是最新版本 (%1$s)</string>
|
||||
|
||||
<!-- 关于与更新 -->
|
||||
<string name="section_about">关于</string>
|
||||
<string name="btn_back">返回</string>
|
||||
<string name="about_author">作者:%1$s</string>
|
||||
<string name="about_app_version">版本</string>
|
||||
<string name="about_check_updates">检查更新</string>
|
||||
<string name="about_latest_version">当前已是最新版本</string>
|
||||
<string name="checking_updates">正在检查更新…</string>
|
||||
<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>
|
||||
|
||||
<!-- 通知设置 -->
|
||||
<string name="settings_category_notification">通知设置</string>
|
||||
<string name="settings_notification_enabled_title">状态栏常驻通知</string>
|
||||
<string name="settings_notification_enabled_desc">开启后,虚拟定位运行时将在任务栏常驻显示软件图标、名称、当前位置及运动参数</string>
|
||||
<string name="notification_title_format">OpenLoc · %1$s</string>
|
||||
<string name="notification_mode_running">跑步模式</string>
|
||||
<string name="notification_mode_static">定点模拟</string>
|
||||
<string name="notification_location_unnamed">自定义坐标</string>
|
||||
<string name="notification_coord_line">纬度: %1$.5f 经度: %2$.5f</string>
|
||||
<string name="notification_speed_bearing_line">速度: %1$.2f m/s 航向: %2$.0f°</string>
|
||||
<string name="notification_accel_line">X加速度: %1$.2f Y加速度: %2$.2f Z加速度: %3$.2f</string>
|
||||
</resources>
|
||||
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string-array name="xposed_scope">
|
||||
<!-- 勾选 Android 系统实现整机全局免指定拦截 -->
|
||||
<!-- 核心系统框架 -->
|
||||
<item>android</item>
|
||||
<!-- 勾选模块自身实现激活状态自检 -->
|
||||
<!-- 模块自身激活自检 -->
|
||||
<item>com.lzxnone.openloc</item>
|
||||
<!-- 小米 MIUI / HyperOS 独立高精融合定位守护进程(小米机型核心命门) -->
|
||||
<item>com.xiaomi.location.fused</item>
|
||||
<!-- 小米网络定位服务 (Metok NLP,基站与Wi-Fi定位核心) -->
|
||||
<item>com.xiaomi.metoknlp</item>
|
||||
<!-- Android 原生与高通底层系统融合定位守护进程 -->
|
||||
<item>com.android.location.fused</item>
|
||||
<!-- OPPO / 一加自研系统融合定位守护进程 -->
|
||||
<item>com.oplus.location</item>
|
||||
<!-- 电话与基站管理服务(阻断硬件基站塔反查) -->
|
||||
<item>com.android.phone</item>
|
||||
<!-- 蓝牙 BLE 信标扫描服务(阻断商场 iBeacon 反查) -->
|
||||
<item>com.android.bluetooth</item>
|
||||
</string-array>
|
||||
</resources>
|
||||
@@ -54,6 +54,7 @@
|
||||
<string name="location_coords_copied">Coordinates copied to clipboard</string>
|
||||
<string name="location_reset_current">Reset to current location</string>
|
||||
<string name="location_located_to_real">Located to current position</string>
|
||||
<string name="location_mock_disabled_prompt">Virtual location is not enabled, please enable it first</string>
|
||||
<string name="location_search_back">Back</string>
|
||||
<string name="location_search_clear">Clear</string>
|
||||
<string name="location_search_history">Recent Searches</string>
|
||||
@@ -162,22 +163,62 @@
|
||||
<string name="settings_anti_network_desc">Camouflage cell tower and Wi-Fi BSSID to prevent cloud reverse geolocation lookup</string>
|
||||
<string name="settings_anti_sensor_title">Handheld Motion Sensor Simulation</string>
|
||||
<string name="settings_anti_sensor_desc">Inject subtle physiological micro-tremor into accelerometer readings to mimic active human hand-holding</string>
|
||||
<string name="settings_anti_stealth_title">Stack Trace & Module Stealth</string>
|
||||
<string name="settings_anti_stealth_desc">Sanitize call stack traces (filter Xposed/OpenLoc frames) and hide module package from target apps</string>
|
||||
<string name="settings_anti_dev_title">Developer Settings Camouflage</string>
|
||||
<string name="settings_anti_dev_desc">Disguise developer mode, USB debugging, and mock location as disabled for target apps</string>
|
||||
<string name="settings_anti_stealth_title">Module Package Stealth</string>
|
||||
<string name="settings_anti_stealth_desc">Hide OpenLoc package from target apps to prevent package scanning detection</string>
|
||||
<string name="settings_anti_dev_title">Mock Flag Sanitization</string>
|
||||
<string name="settings_anti_dev_desc">Sanitize isMock and mIsFromMockProvider flags in Location objects</string>
|
||||
|
||||
|
||||
<!-- Version & Updates -->
|
||||
<string name="home_version_card_title">Current Version</string>
|
||||
<string name="home_version_name">v1.0.0</string>
|
||||
<string name="home_version_name">v1.2.2</string>
|
||||
<string name="home_check_updates_btn">Check for Updates</string>
|
||||
<string name="home_auto_check_update_title">Auto Check on Launch</string>
|
||||
<string name="home_auto_check_update_desc">Automatically check for new releases when opening the app</string>
|
||||
<string name="home_checking_update">Checking for updates…</string>
|
||||
<string name="home_update_available_title">New Version Available: %1$s</string>
|
||||
<string name="home_update_dialog_msg">A new version of OpenLoc has been released on GitHub.</string>
|
||||
<string name="home_update_dialog_msg">A new version of OpenLoc has been released.</string>
|
||||
<string name="home_update_btn_go">Go to Update</string>
|
||||
<string name="home_update_btn_later">Later</string>
|
||||
<string name="home_check_update_failed">Failed to check for updates, please check network</string>
|
||||
<string name="home_already_latest">Already the latest version (%1$s)</string>
|
||||
|
||||
<!-- About & Updates -->
|
||||
<string name="section_about">About</string>
|
||||
<string name="btn_back">Back</string>
|
||||
<string name="about_author">Author: %1$s</string>
|
||||
<string name="about_app_version">Version</string>
|
||||
<string name="about_check_updates">Check for Updates</string>
|
||||
<string name="about_latest_version">Already up to date</string>
|
||||
<string name="checking_updates">Checking for updates…</string>
|
||||
<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>
|
||||
|
||||
<!-- Notification Settings -->
|
||||
<string name="settings_category_notification">Notification Settings</string>
|
||||
<string name="settings_notification_enabled_title">Status Bar Notification</string>
|
||||
<string name="settings_notification_enabled_desc">Show app icon, mock location, and motion parameters in a persistent notification while mock location is active</string>
|
||||
<string name="notification_title_format">OpenLoc · %1$s</string>
|
||||
<string name="notification_mode_running">Running Mode</string>
|
||||
<string name="notification_mode_static">Static Mock</string>
|
||||
<string name="notification_location_unnamed">Custom Point</string>
|
||||
<string name="notification_coord_line">Lat: %1$.5f Lng: %2$.5f</string>
|
||||
<string name="notification_speed_bearing_line">Speed: %1$.2f m/s Bearing: %2$.0f°</string>
|
||||
<string name="notification_accel_line">X Accel: %1$.2f Y Accel: %2$.2f Z Accel: %3$.2f</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,104 @@
|
||||
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
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class HookSafetyTest {
|
||||
|
||||
@Test
|
||||
fun testMockConfigGlobalMode() {
|
||||
val config = MockConfig(
|
||||
isEnabled = true,
|
||||
mode = "GLOBAL"
|
||||
)
|
||||
assertTrue(config.shouldMock("com.tencent.mm"))
|
||||
assertTrue(config.shouldMock("com.autonavi.minimap"))
|
||||
assertTrue(config.shouldMock("any.package.name"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMockConfigDisabled() {
|
||||
val config = MockConfig(
|
||||
isEnabled = false,
|
||||
mode = "GLOBAL"
|
||||
)
|
||||
assertFalse(config.shouldMock("com.tencent.mm"))
|
||||
assertFalse(config.shouldMock("any.package.name"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMockConfigWhitelistMode() {
|
||||
val config = MockConfig(
|
||||
isEnabled = true,
|
||||
mode = "WHITELIST",
|
||||
whitelist = setOf("com.tencent.mm", "com.eg.android.AlipayGphone")
|
||||
)
|
||||
assertTrue(config.shouldMock("com.tencent.mm"))
|
||||
assertTrue(config.shouldMock("com.eg.android.AlipayGphone"))
|
||||
assertFalse(config.shouldMock("com.autonavi.minimap"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMockConfigBlacklistMode() {
|
||||
val config = MockConfig(
|
||||
isEnabled = true,
|
||||
mode = "BLACKLIST",
|
||||
blacklist = setOf("com.google.android.gms")
|
||||
)
|
||||
assertFalse(config.shouldMock("com.google.android.gms"))
|
||||
assertTrue(config.shouldMock("com.tencent.mm"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDangerousHooksAreCompletelyRemoved() {
|
||||
val clazz = AntiDetectionHook::class.java
|
||||
val methodNames = clazz.declaredMethods.map { it.name }
|
||||
|
||||
// Ensure fatal bootloop hooks are NOT present
|
||||
assertFalse("hookStackTrace must be completely removed", methodNames.contains("hookStackTrace"))
|
||||
assertFalse("hookSettingsCamouflage must be completely removed", methodNames.contains("hookSettingsCamouflage"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testHardwareAndSystemProvidersAreExemptFromMock() {
|
||||
val config = MockConfig(
|
||||
isEnabled = true,
|
||||
mode = "GLOBAL"
|
||||
)
|
||||
assertFalse(config.shouldMock("com.lzxnone.openloc"))
|
||||
assertFalse(config.shouldMock("android"))
|
||||
assertFalse(config.shouldMock("com.android.server.location"))
|
||||
assertFalse(config.shouldMock("com.android.server.location.gnss.hal.Gpo4Client"))
|
||||
assertFalse(config.shouldMock("com.qualcomm.location"))
|
||||
assertFalse(config.shouldMock("com.qti.location"))
|
||||
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