I would like my Apex code to know the difference between me being actually logged in as a particular Salesforce user, versus being logged in as an administrator and impersonating the user (because I clicked on his name and selected “Login”).
I cannot find a documented way to do this, and knowing that this is the nature of impersonation, don’t necessarily expect to find a documented API call that tells me this. But Salesforce definitely knows the difference, at least in the UI, and Logout while you’re impersonating just stops the impersonation but leaves you logged in as the administrator again.
So, is there a way for Apex code to tell that it is actually an administrator impersonating a user?
No. As far as the code is concerned, the effective user is the user performing the action. Any records created by an administrator logged in as a user will have their createdby and lastmodifiedby audit fields set to that user, and userinfo.getuserid() will return the user being logged in as. This is the same behavior as System.runAs() in test methods, with the exception that code can detect if it is being run in a test method. There’s nothing you can do, such as examining the session ID, etc, that would give you any clue at all, unless you know how to decrypt the session ID (hypothetically; presumably this is how the UI knows).