Spotify is my go-to app when it comes to music streaming. It’s free, it has a good collection of music. But unfortunately, Spotify is not yet available in India. So, if you are in India and want to listen to your favorite music on Spotify, your only way out is a VPN from Spotify-supported countries. (Spotify needs a supported country IP when a user signs up, but after that you don’t need to use the same country based IP to listen to music, but it logs you out every 14 days if you don’t use an IP from supported country.)

For VPN, I use a VPS from DigitalOcean where OpenVPN is installed and configured to accept connection from my Android devices.

The only real problem is you need to launch and connect to VPN every time you start Spotify. This is irritating and repetitive. So I resorted to Tasker. After a few hours of searching, it turns out that Android doesn’t provide reliable methods to check if a background app is running, unless you are using a rooted device. Since Nougat, this restriction has been more stringent for security purposes.

Since Android runs on Linux, commands like ifconfig, ip addr would work fine, giving expected output. After trying them on a terminal emulator, I found that ifconfig shows an additional tun0 network interface when I am connected to the internet over VPN. So, taking advantage of this fact, I run the following inside the emulator:

ifconfig | grep tun -A5 | grep UP

Essentially, this code checks for network tunnels and additionally checking if the interface is running. (Piping multiple grep might look unaesthetic, but it is faster.) The above code doesn’t return anything if no tunnel interface is connected.

So, with half the work being done, I moved to Tasker to set up a new profile that launches OpenVPN client whenever I start Spotify, if I am not connected to VPN. To do so, let us first create an application context for Spotify app. For the task, select Code and then Run Shell. Inside the command field, type in:

ifconfig | grep tun -A5 | grep UP

Also, make sure you check Continue task after error. I have saved the output of the variable to %OPENVPN.
Next, set an if statement to check if %OPENVPN is set. If it’s not set (which happens when ifconfig gives no output), launch Spotify.

One less repetitive task, a more beautiful world!

A very complicated simple person. Jack of all trades, master of a few. Loves to read books and well-written code. Fluently speaks several languages including JavaScript, PHP, Java, English, Bengali etc. Listens to loads of music everyday. PhD in mood-swing. Chess Grandmaster of disaster.