IMO Guidelines for the Onboard Operational Use of Shipborne AIS state that AIS should always be in operation when ships are underway or at anchor.
If the master believes that the continual operation of AIS might compromise the safety or security of his/her ship, or where security incidents are imminent, the AIS may be switched off. This might be the case in sea areas where pirates and armed robbers are known to operate. Unless it would further compromise the safety or security, if the ship is operating in a mandatory ship reporting system, the master should report this action and the reason for doing so to the competent authority.