【问题标题】:onActivityResult doesn't return successonActivityResult 不返回成功
【发布时间】:2020-09-10 09:06:24
【问题描述】:

我要求用户对我的应用进行评分并将他们导航到 google playstore。

fun openPlayStore() {
        val appPackageName = packageName
        try {
            startActivityForResult(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("market://details?id=$appPackageName")
                ), OPEN_PLAY_STORE
            )
        } catch (anfe: ActivityNotFoundException) {
            startActivityForResult(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")
                ), OPEN_PLAY_STORE
            )
        }
    }

然后,检查用户是否成功进入Playstore


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
if (requestCode == OPEN_PLAY_STORE) {
            println(" resultCode = > $resultCode")
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "cancelled", Toast.LENGTH_SHORT).show()
            }
        }
}

在这里,当用户按下取消键时,我正在敬酒。但是当用户成功导航到 Playstore 时,我没有收到 Toast。

【问题讨论】:

  • 您忘记将结果设置为您的意图
  • @WhatAJerk 我没听懂你说的。

标签: android android-intent android-activity


【解决方案1】:

这是不可能的,但你可以做一些解决方法。

// Logic to ask rating when user opened the app 5th time
        val sp = this.getSharedPreferences("UserLoginCount", Context.MODE_PRIVATE)

        userLoginCount = sp.getInt("count", 1)
        userLoginCountPrevious = sp.getInt("count", 0)
        var showRatingDialogCount = sp.getInt("nextCount", 5)

        if (userLoginCount == showRatingDialogCount) {
            openAskForRating()
        } else {
            sp.edit().putInt("count", ++userLoginCount).commit()
            Toast.makeText(this,"$userLoginCount time user logged in",Toast.LENGTH_SHORT).show()
        }
  • 有两个变量userLoginCountuserLoginCountPrevious
  • 从共享首选项的userLoginCount 中读取,然后将其保存到userLoginCountPrevious
  • 当用户在此示例中第 5 次登录时,将显示评级对话框。否则增加userLoginCount 的值。
  • 现在您可以看到userLoginCount 增加了,但userLoginCountPrevious 没有增加。

然后,在onActivityResult

if (userLoginCount == userLoginCountPrevious) { 
     // means he successfully navigated to playstore and came back 
     dialog.dismiss()
}else{
     // means he closed the rating dialog without visiting playstore
}

希望,它有帮助!

【讨论】:

  • 这有点道理。
【解决方案2】:

您无法检查用户是否被重定向到 Play 商店。

当您使用startActivityForResult启动一个意图时,下一个活动应该在关闭之前调用setResult。只有这样,您才能从 onActivityResult 中的下一个活动中获取结果。

在这种情况下,Play 商店没有设置结果,因此您的onActivityResult 中没有任何结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 2020-04-28
    相关资源
    最近更新 更多