Basically I have used ordered broadcast to achieve this. Here is step by step process.
First let's capture this when application is in foreground. First add a broadcast receiver in your activity.
That's it. Hope this helps you.
Now verify it
sudo apt-get install apache2 php7.0 libapache2-mod-php7.0
Load PHP module.
a2query -m php7.0
sudo a2enmod php7.0
sudo service apache2 restart