Answer:
In 1807, at the time of the first invasion of Portugal by Napoleon’s forces, the King of Portugal, João VI, fled to Brazil.
When French forces were finally defeated in Europe in 1815, King João decided to continue ruling from Brazil, founding the United Kingdom of Portugal, Brazil and the Algarves, leaving a strong British presence in Portugal.
Many people resented British influence and began a movement to reestablish the monarchy in Portugal, specifically a liberal, constitutional monarchy.
In 1820, the constitutionalists rose up in revolution, created a constitution, and forced the return of the Portuguese King.
King João returned to Portugal in April 1821, leaving behind his son and heir, Prince Dom Pedro, to rule Brazil as his regent.
On September 7, 1822, Prince Dom Pedro declared Brazil’s independence from Portugal, founding the Empire of Brazil, which led to a two-year war of independence.
Formal recognition came with a treaty signed by both Brazil and Portugal in late 1825.