Android: getCallingPackage returns null and an alternative

If you ever want to verify the package name of an application which is deeplinking into you, you might take a look at Activity’s ‘getCallingPackage’. The gotcha here is that this will always be null unless the activity was started with startActivityForResult.

Unfortunately, setActivityForResult may not work for your app (especially if it requires changing your launchmode).

There is a workaround that may work for you. If the goal is to find out what package started your activity it can be done by attaching a PendingIntent as an extra to the intent you are sending. PendingIntent has a method called getCreatorPackage which returns the package name of who created the object. We won’t actually be using the functionality of the PendingIntent, we’re merely using the security properties that it can provide.

This means that instead of using startActivityForResult, you can use startActivity as usual and attach an instance of a PendingIntent as an extra. The PendingIntent extra can be read by the receiver of the intent to verify what package sent the intent.

You can gain some additional security properties by making sure that the intent you’re sending is explicit (setTargetPackage) and you can instantiate the PendingIntent to itself also have extra data so you can flag that the pending intent was created for this specific purpose (opposed to some other pending intent instance that may have been vended to some other app).


Leave a Reply

Your email address will not be published. Required fields are marked *