The phone is usually connected to my laptop to provide internet over USB.
Therefore I can create a condition to start a service when a certain network interface becomes available.
Previously I did something similar with udev, but udev has changed a lot since then and this particular task would be so intertwined with systemd anyhow, that I decided to use systemd all the way.
My Linux laptop creates an interface enp0s20u2, and an accompanying systemd .device, whenever the phone shares its internet.
All I have to do is to create one service file, e.g./etc/systemd/system/phone-connect@.service:
[Unit]
Description=Do things phone usb net sharing becomes active
BindsTo=sys-subsystem-net-devices-%i.device
After=sys-subsystem-net-devices-%i.device
[Service]
User=<user>
Group=<user>
ExecStart=/bin/sh -c 'echo "%n $(date)" >> /home/<user>/%n.txt'
[Install]
WantedBy=sys-subsystem-net-devices-%i.device
Now I can tell it to watch for enp0s20u2:
systemctl enable phone-connect@enp0s20u2.service
And check if it works:
watch cat /home/<user>/phone-connect@enp0s20u2.service.txt
This should generate an entry every time you connect the device.