Programmatically find whether installing from unknown sources is allowed

Here is the code that uses the mentioned setting:

boolean isNonPlayAppAllowed = Settings.Secure.getInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS) == 1;

Also showing the setting to user might me useful:

if (!isNonPlayAppAllowed) {
    startActivity(new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS));
}

you can request the package manager to tell you

 applicationContext.packageManager.canRequestPackageInstalls()

    boolean allow = false;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         allow = this.getPackageManager().canRequestPackageInstalls();
        } else {
        try {
         allow = Settings.Secure.getInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS) == 1;
            } catch (Settings.SettingNotFoundException e) {
              e.printStackTrace();
              }
       }
    
    if (!allow)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
       startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES));
       } else {
       startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));
       }

This setting is called "INSTALL_NON_MARKET_APP" (click for documentation).

(I basically already typed the question when I found the answer hidden deep within documentation, with a different name, so I decided to post the question and self answer, since it's not trivial.)