Oracle, another tech titan, had sued Google in 2010 for copyright infringement over what it said was copied computer code.
Android is now used in an estimated 70% of global smartphones, and damages could have run into the billions.
But the Supreme Court let Google off the hook, overturning a lower court's decision it had infringed copyright.
The court ruled six to two in favour of Google.
At issue was whether Google's use of Oracle's Java API - a widely-used "building block" for programmers - counted as "fair use" under US copyright law.
If it was, the fact that Google was accused of copying more than 11,000 lines of code would not matter.
Justice Stephen Breyer, in his written opinion, said that "to allow enforcement of Oracle's copyright here would risk harm to the public".
So many programmers used and had deep knowledge of Oracle's building blocks that such a move would turn computer code into "a lock limiting the future creativity of new programs".
"Oracle alone would hold the key," he warned.