m***@163.com
m***@163.com
  • 发布:2026-01-18 18:17
  • 更新:2026-01-18 18:17
  • 阅读:14

如何触发onActivityResult

分类:uni-app
@file:Suppress("UNCHECKED_CAST", "USELESS_CAST", "INAPPLICABLE_JVM_NAME", "UNUSED_ANONYMOUS_PARAMETER", "NAME_SHADOWING", "UNNECESSARY_NOT_NULL_ASSERTION")  
package uts.sdk.modules.yandexOauth  
import android.app.Activity  
import android.app.Application  
import android.app.Application.ActivityLifecycleCallbacks  
import android.content.Context  
import android.os.Bundle  
import androidx.activity.ComponentActivity  
import androidx.activity.result.ActivityResultCallback  
import androidx.activity.result.ActivityResultLauncher  
import com.yandex.authsdk.YandexAuthLoginOptions  
import com.yandex.authsdk.YandexAuthOptions  
import com.yandex.authsdk.YandexAuthResult  
import com.yandex.authsdk.YandexAuthSdk  
import io.dcloud.uniapp.*  
import io.dcloud.uniapp.extapi.*  
import io.dcloud.uts.*  
import io.dcloud.uts.Map  
import io.dcloud.uts.Set  
import io.dcloud.uts.UTSAndroid  
import kotlin.properties.Delegates  
import kotlinx.coroutines.CoroutineScope  
import kotlinx.coroutines.Deferred  
import kotlinx.coroutines.Dispatchers  
import kotlinx.coroutines.async  
var sdk: YandexAuthSdk? = null  
var launcher: ActivityResultLauncher<YandexAuthLoginOptions>? = null  
var loginCallback: ((res: Any) -> Unit)? = null  
open class YandexActivityLifecycleCallbacks : ActivityLifecycleCallbacks {  
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?): Unit {  
        android.util.Log.e("YandexOAuth", activity::class.java.name)  
        if (activity::class.java.name == "io.dcloud.PandoraEntryActivity") {  
            if (launcher == null && sdk != null) {  
                try {  
                    val componentActivity = activity as ComponentActivity  
                    if (componentActivity != null) {  
                        launcher = componentActivity.registerForActivityResult(  
                            sdk!!!!.contract,  
                            object : ActivityResultCallback<YandexAuthResult> {  
                                override fun onActivityResult(result: YandexAuthResult) {  
                                    handleResult(result)  
                                }  
                            })  
                        console.log("[YandexOAuth] launcher registered in ActivityLifecycleCallbacks")  
                    } else {  
                        console.log("[YandexOAuth] Activity is not a ComponentActivity, cannot register launcher")  
                    }  
                } catch (e: Throwable) {  
                    console.error("[YandexOAuth] Failed to register launcher in ActivityLifecycleCallbacks: " + e)  
                }  
            }  
        }  
    }  
    override fun onActivityStarted(activity: Activity): Unit {}  
    override fun onActivityResumed(activity: Activity): Unit {}  
    override fun onActivityPaused(activity: Activity): Unit {}  
    override fun onActivityStopped(activity: Activity): Unit {}  
    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle): Unit {}  
    override fun onActivityDestroyed(activity: Activity): Unit {}  
}  
open class Yandex_HookProxy : UTSAndroidHookProxy {  
    override fun onCreate(application: Application) {  
        android.util.Log.e("YandexOAuth", "? Yandex_HookProxy.onCreate")  
        try {  
            sdk = YandexAuthSdk.create(YandexAuthOptions(application.getApplicationContext() as Context))  
            android.util.Log.e("YandexOAuth", "✅ YandexAuthSdk created in AppHookProxy")  
            application.registerActivityLifecycleCallbacks(YandexActivityLifecycleCallbacks())  
        }  
        catch (e: Throwable) {  
            android.util.Log.e("YandexOAuth", "❌ SDK create failed in AppHookProxy: " + e)  
        }  
    }  
}  
fun init(): Unit {  
    console.log("[YandexOAuth] init() called - checking status")  
    UTSAndroid.onAppActivityResult { requestCode: Int, resultCode: Int, data: android.content.Intent? ->  
        console.log("[YandexOAuth] Received onActivityResult for Yandex")  
        // 其他 requestCode 忽略  
    }  
}  
fun login(cb: (res: Any) -> Unit): Unit {  
    if (launcher == null) {  
        cb(object : UTSJSONObject() {  
            var code: Number = -1  
            var error = "not initialized, call init() first"  
        })  
        return  
    }  
    loginCallback = cb  
    launcher!!!!.launch(YandexAuthLoginOptions())  
}  
fun handleResult(result: YandexAuthResult): Unit {  
    console.log("[YandexOAuth] handleResult() Start")  
    val cb = loginCallback  
    loginCallback = null  
    if (cb == null) {  
        return  
    }  
    if (result is YandexAuthResult.Success) {  
        console.log("[YandexOAuth] handleResult() Success", result.token.value)  
        cb(object : UTSJSONObject() {  
            var code: Number = 0  
            var token = result.token.value  
        })  
        return  
    }  
    if (result is YandexAuthResult.Failure) {  
        console.log("[YandexOAuth] handleResult() Failure", result.exception?.message)  
        cb(object : UTSJSONObject() {  
            var code: Number = -1  
            var error = result.exception?.message  
        })  
        return  
    }  
    cb(object : UTSJSONObject() {  
        var code: Number = -2  
        var error = "cancelled"  
    })  
}  
fun logout(cb: (res: Any) -> Unit): Unit {  
    sdk = null  
    launcher = null  
    loginCallback = null  
    cb(object : UTSJSONObject() {  
        var code: Number = 0  
    })  
    console.log("[YandexOAuth] logged out")  
}  
fun getUserInfo(token: String, cb: (res: Any) -> Unit): Unit {  
    var tokenPreview = "null"  
    if (token.isNotEmpty()) {  
        tokenPreview = token.substring(0, 20) + "..."  
    }  
    cb(object : UTSJSONObject() {  
        var code: Number = -1  
        var error = "getUserInfo not implemented yet. Token: " + tokenPreview  
    })  
    console.log("[YandexOAuth] getUserInfo called but not fully implemented")  
}  
fun isLoggedIn(cb: (isLoggedIn: Boolean) -> Unit): Unit {  
    val hasToken = sdk != null && launcher != null  
    cb(hasToken)  
    console.log("[YandexOAuth] isLoggedIn check: " + hasToken)  
}  
open class Yandex_HookProxyByJs : Yandex_HookProxy {  
    constructor() : super() {}  
    open fun onCreateByJs(application: Application) {  
        return this.onCreate(application)  
    }  
}  
fun initByJs(): Unit {  
    return init()  
}  
fun loginByJs(cb: UTSCallback): Unit {  
    return login(if (cb.fnJS != null) {  
        cb.fnJS  
    } else {  
        cb.fnJS = fun(res: Any){  
            cb(res)  
        }  
        cb.fnJS  
    }  
            as (res: Any) -> Unit)  
}  
fun logoutByJs(cb: UTSCallback): Unit {  
    return logout(if (cb.fnJS != null) {  
        cb.fnJS  
    } else {  
        cb.fnJS = fun(res: Any){  
            cb(res)  
        }  
        cb.fnJS  
    }  
            as (res: Any) -> Unit)  
}  
fun getUserInfoByJs(token: String, cb: UTSCallback): Unit {  
    return getUserInfo(token, if (cb.fnJS != null) {  
        cb.fnJS  
    } else {  
        cb.fnJS = fun(res: Any){  
            cb(res)  
        }  
        cb.fnJS  
    }  
            as (res: Any) -> Unit)  
}  
fun isLoggedInByJs(cb: UTSCallback): Unit {  
    return isLoggedIn(if (cb.fnJS != null) {  
        cb.fnJS  
    } else {  
        cb.fnJS = fun(isLoggedIn: Boolean){  
            cb(isLoggedIn)  
        }  
        cb.fnJS  
    }  
            as (isLoggedIn: Boolean) -> Unit)  
}

{
"dependencies": [
"androidx.activity:activity:1.8.0",
"androidx.activity:activity-ktx:1.8.0",
"androidx.fragment:fragment:1.6.1",
"androidx.appcompat:appcompat:1.6.1",
"androidx.core:core-ktx:1.12.0",
"com.yandex.android:authsdk:3.1.3"
],
"minSdkVersion": 21,
"proguard": {
"rules": [
"-keep class com.yandex.authsdk. { *; }",
"-keep class com.yandex.authsdk.internal.* { ; }",
"-dontwarn com.yandex.authsdk.
"
]
},
"project": {
"repositories": [
"mavenCentral()",
"google()"
]
},
"hooksClass": "uts.sdk.modules.yandexOauth.Yandex_HookProxy"

}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

<!-- 网络权限 -->  
<uses-permission android:name="android.permission.INTERNET" />  

<!-- Yandex认证需要的Activity -->  
<application>  
    <activity  
        android:name="com.yandex.authsdk.internal.AuthSdkActivity"  
        android:exported="true"  
        android:theme="@style/Theme.AppCompat.Translucent.NoTitleBar"  
        tools:replace="android:theme"  
        tools:ignore="Instantiatable">  
        <intent-filter>  
            <action android:name="android.intent.action.VIEW" />  
            <category android:name="android.intent.category.DEFAULT" />  
            <category android:name="android.intent.category.BROWSABLE" />  
            <!-- 格式:yx{your_client_id} -->  
            <data android:scheme="yx${YANDEX_CLIENT_ID}" />  
        </intent-filter>  
    </activity>  
</application>  

</manifest>

1、可以正常调用yandex进行登录
2、回调没有触发,问gpt 说是 activity 注册和回调的不是同一个activity (不会android 不太了解里面机制)
有没有大佬会的,这个要怎么改

2026-01-18 18:17 负责人:无 分享
已邀请:
Ask小助手

Ask小助手 - Ask社区AI助手

该问题请在专业群( uni-app x技术交流群 ) 咨询,群中有相关专业的管理员和群友。

问题在于Activity注册和回调不一致。uni-app x中Activity管理复杂,建议改用全局监听方式:

  1. 移除ActivityLifecycleCallbacks中的launcher注册逻辑
  2. 在init()中直接使用UTSAndroid.onAppActivityResult全局监听
  3. 定义唯一requestCode标识Yandex登录请求

修改后的代码示例:

var sdk: YandexAuthSdk? = null  
var loginCallback: ((res: Any) -> Unit)? = null  
const val YANDEX_REQUEST_CODE = 1001 // 定义唯一请求码  

fun init(): Unit {  
    sdk = YandexAuthSdk.create(YandexAuthOptions(UTSAndroid.getAppContext() as Context))  
    // 全局监听Activity结果  
    UTSAndroid.onAppActivityResult { requestCode, resultCode, data ->  
        if (requestCode == YANDEX_REQUEST_CODE) {  
            handleActivityResult(resultCode, data)  
        }  
    }  
}  

fun login(cb: (res: Any) -> Unit): Unit {  
    loginCallback = cb  
    val activity = UTSAndroid.getUniActivity()  
    if (activity != null) {  
        // 直接使用sdk.login并指定requestCode  
        sdk!!.login(activity, YandexAuthLoginOptions(), YANDEX_REQUEST_CODE)  
    }  
}  

fun handleActivityResult(resultCode: Int, data: Intent?) {  
    val result = sdk!!.parseActivityResult(resultCode, data)  
    handleResult(result)  
}

关键点:

  • 使用全局UTSAndroid.onAppActivityResult替代Activity-specific注册
  • 通过自定义requestCode区分Yandex登录请求
  • 调用sdk.login()时显式传入requestCode
  • 使用sdk.parseActivityResult()解析结果

参考文档:UTSAndroid.onAppActivityResult

内容为 AI 生成,仅供参考

要回复问题请先登录注册