Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
253f3c72b1 | ||
|
|
7b0d5b802d | ||
|
|
32fa4a611a | ||
|
|
6ffa7d8108 | ||
|
|
07abd416b6 | ||
|
|
ee7b7d3666 | ||
|
|
02a206d384 | ||
|
|
8b49607efe | ||
|
|
2f5b852e00 | ||
|
|
80bba05ecf | ||
|
|
a341d862c2 | ||
|
|
b21966e5b5 | ||
|
|
4d26ffae06 | ||
|
|
22d3197309 | ||
|
|
7ad462a524 | ||
|
|
d615f5d030 | ||
|
|
4b6ae12df6 |
No files matched your search
@@ -0,0 +1,76 @@
|
||||
name: Release OpenLoc APKs
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build & Publish Release
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
cache: 'gradle'
|
||||
|
||||
- name: Grant Execute Permission for Gradlew
|
||||
run: chmod +x gradlew
|
||||
|
||||
- name: Restore Keystore from Secrets (If Configured)
|
||||
env:
|
||||
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
|
||||
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
|
||||
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
|
||||
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
|
||||
run: |
|
||||
if [ -n "$KEYSTORE_BASE64" ]; then
|
||||
echo "Restoring official keystore..."
|
||||
echo "$KEYSTORE_BASE64" | base64 -d > app/openloc.jks
|
||||
cat <<EOF > keystore.properties
|
||||
storeFile=openloc.jks
|
||||
storePassword=${KEYSTORE_PASSWORD}
|
||||
keyAlias=${KEY_ALIAS}
|
||||
keyPassword=${KEY_PASSWORD}
|
||||
EOF
|
||||
else
|
||||
echo "No custom keystore secret provided, fallback signing will be used."
|
||||
fi
|
||||
|
||||
- name: Run Tests & Build Release APKs
|
||||
run: ./gradlew testDebugUnitTest assembleRelease --stacktrace
|
||||
|
||||
- name: Prepare Architecture Assets
|
||||
run: |
|
||||
TAG_NAME="${GITHUB_REF_NAME:-latest}"
|
||||
cd app/build/outputs/apk/release/
|
||||
cp app-universal-release.apk "OpenLoc-${TAG_NAME}-universal.apk"
|
||||
cp app-arm64-v8a-release.apk "OpenLoc-${TAG_NAME}-arm64-v8a.apk"
|
||||
cp app-armeabi-v7a-release.apk "OpenLoc-${TAG_NAME}-armeabi-v7a.apk"
|
||||
cp app-x86_64-release.apk "OpenLoc-${TAG_NAME}-x86_64.apk"
|
||||
cp app-x86-release.apk "OpenLoc-${TAG_NAME}-x86.apk"
|
||||
ls -la OpenLoc-*.apk
|
||||
|
||||
- name: Publish GitHub Release & Upload Assets
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: |
|
||||
app/build/outputs/apk/release/OpenLoc-*-universal.apk
|
||||
app/build/outputs/apk/release/OpenLoc-*-arm64-v8a.apk
|
||||
app/build/outputs/apk/release/OpenLoc-*-armeabi-v7a.apk
|
||||
app/build/outputs/apk/release/OpenLoc-*-x86_64.apk
|
||||
app/build/outputs/apk/release/OpenLoc-*-x86.apk
|
||||
generate_release_notes: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -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>
|
||||
|
||||
# OpenLoc
|
||||
<h1 align="center">OpenLoc</h1>
|
||||
|
||||
<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.
|
||||
+12
-3
@@ -18,8 +18,8 @@ android {
|
||||
applicationId = "com.lzxnone.openloc"
|
||||
minSdk = 28
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "1.0.0"
|
||||
versionCode = 6
|
||||
versionName = "1.2.3"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
@@ -46,6 +46,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 +60,8 @@ android {
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
@@ -68,6 +76,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.**
|
||||
@@ -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,8 +1,11 @@
|
||||
package com.lzxnone.openloc.core.util
|
||||
|
||||
import com.lzxnone.openloc.BuildConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
@@ -10,94 +13,64 @@ import java.net.URL
|
||||
* 版本更新信息
|
||||
*/
|
||||
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
|
||||
)
|
||||
|
||||
/**
|
||||
* GitHub Releases 版本更新检查器
|
||||
*/
|
||||
object UpdateChecker {
|
||||
private const val GITHUB_API_URL = "https://api.github.com/repos/lzxnone/openloc/releases/latest"
|
||||
|
||||
/**
|
||||
* 检查 GitHub 是否有新版本
|
||||
*/
|
||||
suspend fun checkUpdate(currentVersion: String = "v1.0.0"): Result<UpdateInfo> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val url = URL(GITHUB_API_URL)
|
||||
val conn = (url.openConnection() as HttpURLConnection).apply {
|
||||
requestMethod = "GET"
|
||||
connectTimeout = 8000
|
||||
readTimeout = 8000
|
||||
setRequestProperty("Accept", "application/vnd.github.v3+json")
|
||||
setRequestProperty("User-Agent", "OpenLoc-App")
|
||||
val downloadUrl: String,
|
||||
val apkSize: String = ""
|
||||
) {
|
||||
val hasUpdate: Boolean
|
||||
get() = versionCode > BuildConfig.VERSION_CODE
|
||||
}
|
||||
|
||||
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()
|
||||
/**
|
||||
* VPS 节点自建版本更新检查器
|
||||
*/
|
||||
object UpdateChecker {
|
||||
private const val UPDATE_URL = "https://update.lzxnone.cloud/openloc/version.json"
|
||||
|
||||
/**
|
||||
* 检查是否有新版本
|
||||
*/
|
||||
suspend fun checkUpdate(): Result<UpdateInfo> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val url = URL(UPDATE_URL)
|
||||
val connection = (url.openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 8000
|
||||
readTimeout = 8000
|
||||
requestMethod = "GET"
|
||||
setRequestProperty("Accept", "application/json")
|
||||
setRequestProperty("User-Agent", "OpenLoc-Android")
|
||||
}
|
||||
|
||||
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 json = JSONObject(response)
|
||||
val versionCode = json.optLong("versionCode", 0L)
|
||||
val versionName = json.optString("versionName", "")
|
||||
val changelog = json.optString("changelog", "")
|
||||
val downloadUrl = json.optString("downloadUrl", "")
|
||||
val apkSize = json.optString("apkSize", "")
|
||||
|
||||
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"
|
||||
versionCode = versionCode,
|
||||
versionName = versionName,
|
||||
changelog = changelog,
|
||||
downloadUrl = downloadUrl,
|
||||
apkSize = apkSize
|
||||
)
|
||||
)
|
||||
} 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")
|
||||
|
||||
val remoteParts = cleanRemote.split(".").mapNotNull { it.toIntOrNull() }
|
||||
val currentParts = cleanCurrent.split(".").mapNotNull { it.toIntOrNull() }
|
||||
|
||||
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
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
package com.lzxnone.openloc.data.preference
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.SharedPreferences
|
||||
import android.location.LocationManager
|
||||
import android.os.Bundle
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
@@ -11,7 +14,9 @@ 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
|
||||
|
||||
enum class ThemeMode(@param:StringRes val titleRes: Int) {
|
||||
SYSTEM(R.string.settings_theme_mode_system),
|
||||
@@ -86,6 +91,8 @@ object AppPreferences {
|
||||
private const val KEY_SERVICE_ENABLED = "mock_service_enabled"
|
||||
|
||||
private lateinit var prefs: SharedPreferences
|
||||
@Volatile
|
||||
private var appContext: Context? = null
|
||||
|
||||
var themeMode by mutableStateOf(ThemeMode.SYSTEM)
|
||||
private set
|
||||
@@ -115,6 +122,7 @@ object AppPreferences {
|
||||
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 +130,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
|
||||
@@ -181,6 +192,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)
|
||||
@@ -227,10 +239,41 @@ object AppPreferences {
|
||||
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)
|
||||
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
|
||||
fun syncConfigToSystem() {
|
||||
try {
|
||||
val ctx = appContext ?: return
|
||||
val lm = ctx.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return
|
||||
TraceLogger.i("AppPreferences", "syncConfigToSystem -> Enabled=$isServiceEnabled, Mock=($mockLatitude, $mockLongitude), Mode=${appMockMode.name}, Whitelist=${whitelistApps.size}, Blacklist=${blacklistApps.size}")
|
||||
val bundle = Bundle().apply {
|
||||
putBoolean(GlobalMockMemory.EXTRA_ENABLED, isServiceEnabled)
|
||||
putDouble(GlobalMockMemory.EXTRA_LATITUDE, mockLatitude)
|
||||
putDouble(GlobalMockMemory.EXTRA_LONGITUDE, mockLongitude)
|
||||
putDouble(GlobalMockMemory.EXTRA_ALTITUDE, 50.0)
|
||||
putFloat(GlobalMockMemory.EXTRA_ACCURACY, 5.0f)
|
||||
putString(GlobalMockMemory.EXTRA_LOCATION_NAME, mockLocationName)
|
||||
putString(GlobalMockMemory.EXTRA_MODE, appMockMode.name)
|
||||
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 {
|
||||
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 +288,8 @@ object AppPreferences {
|
||||
.putString(KEY_MOCK_LONGITUDE, longitude.toString())
|
||||
.putString(KEY_MOCK_LOCATION_NAME, mockLocationName)
|
||||
.apply()
|
||||
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun updateThemeMode(mode: ThemeMode) {
|
||||
@@ -271,6 +316,7 @@ object AppPreferences {
|
||||
fun updateServiceEnabled(enabled: Boolean) {
|
||||
isServiceEnabled = enabled
|
||||
prefs.edit().putBoolean(KEY_SERVICE_ENABLED, enabled).apply()
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun addSearchHistory(item: SearchResult) {
|
||||
@@ -425,11 +471,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 +492,7 @@ object AppPreferences {
|
||||
fun updateBlacklistApps(packages: Set<String>) {
|
||||
blacklistApps = packages
|
||||
savePackageSet(KEY_BLACKLIST_APPS, packages)
|
||||
syncConfigToSystem()
|
||||
}
|
||||
|
||||
fun toggleBlacklistApp(packageName: String) {
|
||||
@@ -479,36 +528,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,14 @@ 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.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 +18,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 +26,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 +79,38 @@ 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
|
||||
}
|
||||
// 在 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)
|
||||
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 +118,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,608 @@
|
||||
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.TraceLogger
|
||||
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
|
||||
|
||||
/**
|
||||
* 国内三大巨头自研底层 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>())
|
||||
|
||||
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
|
||||
if (packageName == "com.lzxnone.openloc") return
|
||||
|
||||
hookTencentLocationSDK(classLoader, packageName)
|
||||
hookBaiduLocationSDK(classLoader, packageName)
|
||||
hookAmapLocationSDK(classLoader, packageName)
|
||||
}
|
||||
|
||||
// ====================================================================================
|
||||
// 1. 腾讯定位 SDK (TencentLocationManager / TencentLocationListener / SosoInterface)
|
||||
// ====================================================================================
|
||||
|
||||
private fun hookTencentLocationSDK(classLoader: ClassLoader, packageName: String) {
|
||||
// (1) 现代腾讯定位 SDK:com.tencent.map.geolocation.TencentLocationManager
|
||||
val tencentManagerClass = try {
|
||||
XposedHelpers.findClass("com.tencent.map.geolocation.TencentLocationManager", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
if (tencentManagerClass != null) {
|
||||
TraceLogger.i("ThirdPartyNLP", "[$packageName] Detected modern TencentLocationManager, arming Tencent hooks...")
|
||||
|
||||
for (method in tencentManagerClass.declaredMethods) {
|
||||
when (method.name) {
|
||||
"requestLocationUpdates", "requestSingleFreshLocation" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
|
||||
wrapTencentListenerArgs(param.args, classLoader, packageName)
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
"removeUpdates" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val originalListener = param.args.getOrNull(0) ?: return
|
||||
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 mockLoc = createMockTencentLocation(classLoader)
|
||||
if (mockLoc != null) {
|
||||
TraceLogger.w("ThirdPartyNLP", "[$packageName] TencentLocationManager.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) {
|
||||
val listenerInterface = try {
|
||||
XposedHelpers.findClass("com.tencent.map.geolocation.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
|
||||
}
|
||||
val proxy = tencentListenerProxyMap.getOrPut(arg) {
|
||||
Proxy.newProxyInstance(
|
||||
classLoader,
|
||||
arrayOf(listenerInterface),
|
||||
TencentListenerInvocationHandler(arg, classLoader, packageName)
|
||||
)
|
||||
}
|
||||
args[i] = proxy
|
||||
TraceLogger.d("ThirdPartyNLP", "[$packageName] Wrapped TencentLocationListener at index $i with dynamic proxy")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class TencentListenerInvocationHandler(
|
||||
private val originalListener: Any,
|
||||
private val classLoader: ClassLoader,
|
||||
private val packageName: String
|
||||
) : InvocationHandler {
|
||||
override fun invoke(proxy: Any?, method: Method, args: Array<Any?>?): Any? {
|
||||
if (method.name == "onLocationChanged") {
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
val mockLoc = createMockTencentLocation(classLoader)
|
||||
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] TencentLocationListener.onLocationChanged -> REPLACED with Mock Location (${GlobalMockMemory.latitude}, ${GlobalMockMemory.longitude})")
|
||||
}
|
||||
}
|
||||
}
|
||||
return method.invoke(originalListener, *(args ?: emptyArray()))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态反射构建标准 TencentLocation 接口代理实例
|
||||
*/
|
||||
private fun createMockTencentLocation(classLoader: ClassLoader): Any? {
|
||||
val locationInterface = try {
|
||||
XposedHelpers.findClass("com.tencent.map.geolocation.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...")
|
||||
|
||||
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)) {
|
||||
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) {}
|
||||
}
|
||||
"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)) {
|
||||
param.result = 61 // 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?) {
|
||||
private fun hookLocationEntityFlags(classLoader: ClassLoader) {
|
||||
val locationClass = try {
|
||||
XposedHelpers.findClass("android.location.Location", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: return
|
||||
|
||||
for (method in locationClass.declaredMethods) {
|
||||
if (method.name == "isFromMockProvider" || method.name == "isMock") {
|
||||
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
|
||||
|
||||
@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
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
param.result = false
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
if (hasForbidden) {
|
||||
param.result = originalElements.filter { !isForbiddenClassName(it.className) }.toTypedArray()
|
||||
}
|
||||
} finally {
|
||||
isSanitizingStack.set(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}")
|
||||
}
|
||||
}
|
||||
|
||||
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. PackageManager 模块自隐匿
|
||||
* 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) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
|
||||
// 开启模拟定位时,不向应用分发真实硬件原始 NMEA 报文
|
||||
param.result = true
|
||||
}
|
||||
}
|
||||
})
|
||||
} 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 卫星心跳
|
||||
* 兼容老版本 SDK 的 GpsStatus.Listener,恒定返回已极速定星状态
|
||||
*/
|
||||
private fun hookGnssStatusCallbacks(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
private fun hookGpsStatusLegacy(packageName: String) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
} 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 定时卫星仿真分发调度(针对无真实卫星信号、室内等环境兜底)
|
||||
*/
|
||||
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?) {
|
||||
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,204 @@ import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
|
||||
import com.lzxnone.openloc.hook.util.LocationSimulator
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import com.lzxnone.openloc.core.util.TraceLogger
|
||||
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
|
||||
|
||||
/**
|
||||
* 原生定位服务 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>())
|
||||
|
||||
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
|
||||
// 关键安全防线:针对 OpenLoc 自身绝对放行,确保可无阻获取硬件真实 GPS 回到真实定位点
|
||||
if (packageName == "com.lzxnone.openloc") return
|
||||
|
||||
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 hookClientLocationManager(classLoader: ClassLoader, packageName: String) {
|
||||
val lmClass = LocationManager::class.java
|
||||
|
||||
// Android 12 (API 31)+ isMock() 恒返回 false
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
// 1. getLastKnownLocation 与 getLastLocation 拦截(GhostMapX 经典实现)
|
||||
val getLastMethods = listOf("getLastKnownLocation", "getLastLocation")
|
||||
for (methodName in getLastMethods) {
|
||||
try {
|
||||
XposedHelpers.findAndHookMethod(
|
||||
Location::class.java,
|
||||
"isMock",
|
||||
object : XC_MethodReplacement() {
|
||||
override fun replaceHookedMethod(param: MethodHookParam?): Any {
|
||||
return false
|
||||
}
|
||||
}
|
||||
)
|
||||
} 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() {
|
||||
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
|
||||
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
|
||||
|
||||
// (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)
|
||||
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)}")
|
||||
}
|
||||
})
|
||||
} 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}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
XposedBridge.hookAllMethods(lmClass, "isProviderEnabled", 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
|
||||
)
|
||||
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>)
|
||||
// 3. requestLocationUpdates 与 requestSingleUpdate 拦截
|
||||
val requestMethods = listOf("requestLocationUpdates", "requestSingleUpdate")
|
||||
for (methodName in requestMethods) {
|
||||
try {
|
||||
XposedHelpers.findAndHookMethod(
|
||||
clazz,
|
||||
"onLocationChanged",
|
||||
List::class.java,
|
||||
object : XC_MethodHook() {
|
||||
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
|
||||
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)
|
||||
// 查找 LocationListener 参数并挂钩其 onLocationChanged
|
||||
for (arg in param.args) {
|
||||
if (arg is LocationListener) {
|
||||
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) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Android 11+ / 12+ 单次定位 getCurrentLocation 拦截
|
||||
*/
|
||||
private fun hookGetCurrentLocation(contextProvider: () -> Context?) {
|
||||
val methods = LocationManager::class.java.declaredMethods
|
||||
for (method in methods) {
|
||||
if (method.name == "getCurrentLocation") {
|
||||
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)) return
|
||||
|
||||
// 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
|
||||
|
||||
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()))
|
||||
}
|
||||
}
|
||||
param.args[lastIndex] = proxy
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截系统 Binder 回调的传输层 Transport(GhostMapX 关键手段)
|
||||
*/
|
||||
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.hookAllMethods(clazz, "onLocation", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
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")
|
||||
|
||||
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) {}
|
||||
|
||||
// Hook onLocationChanged
|
||||
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("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))
|
||||
}
|
||||
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)
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
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 de.robv.android.xposed.XC_MethodHook
|
||||
import de.robv.android.xposed.XposedBridge
|
||||
import de.robv.android.xposed.XposedHelpers
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* 物理动力学传感器协同与生理微颤拟真拦截器
|
||||
*
|
||||
* 核心目标:
|
||||
* 1. 拦截 SensorManager.registerListener,捕获应用注册的传感器监听器
|
||||
* 2. 针对加速度计 (TYPE_ACCELEROMETER) 与重力传感器 (TYPE_GRAVITY),动态注入人体手持特有的生物力学生理颤动(Physiological Tremor)
|
||||
* 3. 防止加速度方差几乎为 0 导致被高精风控判定为“放置在桌面的静止刚体设备”
|
||||
* 4. 针对陀螺仪 (TYPE_GYROSCOPE) 注入极细微的手持角速度扰动
|
||||
*/
|
||||
object SensorHook {
|
||||
|
||||
private val hookedListenerClasses = mutableSetOf<String>()
|
||||
|
||||
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) {
|
||||
hookSensorManager(contextProvider)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
XposedBridge.log("[OpenLoc] hookSensorManager error: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun hookSensorEventListenerClass(clazz: Class<*>, contextProvider: () -> Context?) {
|
||||
val className = clazz.name
|
||||
if (hookedListenerClasses.contains(className)) return
|
||||
hookedListenerClasses.add(className)
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,68 @@
|
||||
package com.lzxnone.openloc.hook.ipc
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
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 }
|
||||
|
||||
/**
|
||||
* 获取最新配置(带平滑缓存)
|
||||
* 获取最新配置(优先读取零延迟全局内存)
|
||||
*/
|
||||
fun getConfig(context: Context, force: Boolean = false): MockConfig {
|
||||
ensureReceiverRegistered(context)
|
||||
|
||||
// 1. 优先使用系统原生管道注入的全局静态内存
|
||||
if (GlobalMockMemory.isEnabled) {
|
||||
return MockConfig(
|
||||
isEnabled = GlobalMockMemory.isEnabled,
|
||||
latitude = GlobalMockMemory.latitude,
|
||||
longitude = GlobalMockMemory.longitude,
|
||||
altitude = GlobalMockMemory.altitude,
|
||||
accuracy = GlobalMockMemory.accuracy,
|
||||
bearing = GlobalMockMemory.bearing,
|
||||
speed = GlobalMockMemory.speed,
|
||||
mode = GlobalMockMemory.mode,
|
||||
whitelist = GlobalMockMemory.whitelist,
|
||||
blacklist = GlobalMockMemory.blacklist
|
||||
)
|
||||
}
|
||||
|
||||
val now = System.currentTimeMillis()
|
||||
if (!force && cachedConfig != null && (now - lastFetchTime < CACHE_DURATION_MS)) {
|
||||
return cachedConfig!!
|
||||
}
|
||||
|
||||
if (isFetching.get() == true) {
|
||||
return cachedConfig ?: MockConfig()
|
||||
}
|
||||
|
||||
isFetching.set(true)
|
||||
return try {
|
||||
val bundle = context.contentResolver.call(
|
||||
PROVIDER_URI,
|
||||
@@ -43,37 +76,66 @@ 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", 50.0),
|
||||
accuracy = bundle.getFloat("accuracy", 5.0f),
|
||||
bearing = bundle.getFloat("bearing", 0.0f),
|
||||
speed = bundle.getFloat("speed", 0.0f),
|
||||
mode = mode,
|
||||
whitelist = parseSet(whitelistJson),
|
||||
blacklist = parseSet(blacklistJson),
|
||||
isJitterEnabled = isJitter,
|
||||
isGnssSimulationEnabled = isGnss,
|
||||
isNetworkCamouflageEnabled = isNetwork,
|
||||
isSensorSimulationEnabled = isSensor,
|
||||
isStealthEnabled = isStealth,
|
||||
isDevCamouflageEnabled = isDevCamouflage
|
||||
blacklist = parseSet(blacklistJson)
|
||||
)
|
||||
cachedConfig = config
|
||||
lastFetchTime = now
|
||||
|
||||
// 如果通过 Provider 拉取成功且已开启,同步更新全局静态内存
|
||||
if (config.isEnabled) {
|
||||
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
|
||||
}
|
||||
|
||||
config
|
||||
} else {
|
||||
cachedConfig ?: MockConfig()
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
// 在目标尚未完全就绪或权限受限时的静默容错
|
||||
} catch (_: Throwable) {
|
||||
cachedConfig ?: MockConfig()
|
||||
} finally {
|
||||
isFetching.set(false)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
lastFetchTime = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
context.applicationContext.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED)
|
||||
} else {
|
||||
context.applicationContext.registerReceiver(receiver, filter)
|
||||
}
|
||||
isReceiverRegistered = true
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
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 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"
|
||||
|
||||
@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()
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
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 {
|
||||
return Location(provider).apply {
|
||||
latitude = this@GlobalMockMemory.latitude
|
||||
longitude = this@GlobalMockMemory.longitude
|
||||
altitude = this@GlobalMockMemory.altitude
|
||||
accuracy = this@GlobalMockMemory.accuracy
|
||||
bearing = this@GlobalMockMemory.bearing
|
||||
speed = this@GlobalMockMemory.speed
|
||||
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
|
||||
bearingAccuracyDegrees = 1.0f
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,35 @@
|
||||
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 blacklist: Set<String> = emptySet()
|
||||
) {
|
||||
/**
|
||||
* 判断指定应用包名是否应当生效虚拟定位
|
||||
*/
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,280 +1,576 @@
|
||||
package com.lzxnone.openloc.hook.system
|
||||
|
||||
import android.location.Location
|
||||
import android.os.Build
|
||||
import com.lzxnone.openloc.hook.model.MockConfig
|
||||
import com.lzxnone.openloc.hook.util.LocationSimulator
|
||||
import android.os.Binder
|
||||
import android.os.Bundle
|
||||
import android.os.IBinder
|
||||
import android.os.IInterface
|
||||
import com.lzxnone.openloc.core.util.TraceLogger
|
||||
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 org.xmlpull.v1.XmlPullParser
|
||||
import org.xmlpull.v1.XmlPullParserFactory
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.lang.reflect.Method
|
||||
import java.util.Collections
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* 针对 Android 系统框架 (system_server / android) 的系统级全局 Hook
|
||||
* system_server 底层服务核心拦截器(100% 工业级对齐 GhostMapX Lcf/LP3/LXe 架构)
|
||||
*
|
||||
* 核心原理:
|
||||
* 在 Android 操作系统中,整机所有应用调用 LocationManager 获取位置,
|
||||
* 底层最终全部汇集到 system_server 进程里的 LocationManagerService 中进行统一调度和分发。
|
||||
*
|
||||
* 只要在 LSPosed 作用域中勾选了【Android 系统 (android)】,本拦截器就会在系统服务底层
|
||||
* 将发往所有应用的位置数据全部篡改并洗白。
|
||||
* 手机里无论是已有应用还是将来新下载的应用,统统无需单独指定,直接全局生效!
|
||||
* 核心机制说明:
|
||||
* 1. 绝对不篡改底层硬件驱动和物理 GPS 缓冲区(不篡改 LocationProviderManager.onReportLocation),
|
||||
* 保证系统物理 GPS 随时纯净可用,OpenLoc 随时能读取真实设备坐标;
|
||||
* 2. 动态维护活跃 Binder 映射表(与 GhostMapX cf.a / cf.b / LP3 完全一致):
|
||||
* - activeListeners: ConcurrentHashMap<IBinder, String>(跟踪每个 ILocationListener 的所属目标包名)
|
||||
* - activeCallbacks: ConcurrentHashMap<IBinder, String>(跟踪每个 ILocationCallback 的所属目标包名)
|
||||
* - 当客户端注册监听时通过 IBinder.linkToDeath 监听生命周期;
|
||||
* 3. 在 onLocationChanged / onLocation 回调触发时:
|
||||
* - 通过 param.thisObject 提取对应的 IBinder 实例;
|
||||
* - 只有在 activeListeners / activeCallbacks 中明确登记的目标应用才替换入参为虚拟定位;
|
||||
* - OpenLoc 自身、系统进程以及未加入模拟名单的应用绝对放行真实定位,绝无交叉污染!
|
||||
* 4. 首帧秒推机制(GhostMapX Lcf.a: 56-112 行):
|
||||
* - 目标应用注册 requestLocationUpdates 的瞬间,立即反射调用 onLocationChanged 注入首帧,
|
||||
* 让应用(百度地图、高德、QQ)无需等待系统几秒甚至几分钟的搜星延迟,即刻获取定位!
|
||||
*/
|
||||
object SystemServerHook {
|
||||
|
||||
private const val PREF_FILE_PATH_1 = "/data/data/com.lzxnone.openloc/shared_prefs/openloc_prefs.xml"
|
||||
private const val PREF_FILE_PATH_2 = "/data/user/0/com.lzxnone.openloc/shared_prefs/openloc_prefs.xml"
|
||||
// 活跃监听器与其所属目标包名的映射表(以 IBinder 为 key,彻底消除 Class 静态闭包污染)
|
||||
private val activeListeners = ConcurrentHashMap<IBinder, String>()
|
||||
private val activeCallbacks = ConcurrentHashMap<IBinder, String>()
|
||||
|
||||
@Volatile
|
||||
private var lastReadTime = 0L
|
||||
@Volatile
|
||||
private var cachedConfig = MockConfig()
|
||||
|
||||
/**
|
||||
* 在 system_server 进程中直接读取 OpenLoc 的配置文件(system_server 具备最高读取权限)
|
||||
*/
|
||||
private fun readConfigDirectly(): MockConfig {
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - lastReadTime < 1500L) {
|
||||
return cachedConfig
|
||||
}
|
||||
|
||||
val file = listOf(File(PREF_FILE_PATH_1), File(PREF_FILE_PATH_2)).firstOrNull { it.exists() && it.canRead() }
|
||||
?: return cachedConfig
|
||||
|
||||
try {
|
||||
var isEnabled = false
|
||||
var lat = 39.908722
|
||||
var lng = 116.397496
|
||||
var mode = "GLOBAL"
|
||||
val whitelist = mutableSetOf<String>()
|
||||
val blacklist = mutableSetOf<String>()
|
||||
var isJitter = true
|
||||
var isGnss = true
|
||||
var isNetwork = true
|
||||
var isSensor = true
|
||||
var isStealth = true
|
||||
var isDevCamouflage = true
|
||||
|
||||
FileInputStream(file).use { fis ->
|
||||
val factory = XmlPullParserFactory.newInstance()
|
||||
val parser = factory.newPullParser()
|
||||
parser.setInput(fis, "UTF-8")
|
||||
|
||||
var eventType = parser.eventType
|
||||
while (eventType != XmlPullParser.END_DOCUMENT) {
|
||||
if (eventType == XmlPullParser.START_TAG) {
|
||||
val name = parser.getAttributeValue(null, "name")
|
||||
when (parser.name) {
|
||||
"boolean" -> {
|
||||
when (name) {
|
||||
"mock_service_enabled" -> {
|
||||
isEnabled = parser.getAttributeValue(null, "value") == "true"
|
||||
}
|
||||
"enable_jitter" -> {
|
||||
isJitter = parser.getAttributeValue(null, "value") == "true"
|
||||
}
|
||||
"enable_gnss_simulation" -> {
|
||||
isGnss = parser.getAttributeValue(null, "value") == "true"
|
||||
}
|
||||
"enable_network_camouflage" -> {
|
||||
isNetwork = parser.getAttributeValue(null, "value") == "true"
|
||||
}
|
||||
"enable_sensor_simulation" -> {
|
||||
isSensor = parser.getAttributeValue(null, "value") == "true"
|
||||
}
|
||||
"enable_stealth" -> {
|
||||
isStealth = parser.getAttributeValue(null, "value") == "true"
|
||||
}
|
||||
"enable_dev_camouflage" -> {
|
||||
isDevCamouflage = parser.getAttributeValue(null, "value") == "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
"string" -> {
|
||||
when (name) {
|
||||
"mock_latitude" -> {
|
||||
lat = parser.nextText()?.toDoubleOrNull() ?: lat
|
||||
}
|
||||
"mock_longitude" -> {
|
||||
lng = parser.nextText()?.toDoubleOrNull() ?: lng
|
||||
}
|
||||
"app_mock_mode" -> {
|
||||
mode = parser.nextText() ?: mode
|
||||
}
|
||||
"whitelist_apps" -> {
|
||||
parseJsonArrayToSet(parser.nextText(), whitelist)
|
||||
}
|
||||
"blacklist_apps" -> {
|
||||
parseJsonArrayToSet(parser.nextText(), blacklist)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
eventType = parser.next()
|
||||
}
|
||||
}
|
||||
|
||||
cachedConfig = MockConfig(
|
||||
isEnabled = isEnabled,
|
||||
latitude = lat,
|
||||
longitude = lng,
|
||||
mode = mode,
|
||||
whitelist = whitelist,
|
||||
blacklist = blacklist,
|
||||
isJitterEnabled = isJitter,
|
||||
isGnssSimulationEnabled = isGnss,
|
||||
isNetworkCamouflageEnabled = isNetwork,
|
||||
isSensorSimulationEnabled = isSensor,
|
||||
isStealthEnabled = isStealth,
|
||||
isDevCamouflageEnabled = isDevCamouflage
|
||||
)
|
||||
lastReadTime = now
|
||||
} catch (_: Throwable) {}
|
||||
|
||||
return cachedConfig
|
||||
}
|
||||
|
||||
private fun parseJsonArrayToSet(jsonStr: String?, target: MutableSet<String>) {
|
||||
if (jsonStr.isNullOrBlank()) return
|
||||
try {
|
||||
val array = org.json.JSONArray(jsonStr)
|
||||
for (i in 0 until array.length()) {
|
||||
target.add(array.getString(i))
|
||||
}
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
// 已挂钩 onLocationChanged 的类名集合,防止重复 Hook
|
||||
private val hookedListenerClasses = Collections.synchronizedSet(mutableSetOf<String>())
|
||||
private val hookedCallbackClasses = Collections.synchronizedSet(mutableSetOf<String>())
|
||||
// 已挂钩 Wi-Fi 服务的类名集合,防止重复 Hook
|
||||
private val hookedWifiClasses = Collections.synchronizedSet(mutableSetOf<String>())
|
||||
|
||||
fun hook(classLoader: ClassLoader) {
|
||||
XposedBridge.log("[OpenLoc] Initializing SystemServerHook for global mock location...")
|
||||
XposedBridge.log("[OpenLoc] [SystemServer] Initializing GhostMapX architecture in system_server...")
|
||||
|
||||
hookSystemLocationService(classLoader)
|
||||
hookLocationManagerService(classLoader)
|
||||
hookWifiService(classLoader)
|
||||
hookTelephonyRegistry(classLoader)
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截系统底层 LocationManagerService 的分发与获取逻辑
|
||||
*/
|
||||
private fun hookSystemLocationService(classLoader: ClassLoader) {
|
||||
val lmsClassNames = listOf(
|
||||
private fun hookLocationManagerService(classLoader: ClassLoader) {
|
||||
val lmsClasses = listOf(
|
||||
"com.android.server.location.LocationManagerService",
|
||||
"com.android.server.LocationManagerService"
|
||||
)
|
||||
|
||||
for (className in lmsClassNames) {
|
||||
val lmsClass = try {
|
||||
var lmsClass: Class<*>? = null
|
||||
for (className in lmsClasses) {
|
||||
lmsClass = try {
|
||||
XposedHelpers.findClass(className, classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: continue
|
||||
|
||||
hookLmsMethods(lmsClass)
|
||||
break
|
||||
}
|
||||
if (lmsClass != null) break
|
||||
}
|
||||
|
||||
// Android 12+ (API 31)+ 核心底层服务 LocationProviderManager 拦截
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
hookLocationProviderManager(classLoader)
|
||||
}
|
||||
if (lmsClass == null) {
|
||||
XposedBridge.log("[OpenLoc] [SystemServer] LocationManagerService not found!")
|
||||
return
|
||||
}
|
||||
|
||||
private fun hookLmsMethods(lmsClass: Class<*>) {
|
||||
for (method in lmsClass.declaredMethods) {
|
||||
// 1. 拦截系统返回给客户端的最后已知位置 getLastLocation
|
||||
if (method.name == "getLastLocation") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val config = readConfigDirectly()
|
||||
if (!config.isEnabled) return
|
||||
|
||||
val pkg = extractCallingPackage(param)
|
||||
if (pkg != null && !config.shouldMock(pkg)) return
|
||||
|
||||
val loc = param.result as? Location
|
||||
if (loc != null) {
|
||||
LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled)
|
||||
} else {
|
||||
param.result = LocationSimulator.createMockLocation(
|
||||
config.latitude,
|
||||
config.longitude,
|
||||
isJitterEnabled = config.isJitterEnabled
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
// 2. 拦截系统分发定位 reportLocation
|
||||
if (method.name == "reportLocation") {
|
||||
when (method.name) {
|
||||
// (1) 0ms IPC 内存配置同步通道:sendExtraCommand
|
||||
"sendExtraCommand" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val config = readConfigDirectly()
|
||||
if (!config.isEnabled) return
|
||||
|
||||
val loc = param.args.firstOrNull { it is Location } as? Location
|
||||
if (loc != null) {
|
||||
LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled)
|
||||
val provider = param.args.getOrNull(0) as? String
|
||||
val extras = param.args.getOrNull(2) as? Bundle
|
||||
if (provider == GlobalMockMemory.COMMAND_PROVIDER || provider == "ghostmapx") {
|
||||
if (extras != null) {
|
||||
GlobalMockMemory.updateFromBundle(extras)
|
||||
TraceLogger.i("SystemServer", "Config Synced -> Enabled=${GlobalMockMemory.isEnabled}, Target=(${GlobalMockMemory.latitude}, ${GlobalMockMemory.longitude}), Mode=${GlobalMockMemory.mode}, Whitelist=${GlobalMockMemory.whitelist.size}, Blacklist=${GlobalMockMemory.blacklist.size}")
|
||||
param.result = true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
// (2) 历史缓存位置拦截:getLastLocation
|
||||
"getLastLocation" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
val callingUid = Binder.getCallingUid()
|
||||
// 系统服务与硬件 HAL 客户端(UID<=1000)绝对放行物理真实缓存,严禁污染
|
||||
if (callingUid <= 1000) return
|
||||
|
||||
val pkg = resolveCallingPackage(param)
|
||||
val originalLoc = param.result as? Location
|
||||
val shouldMock = GlobalMockMemory.isEnabled && !pkg.isNullOrBlank() && GlobalMockMemory.shouldMock(pkg)
|
||||
|
||||
TraceLogger.d("SystemServer", "getLastLocation called by UID=$callingUid, pkg=$pkg, originalResult=${TraceLogger.formatLocation(originalLoc)}, shouldMock=$shouldMock")
|
||||
|
||||
if (!shouldMock) return
|
||||
|
||||
val provider = param.args.firstOrNull { it is String && it in listOf("gps", "network", "fused", "passive") } as? String ?: "gps"
|
||||
val mockLoc = GlobalMockMemory.createLocation(provider)
|
||||
param.result = mockLoc
|
||||
TraceLogger.w("SystemServer", "getLastLocation -> INTERCEPTED for $pkg, replaced with ${TraceLogger.formatLocation(mockLoc)}")
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
// (3) 单次定位请求:getCurrentLocation
|
||||
"getCurrentLocation" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val callingUid = Binder.getCallingUid()
|
||||
// 系统守护进程与底层驱动请求直接放行
|
||||
if (callingUid <= 1000) return
|
||||
|
||||
val pkg = resolveCallingPackage(param)
|
||||
val shouldMock = GlobalMockMemory.isEnabled && !pkg.isNullOrBlank() && GlobalMockMemory.shouldMock(pkg)
|
||||
|
||||
TraceLogger.d("SystemServer", "getCurrentLocation request from UID=$callingUid, pkg=$pkg, shouldMock=$shouldMock")
|
||||
|
||||
if (!shouldMock) return
|
||||
|
||||
// 查找 ILocationCallback 实例
|
||||
for (arg in param.args) {
|
||||
if (arg != null && (arg is IInterface || arg is IBinder ||
|
||||
arg.javaClass.name.contains("Callback") ||
|
||||
arg.javaClass.name.contains("Consumer") ||
|
||||
arg.javaClass.name.contains("Transport"))) {
|
||||
val binder = (arg as? IInterface)?.asBinder() ?: (arg as? IBinder)
|
||||
if (binder != null) {
|
||||
activeCallbacks[binder] = pkg
|
||||
TraceLogger.i("SystemServer", "Bound callback binder=$binder to pkg=$pkg")
|
||||
try {
|
||||
binder.linkToDeath({
|
||||
activeCallbacks.remove(binder)
|
||||
TraceLogger.d("SystemServer", "Callback binder dead for pkg=$pkg")
|
||||
}, 0)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
hookCallbackClass(arg.javaClass)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
// (4) 持续定位监听器注册:registerLocationListener / requestLocationUpdates
|
||||
"registerLocationListener", "requestLocationUpdates" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val callingUid = Binder.getCallingUid()
|
||||
// 核心铁律:UID<=1000(如高德芯片HAL客户端Gpo4Client、系统fused提供商)绝对放行真实定位,严禁放入Mock监听表!
|
||||
if (callingUid <= 1000) {
|
||||
TraceLogger.d("SystemServer", "${method.name} request from SYSTEM UID=$callingUid, PASS-THROUGH TO HARDWARE directly!")
|
||||
return
|
||||
}
|
||||
|
||||
val pkg = resolveCallingPackage(param)
|
||||
val shouldMock = GlobalMockMemory.isEnabled && !pkg.isNullOrBlank() && GlobalMockMemory.shouldMock(pkg)
|
||||
|
||||
TraceLogger.d("SystemServer", "${method.name} request from UID=$callingUid, pkg=$pkg, shouldMock=$shouldMock")
|
||||
|
||||
if (!shouldMock) return
|
||||
|
||||
val provider = param.args.firstOrNull { it is String && it in listOf("gps", "network", "fused", "passive") } as? String ?: "gps"
|
||||
|
||||
for (arg in param.args) {
|
||||
if (arg != null && (arg is IInterface || arg is IBinder ||
|
||||
arg.javaClass.name.contains("Listener") ||
|
||||
arg.javaClass.name.contains("Transport") ||
|
||||
arg.javaClass.name.contains("Callback"))) {
|
||||
val binder = (arg as? IInterface)?.asBinder() ?: (arg as? IBinder)
|
||||
if (binder != null) {
|
||||
activeListeners[binder] = pkg
|
||||
TraceLogger.i("SystemServer", "Bound listener binder=$binder to pkg=$pkg")
|
||||
try {
|
||||
binder.linkToDeath({
|
||||
activeListeners.remove(binder)
|
||||
TraceLogger.d("SystemServer", "Listener binder dead for pkg=$pkg")
|
||||
}, 0)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
val listenerClass = arg.javaClass
|
||||
hookListenerClass(listenerClass)
|
||||
|
||||
// GhostMapX 首帧秒推
|
||||
sendInitialMockLocation(arg, provider)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
// (5) Provider 可用性伪装恒为 true
|
||||
"isProviderEnabled", "isProviderEnabledForUser" -> {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (GlobalMockMemory.isEnabled) {
|
||||
val pkg = resolveCallingPackage(param)
|
||||
if (!pkg.isNullOrBlank() && GlobalMockMemory.shouldMock(pkg)) {
|
||||
param.result = true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Android 12/13/14+ LocationProviderManager 深度拦截
|
||||
* 动态挂钩 ILocationListener.onLocationChanged(GhostMapX LP3 工业级实现)
|
||||
*/
|
||||
private fun hookLocationProviderManager(classLoader: ClassLoader) {
|
||||
val lpmClasses = listOf(
|
||||
"com.android.server.location.provider.LocationProviderManager",
|
||||
"com.android.server.location.LocationProviderManager"
|
||||
)
|
||||
private fun hookListenerClass(clazz: Class<*>) {
|
||||
val className = clazz.name
|
||||
if (hookedListenerClasses.contains(className)) return
|
||||
hookedListenerClasses.add(className)
|
||||
|
||||
for (className in lpmClasses) {
|
||||
val lpmClass = try {
|
||||
XposedHelpers.findClass(className, classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: continue
|
||||
|
||||
for (method in lpmClass.declaredMethods) {
|
||||
if (method.name == "setLastLocation" || method.name == "onReportLocation") {
|
||||
try {
|
||||
XposedBridge.hookMethod(method, object : XC_MethodHook() {
|
||||
XposedBridge.hookAllMethods(clazz, "onLocationChanged", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val config = readConfigDirectly()
|
||||
if (!config.isEnabled) return
|
||||
if (!GlobalMockMemory.isEnabled) return
|
||||
|
||||
val loc = param.args.firstOrNull { it is Location } as? Location
|
||||
if (loc != null) {
|
||||
LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled)
|
||||
// 通过 param.thisObject 获取当前 listener 的真实 Binder 实例
|
||||
val thisObj = param.thisObject ?: return
|
||||
val binder = (thisObj as? IInterface)?.asBinder() ?: (thisObj as? IBinder) ?: return
|
||||
|
||||
// 动态查找该 Binder 归属的目标包名
|
||||
val pkg = activeListeners[binder] ?: return
|
||||
val arg0 = param.args.getOrNull(0)
|
||||
|
||||
val isTargetApp = pkg != "com.lzxnone.openloc" && pkg != "android" && GlobalMockMemory.shouldMock(pkg)
|
||||
|
||||
if (!isTargetApp) {
|
||||
TraceLogger.d("SystemServer", "onLocationChanged -> PASS-THROUGH REAL LOCATION to $pkg, arg0=${if (arg0 is Location) TraceLogger.formatLocation(arg0) else arg0?.toString()}")
|
||||
return
|
||||
}
|
||||
|
||||
// 命中目标应用,实施独立新对象指针置换
|
||||
if (arg0 is Location) {
|
||||
val mockLoc = GlobalMockMemory.createLocation(arg0.provider ?: "gps")
|
||||
TraceLogger.w("SystemServer", "onLocationChanged -> REPLACING for target $pkg: [Original=${TraceLogger.formatLocation(arg0)}] -> [Mock=${TraceLogger.formatLocation(mockLoc)}]")
|
||||
param.args[0] = mockLoc
|
||||
} else if (arg0 is List<*>) {
|
||||
val mockList = ArrayList<Location>(arg0.size)
|
||||
for (item in arg0) {
|
||||
val provider = (item as? Location)?.provider ?: "gps"
|
||||
mockList.add(GlobalMockMemory.createLocation(provider))
|
||||
}
|
||||
TraceLogger.w("SystemServer", "onLocationChanged(List) -> REPLACING ${arg0.size} items for target $pkg")
|
||||
param.args[0] = mockList
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态挂钩 ILocationCallback.onLocation(GhostMapX 单次定位精髓)
|
||||
*/
|
||||
private fun hookCallbackClass(clazz: Class<*>) {
|
||||
val className = clazz.name
|
||||
if (hookedCallbackClasses.contains(className)) return
|
||||
hookedCallbackClasses.add(className)
|
||||
|
||||
val targetMethods = listOf("onLocation", "onLocationChanged", "accept")
|
||||
for (methodName in targetMethods) {
|
||||
try {
|
||||
XposedBridge.hookAllMethods(clazz, methodName, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled) return
|
||||
|
||||
val thisObj = param.thisObject ?: return
|
||||
val binder = (thisObj as? IInterface)?.asBinder() ?: (thisObj as? IBinder) ?: return
|
||||
|
||||
val pkg = activeCallbacks[binder] ?: return
|
||||
val arg0 = param.args.getOrNull(0)
|
||||
val isTargetApp = pkg != "com.lzxnone.openloc" && pkg != "android" && GlobalMockMemory.shouldMock(pkg)
|
||||
|
||||
if (!isTargetApp) {
|
||||
TraceLogger.d("SystemServer", "Callback.$methodName -> PASS-THROUGH REAL LOCATION to $pkg, arg0=${if (arg0 is Location) TraceLogger.formatLocation(arg0) else arg0?.toString()}")
|
||||
return
|
||||
}
|
||||
|
||||
if (arg0 is Location) {
|
||||
val mockLoc = GlobalMockMemory.createLocation(arg0.provider ?: "gps")
|
||||
TraceLogger.w("SystemServer", "Callback.$methodName -> REPLACING for target $pkg: [Original=${TraceLogger.formatLocation(arg0)}] -> [Mock=${TraceLogger.formatLocation(mockLoc)}]")
|
||||
param.args[0] = mockLoc
|
||||
} else if (arg0 is List<*>) {
|
||||
val mockList = ArrayList<Location>(arg0.size)
|
||||
for (item in arg0) {
|
||||
val provider = (item as? Location)?.provider ?: "gps"
|
||||
mockList.add(GlobalMockMemory.createLocation(provider))
|
||||
}
|
||||
TraceLogger.w("SystemServer", "Callback.$methodName(List) -> REPLACING ${arg0.size} items for target $pkg")
|
||||
param.args[0] = mockList
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 首帧秒推辅助方法(对齐 GhostMapX Lcf.a 144-200行)
|
||||
*/
|
||||
private fun sendInitialMockLocation(listenerInstance: Any, provider: String) {
|
||||
try {
|
||||
val mockLoc = GlobalMockMemory.createLocation(provider)
|
||||
val methods = listenerInstance.javaClass.methods
|
||||
for (method in methods) {
|
||||
if (method.name == "onLocationChanged") {
|
||||
val pTypes = method.parameterTypes
|
||||
if (pTypes.isNotEmpty()) {
|
||||
if (List::class.java.isAssignableFrom(pTypes[0])) {
|
||||
val args = arrayOfNulls<Any>(pTypes.size)
|
||||
args[0] = listOf(mockLoc)
|
||||
method.invoke(listenerInstance, *args)
|
||||
return
|
||||
} else if (Location::class.java.isAssignableFrom(pTypes[0])) {
|
||||
val args = arrayOfNulls<Any>(pTypes.size)
|
||||
args[0] = mockLoc
|
||||
method.invoke(listenerInstance, *args)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wi-Fi 扫描结果与连接指纹拦截(支持 Android 8 ~ 15,包含 Android 12+ APEX 模块支持)
|
||||
* 核心目标:
|
||||
* 1. 彻底支持 Android 12+ APEX modular service-wifi.jar 中的 WifiServiceImpl;
|
||||
* 2. getScanResults: 拦截所有目标第三方应用的 Wi-Fi 扫描,返回空列表,阻断腾讯/高德/百度云端指纹反查;
|
||||
* 3. getConnectionInfo: 抹去当前连接 Wi-Fi 路由器的真实 BSSID (MAC),阻断针对当前局域网的反查;
|
||||
* 4. startScan: 抑制目标应用触发硬件扫描。
|
||||
*/
|
||||
private fun hookWifiService(classLoader: ClassLoader) {
|
||||
// 1. 尝试直接从系统类加载器查找 (Android 8 ~ 11)
|
||||
val wifiServiceClasses = listOf(
|
||||
"com.android.server.wifi.WifiServiceImpl",
|
||||
"com.android.server.wifi.WifiService"
|
||||
)
|
||||
for (className in wifiServiceClasses) {
|
||||
try {
|
||||
val wifiClass = XposedHelpers.findClass(className, classLoader)
|
||||
hookWifiServiceImpl(wifiClass)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
|
||||
// 2. 尝试从 ServiceManager.checkService("wifi") 提取当前已运行的运行时 Binder 实例 (跨 APEX)
|
||||
try {
|
||||
val smClass = Class.forName("android.os.ServiceManager")
|
||||
val checkServiceMethod = smClass.getMethod("checkService", String::class.java)
|
||||
val wifiBinder = checkServiceMethod.invoke(null, "wifi")
|
||||
if (wifiBinder != null) {
|
||||
TraceLogger.i("SystemServer", "Found active 'wifi' IBinder in ServiceManager: ${wifiBinder.javaClass.name}")
|
||||
hookWifiServiceImpl(wifiBinder.javaClass)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
TraceLogger.d("SystemServer", "checkService('wifi') inspection: ${t.message}")
|
||||
}
|
||||
|
||||
// 3. 动态拦截 ServiceManager.addService,捕获后续启动阶段注册的 "wifi" 服务 (针对 Android 12+ APEX 模块晚加载)
|
||||
try {
|
||||
val smClass = Class.forName("android.os.ServiceManager")
|
||||
XposedBridge.hookAllMethods(smClass, "addService", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
val name = param.args.getOrNull(0) as? String ?: return
|
||||
if (name == "wifi") {
|
||||
val binder = param.args.getOrNull(1) ?: return
|
||||
TraceLogger.i("SystemServer", "Captured 'wifi' addService registration: ${binder.javaClass.name}")
|
||||
hookWifiServiceImpl(binder.javaClass)
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (t: Throwable) {
|
||||
TraceLogger.e("SystemServer", "Failed to hook ServiceManager.addService: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun hookWifiServiceImpl(wifiClass: Class<*>) {
|
||||
val className = wifiClass.name
|
||||
if (hookedWifiClasses.contains(className)) return
|
||||
hookedWifiClasses.add(className)
|
||||
|
||||
TraceLogger.i("SystemServer", "Arming Wi-Fi interceptor for class: $className (ClassLoader=${wifiClass.classLoader})")
|
||||
|
||||
// (1) 拦截 getScanResults
|
||||
try {
|
||||
XposedBridge.hookAllMethods(wifiClass, "getScanResults", object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled) return
|
||||
val callingUid = Binder.getCallingUid()
|
||||
if (callingUid <= 1000) return // 严格放行系统服务与硬件 HAL
|
||||
|
||||
val pkg = resolveCallingPackage(param)
|
||||
if (pkg.isNullOrBlank() || !GlobalMockMemory.shouldMock(pkg)) return
|
||||
|
||||
val res = param.result ?: return
|
||||
TraceLogger.w("SystemServer", "WifiServiceImpl.getScanResults intercepted for $pkg (UID=$callingUid), returning EMPTY scan results")
|
||||
|
||||
if (res is List<*>) {
|
||||
param.result = emptyList<Any>()
|
||||
} else if (res.javaClass.name.contains("ParceledListSlice")) {
|
||||
try {
|
||||
param.result = XposedHelpers.callStaticMethod(res.javaClass, "emptyList")
|
||||
} catch (_: Throwable) {
|
||||
try {
|
||||
val ctor = res.javaClass.getConstructor(List::class.java)
|
||||
ctor.isAccessible = true
|
||||
param.result = ctor.newInstance(emptyList<Any>())
|
||||
} catch (_: Throwable) {
|
||||
param.result = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (t: Throwable) {
|
||||
TraceLogger.e("SystemServer", "Failed to hook getScanResults on $className: ${t.message}")
|
||||
}
|
||||
|
||||
// (2) 拦截 getConnectionInfo (抹除已连接 Wi-Fi 的 BSSID/MAC)
|
||||
try {
|
||||
XposedBridge.hookAllMethods(wifiClass, "getConnectionInfo", object : XC_MethodHook() {
|
||||
override fun afterHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled) return
|
||||
val callingUid = Binder.getCallingUid()
|
||||
if (callingUid <= 1000) return
|
||||
|
||||
val pkg = resolveCallingPackage(param)
|
||||
if (pkg.isNullOrBlank() || !GlobalMockMemory.shouldMock(pkg)) return
|
||||
|
||||
val wifiInfo = param.result ?: return
|
||||
TraceLogger.w("SystemServer", "WifiServiceImpl.getConnectionInfo intercepted for $pkg (UID=$callingUid), anonymizing BSSID")
|
||||
|
||||
for (field in listOf("mBSSID", "mBssid", "bssid")) {
|
||||
try { XposedHelpers.setObjectField(wifiInfo, field, "02:00:00:00:00:00") } catch (_: Throwable) {}
|
||||
}
|
||||
for (field in listOf("mMacAddress", "mMac", "macAddress")) {
|
||||
try { XposedHelpers.setObjectField(wifiInfo, field, "02:00:00:00:00:00") } catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (t: Throwable) {
|
||||
TraceLogger.e("SystemServer", "Failed to hook getConnectionInfo on $className: ${t.message}")
|
||||
}
|
||||
|
||||
// (3) 拦截 startScan (抑制目标第三方应用主动触发物理 Wi-Fi 扫描)
|
||||
try {
|
||||
XposedBridge.hookAllMethods(wifiClass, "startScan", object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
if (!GlobalMockMemory.isEnabled) return
|
||||
val callingUid = Binder.getCallingUid()
|
||||
if (callingUid <= 1000) return
|
||||
|
||||
val pkg = resolveCallingPackage(param)
|
||||
if (pkg.isNullOrBlank() || !GlobalMockMemory.shouldMock(pkg)) return
|
||||
|
||||
TraceLogger.d("SystemServer", "WifiServiceImpl.startScan suppressed for $pkg (UID=$callingUid)")
|
||||
param.result = true
|
||||
}
|
||||
})
|
||||
} catch (t: Throwable) {
|
||||
TraceLogger.e("SystemServer", "Failed to hook startScan on $className: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* system_server 内部 TelephonyRegistry 监听拦截
|
||||
* 阻断通过 PhoneStateListener 监听基站变化的行为
|
||||
*/
|
||||
private fun hookTelephonyRegistry(classLoader: ClassLoader) {
|
||||
val registryClass = try {
|
||||
XposedHelpers.findClass("com.android.server.TelephonyRegistry", classLoader)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} ?: return
|
||||
|
||||
for (methodName in listOf("notifyCellInfo", "notifyCellInfoForSubscriber")) {
|
||||
try {
|
||||
XposedBridge.hookAllMethods(registryClass, methodName, object : XC_MethodHook() {
|
||||
override fun beforeHookedMethod(param: MethodHookParam) {
|
||||
// 系统向外广播基站变动时,底层由系统维护,调用方由客户端与 Phone 进程拦截
|
||||
}
|
||||
})
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 结合参数上下文与 Binder Calling UID 全面解析调用方真实包名
|
||||
* 彻底解决 Android 11+ 参数抽象为 AttributionSource 导致的包名解析漏网问题
|
||||
*/
|
||||
private fun resolveCallingPackage(param: XC_MethodHook.MethodHookParam): String? {
|
||||
val extracted = extractCallingPackage(param)
|
||||
if (!extracted.isNullOrBlank()) {
|
||||
return extracted
|
||||
}
|
||||
val uid = Binder.getCallingUid()
|
||||
return getPackageNameForCallingUid(uid)
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 system_server 内部通过 PackageManager 根据 Calling UID 反查首选包名
|
||||
*/
|
||||
private fun getPackageNameForCallingUid(uid: Int): String? {
|
||||
if (uid == 1000 || uid == 0) return "android"
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 智能从参数和 Binder 调用上下文中提取真实的调用方应用包名(适配 Android 10 ~ 15)
|
||||
*/
|
||||
private fun extractCallingPackage(param: XC_MethodHook.MethodHookParam): String? {
|
||||
val uid = Binder.getCallingUid()
|
||||
if (uid == 1000 || uid == 0) {
|
||||
// 系统进程自身调用,遍历参数提取实际代理包名
|
||||
}
|
||||
|
||||
for (arg in param.args) {
|
||||
if (arg is String && arg.contains(".") && !arg.contains("/")) {
|
||||
if (arg != "android.location.Location" && !arg.startsWith("android.location.") &&
|
||||
!arg.startsWith("com.android.server.") && !arg.contains("$$") && !arg.contains("@") && !arg.contains(" ") &&
|
||||
arg != "gps" && arg != "network" && arg != "fused" && arg != "passive") {
|
||||
return arg
|
||||
}
|
||||
}
|
||||
if (arg != null && arg.javaClass.name.contains("AttributionSource")) {
|
||||
try {
|
||||
val pkg = XposedHelpers.callMethod(arg, "getPackageName") as? String
|
||||
if (!pkg.isNullOrBlank()) return pkg
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
if (arg != null && arg.javaClass.name.contains("CallerIdentity")) {
|
||||
try {
|
||||
val pkg = XposedHelpers.callMethod(arg, "getPackageName") as? String
|
||||
if (!pkg.isNullOrBlank()) return pkg
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -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,28 +29,26 @@ 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(
|
||||
text = stringResource(id = R.string.update_dialog_title_format, displayVersion),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
)
|
||||
},
|
||||
text = {
|
||||
Column(
|
||||
@@ -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
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
text = stringResource(id = R.string.home_update_dialog_msg),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
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 = {
|
||||
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.home_update_btn_later))
|
||||
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,13 +137,53 @@ fun MainScreen(
|
||||
}
|
||||
}
|
||||
|
||||
if (isAboutViewOpen) {
|
||||
BackHandler {
|
||||
isAboutViewOpen = false
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
topBar = {
|
||||
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 ->
|
||||
AboutScreen(
|
||||
onCheckAppUpdate = performManualCheck,
|
||||
isCheckingUpdate = isCheckingAppUpdate,
|
||||
modifier = Modifier.padding(innerPadding)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Box(modifier = modifier.fillMaxSize()) {
|
||||
Scaffold(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||
topBar = {
|
||||
if (currentTab != NavTab.LOCATION) {
|
||||
OpenLocTopBar()
|
||||
OpenLocTopBar(
|
||||
onAboutClick = { isAboutViewOpen = true }
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
@@ -107,27 +193,64 @@ fun MainScreen(
|
||||
)
|
||||
}
|
||||
) { innerPadding ->
|
||||
AnimatedContent(
|
||||
targetState = currentTab,
|
||||
transitionSpec = {
|
||||
fadeIn() togetherWith fadeOut()
|
||||
},
|
||||
label = "TabContentAnimation",
|
||||
modifier = Modifier.padding(innerPadding)
|
||||
) { targetTab ->
|
||||
when (targetTab) {
|
||||
NavTab.HOME -> HomeScreen(
|
||||
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 },
|
||||
onCheckUpdate = performManualCheck
|
||||
onOpenWhitelist = { activeAppSelectionMode = AppMockMode.WHITELIST }
|
||||
)
|
||||
NavTab.LOCATION -> LocationScreen()
|
||||
NavTab.SETTINGS -> SettingsScreen()
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,14 +269,17 @@ fun MainScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 新版本更新弹窗
|
||||
// 新版本更新弹窗(全局层级)
|
||||
updateInfoToDisplay?.let { info ->
|
||||
UpdateDialog(
|
||||
updateInfo = info,
|
||||
onDismiss = { updateInfoToDisplay = null }
|
||||
onDismiss = { updateInfoToDisplay = null },
|
||||
onDontShowAgain = { suppressedCode ->
|
||||
AppPreferences.updateSuppressedVersionCode(suppressedCode)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,21 +146,36 @@ fun AppSelectionScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// 关联当前名单选中的包名集合
|
||||
// 关联当前名单选中的包名集合(用于实时响应勾选状态与计数展示)
|
||||
val selectedPackages = if (mode == AppMockMode.BLACKLIST) {
|
||||
AppPreferences.blacklistApps
|
||||
} else {
|
||||
AppPreferences.whitelistApps
|
||||
}
|
||||
|
||||
// 根据搜索词和系统应用开关进行过滤
|
||||
val filteredApps = remember(installedApps, searchQuery, showSystemApps) {
|
||||
installedApps.filter { app ->
|
||||
// 记录进入页面时的初始选中集合:排序仅基于此快照,选中/取消不立即触发重排,只有用户下一次进入页面时才重新排序
|
||||
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) }
|
||||
)
|
||||
}
|
||||
|
||||
// 标题与说明
|
||||
@@ -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,11 +605,23 @@ fun LocationScreen(
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
update = { mapView ->
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (isVisible) {
|
||||
// ------------------ 2. 顶部未激活时的浮动搜索胶囊 ------------------
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
@@ -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
|
||||
@@ -1378,6 +1578,7 @@ fun LocationScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制文本到系统剪贴板工具函数
|
||||
|
||||
@@ -400,102 +400,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,197 @@
|
||||
<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>
|
||||
</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,37 @@
|
||||
<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>
|
||||
</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,37 @@
|
||||
<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>
|
||||
</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,35 @@
|
||||
<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>
|
||||
</resources>
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.lzxnone.openloc
|
||||
|
||||
import com.lzxnone.openloc.hook.interceptor.AntiDetectionHook
|
||||
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"))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user