Firebase AI Logic (LLM) — 3: מקפיאים את המסך


מחכים ל־Gemini על ה־UI thread ורואים איך המסך קופא וחוזר להגיב

הקודם — 2: כפתור אחד ותשובה אחת · English

זהו ניסוי מכוון בחסימת המסך. התחילו אחרי שקיבלתם תשובה מ־Gemini בשיעור 2. שמרו את הגרסה שעובדת כדי שתוכלו לחזור אליה בסוף הניסוי. אם ניסיתם את model.generateContent(prompt).get() מגרסה קודמת של השיעור, החזירו את ה־callback של שיעור 2 לפני העריכה.

1. מוסיפים כפתור עם מונה לחיצות

ב־app > res > layout > activity_main.xml הוסיפו את כפתור הבדיקה מעל Ask LLM ועגנו את Ask LLM מתחתיו.

המאפיין tools:text מציג את הכיתוב הראשוני בעורך העיצוב של Android Studio. בזמן הריצה קוד ה־Java קובע את הכיתוב שמופיע על הכפתור.

     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" />

ב־app > res > values > strings.xml הוסיפו את השורה הזאת בתוך <resources>. הסימון %1$d משבץ את מספר הלחיצות בכיתוב של הכפתור.

<string name="tap_test_count">Tap test (%1$d)</string>

ב־MainActivity הוסיפו את testTapCount אחרי התכונה binding. הערך ההתחלתי של תכונה מסוג int הוא אפס.

 private ActivityMainBinding binding;
+private int testTapCount;

בתוך onCreate, אחרי המאזין לשוליים של החלון ולפני FirebaseApp.initializeApp(this), אתחלו את הכיתוב של הכפתור ועדכנו אותו בכל לחיצה.

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));
});

בנו והריצו כשה־callback של שיעור 2 עדיין פעיל. בדקו שלחיצה אחת משנה את הכיתוב מ־Tap test (0) ל־Tap test (1). לחצו על Ask LLM ואז על Tap test בזמן הבקשה. המונה יכול להתעדכן עוד לפני ש־Gemini עונה.

2. מאפשרים לבקשה להסתיים כשהמסך קפוא

הקריאה ל־generateContent() של Java מחזירה future. מעטפת ה־Java של Firebase ממשיכה את הבקשה על ה־UI thread כברירת מחדל. אם קוראים ל־get() על אותו thread, הבקשה עלולה להיתקע כי היא זקוקה ל־thread שמחכה לה. בניסוי runBlocking מפעילה את גרסת generateContent של Kotlin על Dispatchers.IO ומחכה לתשובה אמיתית על ה־UI thread. התלויות הקיימות כבר כוללות את ספריית ה־coroutines של Kotlin. תיעוד runBlocking של Kotlin

פתחו את app > kotlin+java > החבילה שלכם > MainActivity. עדכנו את ה־imports לפי הסימונים.

-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;

ב־onCreate הסירו את השורה GenerativeModelFutures model = GenerativeModelFutures.from(ai); והשאירו את יצירת ai. במאזין הקיים binding.askLlm.setOnClickListener, השאירו את השורות שמעדכנות את הטקסט ל־Thinking…, משביתות את הכפתור ובונות את prompt. החליפו את הקטע שאחרי .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);
+    }
 });

הבקשה רצה על Dispatchers.IO בזמן ש־runBlocking חוסמת את ה־UI thread עד שהתשובה מוכנה. בקריאה לפונקציית suspend שפת Kotlin מוסיפה את פרמטרי ה־continuation, ובקוד Java מעבירים אותם במפורש. אם נגמר הזמן שקובע withTimeout(30_000L, ...), הבקשה מתבטלת והאפליקציה מציגה Request timed out. הבלוק finally מפעיל שוב את הכפתור בסיום.

3. רואים את המסך קופא

  1. בנו והריצו שוב. כשהאפליקציה ממתינה לקלט, לחצו פעם אחת על Tap test ובדקו שהכיתוב משתנה מ־Tap test (0) ל־Tap test (1).
  2. לחצו על Ask LLM ומיד לחצו שוב על Tap test. כל עוד runBlocking מחכה, ה־UI thread לא יכול לעבד את הלחיצה או לצייר מחדש את הכפתור, ולכן עדיין מופיע Tap test (1). אם אנדרואיד שומר את הלחיצה בתור, המונה יכול לגדול ל־(2) כשהתשובה מופיעה.
  3. כשהתשובה מופיעה, לחצו שוב על Tap test. המונה אמור לגדול מיד. אם Gemini עונה מהר, ייתכן שיהיה קשה להבחין בקיפאון. אם אנדרואיד מציג Application Not Responding (ANR), בחרו Wait אם האפשרות מופיעה. תיעוד ANR של Android

למה המסך בשיעור 2 נשאר פעיל? פעולת הלחיצה הסתיימה מיד אחרי רישום ה־callback, ולכן אנדרואיד היה פנוי לצייר את Thinking… ולקבל נגיעות. ה־callback עצמו רץ לזמן קצר על ה־UI thread כשהתשובה כבר הייתה מוכנה.

בסיום הניסוי החזירו את מעטפת המודל, ה־imports וה־callback של שיעור 2. אפשר להשאיר את מונה הלחיצות כדי לחזור על ההשוואה.

Firebase GenerativeModel · תיעוד withTimeout של Kotlin