After years of prodding by patient advocates, federal officials on Wednesday sued the drug maker Gilead Sciences, charging that it had infringed government patents on the idea of preventing H.I.V. with a daily pill.

The suit, by the Department of Health and Human Services, came as a pleasant shock to many critics of the company, including Democratic members of Congress who had pressed the administration to act.

It is very rare for the government to take on a drug maker over patents. But the medications made by Gilead are necessary to end the AIDS epidemic by 2030, which the Trump administration has set as a goal. That cannot be accomplished if the drugs are not made more affordable.

Still, exactly what effect the lawsuit will have in the fight against AIDS remains unclear.

Certainly, it was an unexpected turnabout by Alex M. Azar II, the secretary of health and human services. In May, he had praised Gilead for donating Truvada to the administration’s campaign to beat the AIDS epidemic.