Adding a Ratings Feature

How can I add a feature to my app where right before they close my app, it asks them if they want to rate and review it?
I found a code, but am not sure if it would work or where to place it.

SharedPreferences prefs = mContext.getSharedPreferences(“HasRated”, 0);
has_rated = prefs.getBoolean(“rated”, false);

if (!has_rated) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:

Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=xxxxxxxxxxx"));
startActivity(browserIntent);

SharedPreferences prefs = mContext.getSharedPreferences(“HasRated”, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(“rated”, true).commit();

break;

case DialogInterface.BUTTON_NEGATIVE:
finish();
break;
}
}
};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(“Please rate the app if you liked it ”).setPositiveButton(“Yes”, dialogClickListener)
.setNegativeButton(“Later”, dialogClickListener).show();

} else {
finish();
}

I am developing with android native java not much but if they press close button you should check first something like “wasRateDialogShown”. Like your code.
I guess this should be in a listener of the “exit” button

But you can look to this too.https://github.com/kskkbys/Android-RateThisApp