Browse Source

add

newdev_shunjiawei
wolfplus 1 year ago
parent
commit
901289c98c
  1. 49
      local_plugins/open_ai_service/android/src/main/kotlin/com/yunqiinnovation/open_ai_service/OpenAIService.kt
  2. 173
      local_plugins/open_ai_service/android/src/main/kotlin/com/yunqiinnovation/open_ai_service/SystemFunctionHandler.kt

49
local_plugins/open_ai_service/android/src/main/kotlin/com/yunqiinnovation/open_ai_service/OpenAIService.kt

@ -586,11 +586,17 @@ class OpenAIService(private val context: Context? = null) : CoroutineScope {
return
}
try {
handleStreamJson(JSONObject(data), toolCalls, callback, messages)
} catch (e: Exception) {
// 忽略解析错误,但记录日志
Log.e(TAG, "解析JSON出错: ${e.message}", e)
// 验证JSON是否完整(至少检查大括号匹配)
if (isValidJson(data)) {
try {
handleStreamJson(JSONObject(data), toolCalls, callback, messages)
} catch (e: Exception) {
// 忽略解析错误,但记录日志
Log.e(TAG, "解析JSON出错: ${e.message}", e)
}
} else {
// 记录不完整的JSON,但不尝试解析它
Log.d(TAG, "收到不完整的JSON数据,跳过处理, data=$data")
}
}
}
@ -879,6 +885,39 @@ class OpenAIService(private val context: Context? = null) : CoroutineScope {
fun onFunctionCall(functionCall: JSONObject)
fun onFunctionCallResult(functionCall: JSONObject, functionCallResult: JSONObject)
}
/**
* 检查字符串是否为有效的JSON
* 使用简单的括号匹配和引号检查来确定JSON是否完整
*/
private fun isValidJson(jsonStr: String): Boolean {
if (jsonStr.isEmpty()) return false
if (!jsonStr.startsWith("{") || !jsonStr.endsWith("}")) return false
var braceCount = 0
var insideQuotes = false
var escapeNext = false
for (char in jsonStr) {
if (escapeNext) {
escapeNext = false
continue
}
when (char) {
'\\' -> escapeNext = true
'"' -> if (!escapeNext) insideQuotes = !insideQuotes
'{' -> if (!insideQuotes) braceCount++
'}' -> if (!insideQuotes) braceCount--
}
// 如果括号不匹配(闭合太多),提前返回
if (braceCount < 0) return false
}
// 所有引号都应该闭合,所有括号也应该匹配
return braceCount == 0 && !insideQuotes
}
}
/**

173
local_plugins/open_ai_service/android/src/main/kotlin/com/yunqiinnovation/open_ai_service/SystemFunctionHandler.kt

@ -18,6 +18,10 @@ import org.json.JSONObject
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import android.view.KeyEvent
import android.os.Handler
import android.os.Looper
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers
/**
* 系统功能处理器 - 负责调用系统API执行各种功能以及注册系统功能
*/
@ -878,10 +882,10 @@ class SystemFunctionHandler(private val context: Context) {
}
/**
* 获取当前位置
* 获取当前位置(简化版,只获取最后已知位置)
* @return 操作结果
*/
suspend fun getCurrentLocation(): Result = suspendCancellableCoroutine { continuation ->
suspend fun getCurrentLocation(): Result = withContext(Dispatchers.Main) {
Log.d(TAG, "开始获取当前位置")
try {
@ -901,13 +905,10 @@ class SystemFunctionHandler(private val context: Context) {
if (!hasFineLocationPermission && !hasCoarseLocationPermission) {
Log.d(TAG, "没有位置权限")
// 如果没有权限,返回需要授权的结果
continuation.resume(Result(
return@withContext Result(
success = false,
message = "需要位置权限才能获取当前位置"
))
return@suspendCancellableCoroutine
)
}
// 检查位置服务是否开启
@ -915,153 +916,49 @@ class SystemFunctionHandler(private val context: Context) {
!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.d(TAG, "位置服务未启用")
// 提醒用户打开位置服务
try {
val settingsIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
context.startActivity(settingsIntent)
} catch (e: Exception) {
Log.e(TAG, "无法打开位置设置: ${e.message}")
}
continuation.resume(Result(
return@withContext Result(
success = false,
message = "位置服务未启用,请打开GPS或网络定位"
))
return@suspendCancellableCoroutine
)
}
// 尝试先获取最后已知位置
// 获取最后已知位置
var bestLocation: Location? = null
try {
// 检查网络提供者最后已知位置
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
val networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
if (networkLocation != null) {
bestLocation = networkLocation
Log.d(TAG, "获取到网络位置: ${networkLocation.latitude}, ${networkLocation.longitude}")
}
}
// 检查GPS提供者最后已知位置
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
val gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (gpsLocation != null && (bestLocation == null || gpsLocation.accuracy < bestLocation.accuracy)) {
bestLocation = gpsLocation
Log.d(TAG, "获取到GPS位置: ${gpsLocation.latitude}, ${gpsLocation.longitude}")
}
}
} catch (e: Exception) {
Log.e(TAG, "获取最后已知位置失败: ${e.message}")
}
// 如果有最后已知位置,直接返回结果
if (bestLocation != null) {
val message = "当前位置: 经度 ${bestLocation.longitude}, 纬度 ${bestLocation.latitude}"
Log.d(TAG, message)
continuation.resume(Result(
success = true,
message = message
))
return@suspendCancellableCoroutine
}
// 如果没有最后已知位置,尝试请求更新位置(设置10秒超时)
val locationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
// 收到位置更新
val message = "当前位置: 经度 ${location.longitude}, 纬度 ${location.latitude}"
Log.d(TAG, "位置更新: $message")
locationManager.removeUpdates(this)
if (continuation.isActive) {
continuation.resume(Result(
success = true,
message = message
))
}
}
@Deprecated("Deprecated in Java")
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
// 不需要处理
}
override fun onProviderEnabled(provider: String) {
// 不需要处理
}
override fun onProviderDisabled(provider: String) {
// 如果提供者被禁用,检查是否还有其他可用提供者
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.removeUpdates(this)
if (continuation.isActive) {
continuation.resume(Result(
success = false,
message = "位置服务已被禁用"
))
}
}
}
}
// 注册位置更新请求
// 尝试获取网络位置
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
0L,
0f,
locationListener
)
val networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
if (networkLocation != null) {
bestLocation = networkLocation
Log.d(TAG, "获取到网络位置: ${networkLocation.latitude}, ${networkLocation.longitude}")
}
}
// 尝试获取GPS位置(如果更精确)
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0L,
0f,
locationListener
)
}
// 设置超时取消
continuation.invokeOnCancellation {
try {
locationManager.removeUpdates(locationListener)
} catch (e: Exception) {
Log.e(TAG, "取消位置更新失败: ${e.message}")
val gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (gpsLocation != null && (bestLocation == null || gpsLocation.accuracy < bestLocation.accuracy)) {
bestLocation = gpsLocation
Log.d(TAG, "获取到GPS位置: ${gpsLocation.latitude}, ${gpsLocation.longitude}")
}
}
// 启动超时处理
android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
if (continuation.isActive) {
try {
locationManager.removeUpdates(locationListener)
continuation.resume(Result(
success = false,
message = "获取位置超时,请稍后重试"
))
} catch (e: Exception) {
Log.e(TAG, "超时处理失败: ${e.message}")
}
}
}, 10000L) // 10秒超时
// 返回结果
return@withContext if (bestLocation != null) {
val message = "当前位置: 经度 ${bestLocation.longitude}, 纬度 ${bestLocation.latitude}"
Log.d(TAG, message)
Result(success = true, message = message)
} else {
Log.d(TAG, "无法获取位置信息")
Result(success = false, message = "无法获取位置信息,请稍后重试")
}
} catch (e: Exception) {
Log.e(TAG, "获取位置过程中发生异常: ${e.message}")
if (continuation.isActive) {
continuation.resume(Result(
success = false,
message = "获取位置失败: ${e.message}"
))
}
return@withContext Result(
success = false,
message = "获取位置失败: ${e.message}"
)
}
}

Loading…
Cancel
Save