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.

But exactly what effect the lawsuit will have on the war on 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 Trump administration’s campaign to beat the AIDS epidemic.

On Wednesday, Mr. Azar struck a much harsher tone. “Gilead must respect the U.S. patent system, the groundbreaking work by C.D.C. researchers, and the substantial taxpayer contributions to the development of these drugs,” he said in a prepared statement.

The lawsuit bluntly accused Gilead of exaggerating its role in developing pre-exposure prophylaxis, or PrEP, ignoring work by government scientists and “baselessly denying” the validity of federal patents.

The Department of Health and Human Services declined to explain on Thursday what led Mr. Azar to change his tone and request a jury trial.

“The fact that the federal government sued a drug maker over a medication developed in part with taxpayer money is a milestone,” said Zain Rizvi, a researcher in the medicines access program at the advocacy organization Public Citizen.

“We hope it marks a fundamental shift in how the government will think about the many other medicines developed using public funding that remain unaffordable for millions of Americans,” Mr. Rizvi said.

Gilead has responded that the government patents are invalid and denied infringing them.

The government first applied for patents on prophylaxis techniques in 2006. Gilead recently asked the Patent and Trademark Office to cancel the government patents, arguing that other researchers already had conceived the idea of using drugs to prevent H.I.V.

Gilead said it would ask the court to stay the government’s suit until the patent office reaches a decision.

PrEP is a drug regimen: A person at risk of contracting H.I.V. is prescribed one of two drugs to be taken in pill form once daily to prevent the infection. Both of the drugs approved for use in this regimen, Truvada and Descovy, are made by Gilead.

If taken daily, the drugs cut the risk of H.I.V. infection by more than 99 percent. Public health officials are eager to get more people on PrEP, and the Trump administration in February announced an enormous effort to get the drugs to people in high-risk communities.

About one million Americans are at high risk of getting H.I.V. through sex or shared needles and would benefit from PrEP, according to the Centers for Disease Control and Prevention. But just 270,000 Americans are on PrEP, and there are about 40,000 new infections each year.

The price has been an obstacle, critics say. Truvada, which will come off patent next year, has cost about $20,000 per patient per year in recent years; Descovy currently costs about the same. In other countries, generic versions of Truvada sell for as little as $60 a year.

Gilead has said that virtually no patient pays the list price, and that those who cannot afford the drug may qualify for assistance.

The Justice Department, which filed the suit on behalf of the Department of Health and Human Services, could seek billions of dollars in royalties, not only on previous sales of Truvada but also on future sales of Descovy.

Alternatively, the government could use the suit as leverage to force Gilead to lower the price of Descovy as part of any settlement.

The lawsuit, which was announced late Wednesday evening, does not seek a specific amount in damages. The Financial Times estimated in August that the government could reasonably claim about $1 billion in back royalties on Truvada, based on the strength of the patents and third-party sales estimates.

Moreover, the government’s brief argued that Gilead’s conduct was “malicious, wanton, deliberate, consciously wrongful, flagrant and in bad faith.” If the court finds that Gilead’s infringement was “willful,” it could trigger a provision for enhanced damages, which could total up to $3 billion.

If the government were to win or force a rich settlement, it is unclear what it will do with the money. AIDS activists are adamant that any award should not simply go into the Treasury Department’s coffers, but should be dedicated to helping uninsured Americans get on PrEP.

The government lawsuit was not expected by many AIDS advocates.

The department and Gilead have been in discussions over increasing access to Truvada, and the company’s pricing practices have been the subject of congressional hearings. But federal officials had seemed eager to accommodate, or even reward, Gilead.

“In 15 years, PrEP has never ceased to surprise me,” said Mitchell J. Warren, executive director of AVAC, an H.I.V.-prevention advocacy group based in New York. “This was an action I did not expect to see, especially after the announcement about Gilead’s donation.”

In May, Gilead and H.H.S. jointly announced that the company would donate enough Truvada to cover 200,000 patients for up to 11 years. The recipients were to be switched to a more expensive replacement, Descovy, once it was approved for prevention of H.I.V. infection.

The Food and Drug Administration approved Descovy last month.

Although Mr. Azar praised Gilead for its donation, H.I.V. activists and some medical experts greeted the arrangement with suspicion, saying that it appeared to be an effort to build a market for Descovy.

Gilead has made about $3 billion a year on Truvada and would presumably make at least that much on Descovy, if insurers and government programs switch patients to the new drug instead of adopting generic equivalents to Truvada.

Descovy contains tenofovir alafenamide, a precursor molecule to tenofovir disoproxil, the main drug in Truvada. Gilead claims Descovy is less likely than Truvada to cause kidney damage or bone loss.

Critics note that Truvada is safe, and that Gilead has said so for years. They also point to a study suggesting that Descovy raises cholesterol levels more than Truvada does.

In September, four months after news of Gilead’s donation, H.H.S. announced that it would award the drug maker a $6 million contract to distribute donated Truvada and Descovy. The six-month contract, with a renewal option, paid Gilead to distribute the drugs to about 4,000 needy people.

But most drug makers already have programs like this one — including Gilead, which since 2012 has run a medication assistance program through which the company has provided Truvada free of charge to about 20,000 people each year.

Activists for H.I.V. patients said 4,000 more recipients amounted to a drop in the bucket, compared with the overall need. And they wondered why the government should pay for a separate distribution program when Gilead already has one.

“I’m very confused about who except Gilead is benefiting from this arrangement,” said Jeremiah Johnson, a project director at Treatment Action Group, an H.I.V. advocacy organization.

Individuals with drug addictions or mental problems, or who are homeless or live in distant rural areas, are very difficult and expensive for public health departments to enroll and keep on PrEP.

But there was no indication in the Gilead contract that such intensive services would be provided. The drug maker’s current assistance program simply provides Truvada free to anyone who comes to a pharmacy with a prescription, lacks health insurance and earns less than $62,450 a year.

Credit…Gilead Sciences

The basis of the government’s patent claim is that, in the early 2000s, scientists at the C.D.C. did many experiments on monkeys to see if antiretroviral drugs given subcutaneously, in vaginal or anal gels, or as oral pills, would protect them against infection with the simian version of H.I.V.

Government scientists ultimately found that a combination of tenofovir and emtricitabine was the most effective at stopping the virus, said James Krellenstein, a founder of the advocacy group Prep4All Collaboration.

Common mutations that make the virus less susceptible to tenofovir make it more susceptible to emtricitabine, and vice versa, he added. The government patented the prophylactic use of tenofovir and its precursor drugs, including the version of tenofovir in Descovy.

Although the government started applying for patents in 2006, some were not granted until 2015 and one was granted only in July.

(The C.D.C. patents were recognized in Europe, and generic companies that sell the drug in Europe, Canada and Australia are paying royalties to the agency.)

Gilead, the government contends, relied on those C.D.C. experiments in its application to the F.D.A. for approval to use Truvada for prophylaxis.

The crucial 2010 study proving that Truvada prevented H.I.V., called iPrEx, was conducted by Dr. Robert M. Grant of the University of California, San Francisco, and paid for by the National Institutes of Health and the Bill and Melinda Gates Foundation.

Gilead’s only role, Dr. Grant said, was to provide Truvada free of charge.

In a recent interview, he said that Gilead had indicated that Truvada would be off patent by the time his study was finished. But Gilead maintains that its patents will not expire until 2021.

Tenofovir was invented in Czechoslovakia in 1985, and Gilead later purchased the American patent rights.

Patents normally last for 20 years, but drug companies often do everything they can to “evergreen” them and head off generic competition by making small changes in the molecules, the combinations made with them, or the way they are delivered.

Gilead first released Truvada for H.I.V. treatment in 2004, charging less than $10,000 a year.

After it was approved for prevention in 2012, however, Gilead slowly raised the price to about $20,000.

[Like the Science Times page on Facebook. | Sign up for the Science Times newsletter.]

The company also sued every generic maker that tried to enter the market, and then reached out-of-court settlements with each one. The details were kept secret, but activists believe that Gilead paid each company millions of dollars to stay out of the market — “pay-for-delay” deals.

In June, Senator Debbie Stabenow, Democrat of Michigan, and the late Representative Elijah Cummings, Democrat of Maryland, asked the Government Accountability Office to open an investigation into why H.H.S. had not enforced its patents against Gilead.

“After shining a light on Gilead’s unfair practices, I am pleased to see H.H.S. decide to take action against Gilead,” Ms. Stabenow said Thursday.

“Drug companies should not be able to charge patients tens of thousands of dollars for lifesaving treatments, discovered through taxpayer-funded research, nor should they be allowed to infringe on government-owned intellectual property with impunity.”

Activists have also been privately and publicly pressing government officials to act.

In March, Larry Kramer, the playwright and founder of Gay Men’s Health Crisis and Act-Up, released an open letter to Dr. Anthony S. Fauci, the director of the National Institute for Allergy and Infectious Disease and a lifelong AIDS specialist, asking, “Are you the heavy or the hero, Tony?”

He argued that Dr. Fauci had the legal authority to withdraw Gilead’s patents because of his agency’s funding of them and asked, “Why are you not doing so?”

Asked about that, Dr. Fauci said the agency “does not want to mess up the litigation, so they are adamant about no one commenting on this at all.”