首页 > 解决方案 > 如何在 jetpack compose 中观察 onActivityResult()?

问题描述

我正在尝试Change location settings从这里启用 gps 设置:https ://developer.android.com/training/location/change-location-settings

它说check the result in onActivityResult(),但我不知道如何在 jetpack compose 中观察结果。请告诉我如何在撰写中观察此结果

task.addOnFailureListener { exception ->
    if (exception is ResolvableApiException){
        // Location settings are not satisfied, but this can be fixed
        // by showing the user a dialog.
        try {
            // Show the dialog by calling startResolutionForResult(),
            // and check the result in onActivityResult().
            exception.startResolutionForResult(this@MainActivity,
                    REQUEST_CHECK_SETTINGS)
        } catch (sendEx: IntentSender.SendIntentException) {
            // Ignore the error.
        }
    }
}

标签: androidandroid-studio

解决方案


如果有人需要答案

    val settingResultRequest =
        rememberLauncherForActivityResult(contract = ActivityResultContracts.StartIntentSenderForResult()) {activityResult->
            if (activityResult.resultCode == RESULT_OK)
                Log.d("appDebug", "Accepted")
            else {
                Log.d("appDebug", "Denied")
            }
        }

    task.addOnFailureListener { exception ->
        if (exception is ResolvableApiException) {
            try {
                val intentSenderRequest = IntentSenderRequest.Builder(exception.resolution).build()
                settingResultRequest.launch(intentSenderRequest)
            } catch (sendEx: IntentSender.SendIntentException) {
                // Ignore the error.
            }
        }
    }

推荐阅读