Search code examples
androidandroid-intentandroid-activity

onActivityResult doesn't return success


I'm asking the user to rate my app and navigating them to 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
            )
        }
    }

Then, to check user successfully went to playstore or not


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()
            }
        }
}

Here, I'm getting toast when user presses cancel. But I'm not getting Toast when user successfully navigated to playstore.


Solution

  • It's not possible but you can do some workaround.

    // 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()
            }
    
    • have two variable userLoginCount and userLoginCountPrevious
    • read from shared pref's userLoginCount then save it's val to userLoginCountPrevious
    • when user login 5th time here as in this example, Rating dialog is showed. else increment the value of userLoginCount.
    • now you can see that userLoginCount is incremented but not userLoginCountPrevious.

    Then, in on 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
    }
    

    Hope, it helps !