Can I avoid attacks indefinitely by remaining online?

Basically, yes.
I have found that if I set the timeout on my device to "never", then I can avoid attacks from opponents nearly indefinitely. The game does have a 5 minute inactivity timer, after which you will be given a prompt to reload (and presumably you become vulnerable as soon as that prompt appears). However, if you keep the game active by moving every few minutes, you can avoid attack indefinitely. I have personally done so for hours now.

Edit:

One slight edit, that the games determination of "activity" seems to involve more than just scrolling around. When I just scroll around, I still seem to hit the activity timeout, but if I select building by clicking on them, the timeout is never triggered.


No you can't.

A break will occur after 3 hours of continuous play; you'll need to close the app for a few minutes before you can play again. This was apparently introduced to prevent players from staying online continuously and avoiding attacks.

Clash of Clans: Take a break