Previous — 2: one button, one answer · עברית
This experiment deliberately freezes the screen. Start with a successful Gemini response in lesson 2. Save that working version so you can restore it after the experiment. If you tried model.generateContent(prompt).get() from an earlier version of this lesson, restore the lesson 2 callback before applying the edits below.
1. Add a button with a visible tap counter
In app > res > layout > activity_main.xml, add the test button above Ask LLM and anchor Ask LLM below it.
tools:text shows the initial label in Android Studio’s Layout Editor. The Java code sets the label when the app runs.
tools:context=".MainActivity">
+ <Button
+ android:id="@+id/nothing_btn"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_margin="16dp"
+ tools:text="Tap test (0)"
+ app:layout_constraintTop_toTopOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/ask_llm"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Ask LLM"
- app:layout_constraintTop_toTopOf="parent"
+ app:layout_constraintTop_toBottomOf="@id/nothing_btn"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
In app > res > values > strings.xml, add this line inside <resources>. %1$d inserts the number of taps into the button label.
<string name="tap_test_count">Tap test (%1$d)</string>
In MainActivity, add testTapCount after the binding field. The int field starts at zero.
private ActivityMainBinding binding;
+private int testTapCount;
In onCreate, after the window insets listener and before FirebaseApp.initializeApp(this), give the button its initial label and update it on every tap.
binding.nothingBtn.setText(getString(R.string.tap_test_count, testTapCount));
binding.nothingBtn.setOnClickListener(v -> {
testTapCount++;
binding.nothingBtn.setText(getString(R.string.tap_test_count, testTapCount));
});
Build and run with the lesson 2 callback still in place. Check that Tap test (0) becomes Tap test (1) after one tap. Press Ask LLM and tap Tap test while the request runs. The counter can update before Gemini answers.
2. Let the request finish while the screen is frozen
Firebase’s Java generateContent() returns a future. Its Java wrapper resumes the request on the UI thread by default. Calling get() on that thread can deadlock because the request needs the thread that is waiting for it. In this experiment, runBlocking calls Firebase’s suspending generateContent on Dispatchers.IO and waits for the actual reply on the UI thread. The project already has Kotlin coroutines through its existing dependencies. Kotlin documentation for runBlocking
Open app > kotlin+java > your package > MainActivity. Update the imports as shown.
-import androidx.core.content.ContextCompat;
-import com.google.firebase.ai.java.GenerativeModelFutures;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
+import java.util.Collections;
+import java.util.concurrent.CancellationException;
+import kotlinx.coroutines.BuildersKt;
+import kotlinx.coroutines.Dispatchers;
+import kotlinx.coroutines.TimeoutCancellationException;
+import kotlinx.coroutines.TimeoutKt;
In onCreate, remove GenerativeModelFutures model = GenerativeModelFutures.from(ai); and keep the line that creates ai. Inside the existing binding.askLlm.setOnClickListener, keep the lines that set Thinking…, disable the button and build prompt. Replace the block immediately after .build();.
.build();
- // Start asynchronously: future is a handle, not the answer.
- ListenableFuture<GenerateContentResponse> future = model.generateContent(prompt);
- // Attach ONE callback object with TWO possible outcome methods.
- Futures.addCallback(future, new FutureCallback<GenerateContentResponse>() {
- /** Called on success; result is supplied by the callback mechanism. */
- @Override
- public void onSuccess(GenerateContentResponse result) {
- if (isFinishing() || isDestroyed()) return;
- String text = result.getText(); // SDK already decoded the response.
- binding.answerLabel.setText(text != null ? text : "No text returned.");
- binding.askLlm.setEnabled(true);
- }
-
- /** Called on failure; error describes what went wrong. */
- @Override
- public void onFailure(Throwable error) {
- if (isFinishing() || isDestroyed()) return;
- binding.answerLabel.setText("Request failed: " + error.getMessage());
- binding.askLlm.setEnabled(true);
- }
- }, ContextCompat.getMainExecutor(this)); // Run BOTH callbacks on the UI thread.
- // This click callback ends now; the screen does not wait for the answer.
+ try {
+ GenerateContentResponse result = BuildersKt.runBlocking(Dispatchers.getIO(),
+ (scope, continuation) -> TimeoutKt.withTimeout(30_000L,
+ (requestScope, requestContinuation) -> ai.generateContent(
+ Collections.singletonList(prompt), requestContinuation),
+ continuation));
+ String text = result.getText(); // SDK already decoded the response.
+ binding.answerLabel.setText(text != null ? text : "No text returned.");
+ } catch (InterruptedException error) {
+ Thread.currentThread().interrupt();
+ binding.answerLabel.setText("Request interrupted.");
+ } catch (TimeoutCancellationException error) {
+ binding.answerLabel.setText("Request timed out.");
+ } catch (CancellationException error) {
+ binding.answerLabel.setText("Request canceled.");
+ } catch (Exception error) {
+ binding.answerLabel.setText("Request failed: " + error);
+ } finally {
+ binding.askLlm.setEnabled(true);
+ }
});
The request runs on Dispatchers.IO while runBlocking blocks the UI thread until the result is ready. Kotlin normally supplies the continuation arguments when calling suspending functions. In Java, those arguments are explicit. withTimeout(30_000L, ...) cancels the pending request on timeout and the app displays Request timed out. The finally block re-enables the button when the wait ends.
3. Make the freeze visible
- Build and run again. Press Tap test once while the app is idle and verify that the label changes from Tap test (0) to Tap test (1).
- Press Ask LLM and immediately tap Tap test again. While
runBlockingis waiting, the UI thread cannot process the tap or redraw the button, so it still shows Tap test (1). If Android queues the tap, the counter can change to (2) when the answer appears. - Once the answer is visible, tap Tap test again. The counter should increase immediately. A fast Gemini response can make the freeze hard to catch. If Android shows Application Not Responding (ANR), choose Wait if available. Android ANR documentation
Why did lesson 2 stay responsive? Its click handler returned immediately after registering the callback, so Android could draw Thinking… and process touches. The result callback itself ran briefly on the UI thread once the response was ready.
After the experiment, restore the lesson 2 model wrapper, imports, and callback. You can keep the tap counter to repeat the comparison.