O'Reilly logo

Hello, Android, 4th Edition by Ed Burnette

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Simulating Thought

In a real game we’d look ahead several plys until we either reached the end of the game (a win, loss, or draw) or a timer ran out. For this example, we’ll use a timer to simulate one second of think time.

Using a Handler and postDelayed

To start, we need to declare and initialize an Android Handler instance in GameFragment.java:

ticTacToev3/src/main/java/org/example/tictactoe/GameFragment.java
 
import​ android.os.Handler;
 
public​ ​class​ GameFragment ​extends​ Fragment {
 
// Data structures go here...
 
private​ ​Handler​ mHandler = ​new​ ​Handler​();
 
// ...
 
}

A handler is a class that lets us delay doing something until later. We call its postDelayed() method, passing it the code that we want to run when the timer ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required