“He had one son. He was 18, he was getting ready to go to college upstate, and somebody shot him in the street and killed him,” said Ms. Williams, 80. “He never got over it.”

Mr. Williams keeps a white candle lit in his own bedroom to remember his son, and has his baby picture hanging above his bed, she said. Ms. Williams said she believes her grandson started using heavy drugs to cope with his grief: “I think that was his downfall.”

Police records show that in 2018, Robert Williams, 18, died in a shooting in the Bronx. Ms. Williams confirmed that was her great-grandson.

In surveillance video, a man, who the police said was Mr. Williams, is seen calmly entering the 41st Precinct, which serves the Hunts Point neighborhood, at around 8 a.m. on Sunday. He glanced around and almost immediately opened fire, sending officers and civilian staff scrambling to shield themselves. One bullet struck the arm of a lieutenant, who then returned fire, but missed.

The man paused, appeared to hear returning gunshots, and then lay on the ground, sliding his gun along the floor to officers at the other end of the room.

“This coward immediately laid down, but only after he ran out of bullets,” Commissioner Shea said.

Mr. Williams was taken into custody at the precinct without further incident. He was charged Sunday with attempted murder, criminal possession of a weapon and resisting arrest.

Just 12 hours earlier, at around 8 p.m. on Saturday, the police said, Mr. Williams had approached two officers in a marked police vehicle a few blocks from that same station house. The officers had been posted in the neighborhood because there had been reports of drug dealing and shootings there recently, Commissioner Shea said.