JERUSALEM — Prime Minister Benjamin Netanyahu of Israel and his former challenger, Benny Gantz, agreed Monday night to establish a unity government, a deal that finally breaks a yearlong political impasse and keeps Mr. Netanyahu in office as he faces trial on corruption charges.

After three inconclusive elections in the past year, the creation of the new government forestalls what had appeared to be an inevitable fourth election and offers a deeply divided Israel a chance for national healing as it battles the coronavirus pandemic.

For Mr. Netanyahu, the agreement buys him time to try to resolve two contentious issues central to his legacy: to sidestep his prosecution or at least prevent it from driving him from power, and to extend Israeli sovereignty over occupied territory.

The deal, announced by both men’s political parties at 7:15 p.m., adds to Mr. Netanyahu’s tenure as Israel’s longest-serving leader and, coming after his conservative coalition failed to win a majority, cements his reputation as a canny political survivor who can never be counted out.