除了原生 API 外,您也可以使用 Java API 存取 Google Play 服務中的 LiteRT,這些 API 可透過 Java 或 Kotlin 程式碼使用。具體來說,Google Play 服務中的 LiteRT 可透過 LiteRT 解譯器 API 使用。
使用解譯器 API
TensorFlow 執行階段提供的 LiteRT 解譯器 API,可提供建構及執行機器學習模型的通用介面。請按照下列步驟,使用 Google Play 服務執行階段中的 TensorFlow Lite 執行推論作業,透過 Interpreter API 執行推論。
1. 新增專案依附元件
在應用程式專案程式碼中加入下列依附元件,即可存取 LiteRT 適用的 Play 服務 API:
dependencies{...// LiteRT dependencies for Google Play servicesimplementation'com.google.android.gms:play-services-tflite-java:16.1.0'// Optional: include LiteRT Support Libraryimplementation'com.google.android.gms:play-services-tflite-support:16.1.0'...}
2. 新增 LiteRT 的初始化
使用 LiteRT API「之前」,先初始化 Google Play 服務 API 的 LiteRT 元件:
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-24 (世界標準時間)。"],[],[],null,["# LiteRT in Google Play services Java (and Kotlin) API\n\nLiteRT in Google Play services can also be accessed using Java APIs,\nwhich can be used from Java or Kotlin code, in\naddition to the Native API. In particular, LiteRT in Google Play\nservices is available through the [LiteRT Interpreter\nAPI](../../api/tflite/java/org/tensorflow/lite/InterpreterApi).\n\nUsing the Interpreter APIs\n--------------------------\n\nThe LiteRT Interpreter API, provided by the TensorFlow runtime,\nprovides a general-purpose interface for building and running ML models. Use the\nfollowing steps to run inferences with the Interpreter API using the TensorFlow\nLite in Google Play services runtime.\n\n### 1. Add project dependencies\n\n| **Note:** LiteRT in Google Play services uses the `play-services-tflite` package.\n\nAdd the following dependencies to your app project code to access the Play\nservices API for LiteRT: \n\n dependencies {\n ...\n // LiteRT dependencies for Google Play services\n implementation 'com.google.android.gms:play-services-tflite-java:16.1.0'\n // Optional: include LiteRT Support Library\n implementation 'com.google.android.gms:play-services-tflite-support:16.1.0'\n ...\n }\n\n### 2. Add initialization of LiteRT\n\nInitialize the LiteRT component of the Google Play services API\n*before* using the LiteRT APIs: \n\n### Kotlin\n\n```kotlin\nval initializeTask: Task\u003cVoid\u003e by lazy { TfLite.initialize(this) }\n```\n\n### Java\n\n```java\nTask\u003cVoid\u003e initializeTask = TfLite.initialize(context);\n```\n| **Note:** Make sure the `TfLite.initialize` task completes before executing code that accesses LiteRT APIs. Use the `addOnSuccessListener()` method, as shown in the next section.\n\n### 3. Create an Interpreter and set runtime option\n\nCreate an interpreter using `InterpreterApi.create()` and configure it to use\nGoogle Play services runtime, by calling `InterpreterApi.Options.setRuntime()`,\nas shown in the following example code: \n\n### Kotlin\n\n```kotlin\nimport org.tensorflow.lite.InterpreterApi\nimport org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime\n...\nprivate lateinit var interpreter: InterpreterApi\n...\ninitializeTask.addOnSuccessListener {\n val interpreterOption =\n InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)\n interpreter = InterpreterApi.create(\n modelBuffer,\n interpreterOption\n )}\n .addOnFailureListener { e -\u003e\n Log.e(\"Interpreter\", \"Cannot initialize interpreter\", e)\n }\n```\n\n### Java\n\n```java\nimport org.tensorflow.lite.InterpreterApi\nimport org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime\n...\nprivate InterpreterApi interpreter;\n...\ninitializeTask.addOnSuccessListener(a -\u003e {\n interpreter = InterpreterApi.create(modelBuffer,\n new InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY));\n })\n .addOnFailureListener(e -\u003e {\n Log.e(\"Interpreter\", String.format(\"Cannot initialize interpreter: %s\",\n e.getMessage()));\n });\n```\n\nYou should use the implementation above because it avoids blocking the Android\nuser interface thread. If you need to manage thread execution more closely, you\ncan add a `Tasks.await()` call to interpreter creation: \n\n### Kotlin\n\n```kotlin\nimport androidx.lifecycle.lifecycleScope\n...\nlifecycleScope.launchWhenStarted { // uses coroutine\n initializeTask.await()\n}\n```\n\n### Java\n\n```java\n@BackgroundThread\nInterpreterApi initializeInterpreter() {\n Tasks.await(initializeTask);\n return InterpreterApi.create(...);\n}\n```\n| **Warning:** Do not call `.await()` on the foreground user interface thread because it interrupts display of user interface elements and creates a poor user experience.\n\n### 4. Run inferences\n\nUsing the `interpreter` object you created, call the `run()` method to generate\nan inference. \n\n### Kotlin\n\n```kotlin\ninterpreter.run(inputBuffer, outputBuffer)\n```\n\n### Java\n\n```java\ninterpreter.run(inputBuffer, outputBuffer);\n```\n\nHardware acceleration\n---------------------\n\nLiteRT allows you to accelerate the performance of your model using\nspecialized hardware processors, such as graphics processing units (GPUs). You\ncan take advantage of these specialized processors using hardware drivers called\n[*delegates*](../performance/delegates).\n\nThe [GPU delegate](../performance/gpu) is provided through Google Play services\nand is dynamically loaded, just like the Play services versions of the\nInterpreter API.\n\n### Checking device compatibility\n\nNot all devices support GPU hardware acceleration with TFLite. In order to\nmitigate errors and potential crashes, use the\n`TfLiteGpu.isGpuDelegateAvailable` method to check whether a device is\ncompatible with the GPU delegate.\n\nUse this method to confirm whether a device is compatible with GPU, and use CPU\nas a fallback for when GPU is not supported. \n\n useGpuTask = TfLiteGpu.isGpuDelegateAvailable(context)\n\nOnce you have a variable like `useGpuTask`, you can use it to determine whether\ndevices use the GPU delegate. \n\n### Kotlin\n\n```kotlin\nval interpreterTask = useGpuTask.continueWith { task -\u003e\n val interpreterOptions = InterpreterApi.Options()\n .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)\n if (task.result) {\n interpreterOptions.addDelegateFactory(GpuDelegateFactory())\n }\n InterpreterApi.create(FileUtil.loadMappedFile(context, MODEL_PATH), interpreterOptions)\n}\n \n```\n\n### Java\n\n```java\nTask\u003cInterpreterApi.Options\u003e interpreterOptionsTask = useGpuTask.continueWith({ task -\u003e\n InterpreterApi.Options options =\n new InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY);\n if (task.getResult()) {\n options.addDelegateFactory(new GpuDelegateFactory());\n }\n return options;\n});\n \n```\n\n### GPU with Interpreter APIs\n\nTo use the GPU delegate with the Interpreter APIs:\n\n1. Update the project dependencies to use the GPU delegate from Play services:\n\n implementation 'com.google.android.gms:play-services-tflite-gpu:16.2.0'\n\n2. Enable the GPU delegate option in the TFlite initialization:\n\n ### Kotlin\n\n ```kotlin\n TfLite.initialize(context,\n TfLiteInitializationOptions.builder()\n .setEnableGpuDelegateSupport(true)\n .build())\n ```\n\n ### Java\n\n ```java\n TfLite.initialize(context,\n TfLiteInitializationOptions.builder()\n .setEnableGpuDelegateSupport(true)\n .build());\n ```\n3. Enable GPU delegate in the interpreter options: set the delegate factory to\n GpuDelegateFactory by calling `addDelegateFactory()\n within`InterpreterApi.Options()\\`:\n\n ### Kotlin\n\n ```kotlin\n val interpreterOption = InterpreterApi.Options()\n .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)\n .addDelegateFactory(GpuDelegateFactory())\n ```\n\n ### Java\n\n ```java\n Options interpreterOption = InterpreterApi.Options()\n .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)\n .addDelegateFactory(new GpuDelegateFactory());\n ```\n\nMigrating from stand-alone LiteRT\n---------------------------------\n\nIf you are planning to migrate your app from stand-alone LiteRT to the\nPlay services API, review the following additional guidance for updating your\napp project code:\n\n1. Review the [Limitations](#limitations) section of this page to ensure your use case is supported.\n2. Prior to updating your code, we recommend doing performance and accuracy checks for your models, particularly if you are using versions of LiteRT (TF Lite) earlier than version 2.1, so you have a baseline to compare against the new implementation.\n3. If you have migrated all of your code to use the Play services API for LiteRT, you should remove the existing LiteRT *runtime\n library* dependencies (entries with `org.tensorflow:`**tensorflow-lite**`:*`) from your build.gradle file so that you can reduce your app size.\n4. Identify all occurrences of `new Interpreter` object creation in your code, and modify each one so that it uses the `InterpreterApi.create()` call. The new `TfLite.initialize` is asynchronous, which means in most cases it's not a drop-in replacement: you must register a listener for when the call completes. Refer to the code snippet in [Step 3](#step_3_interpreter) code.\n5. Add `import org.tensorflow.lite.InterpreterApi;` and `import\n org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime;` to any source files using the `org.tensorflow.lite.Interpreter` or `org.tensorflow.lite.InterpreterApi` classes.\n6. If any of the resulting calls to `InterpreterApi.create()` have only a single argument, append `new InterpreterApi.Options()` to the argument list.\n7. Append `.setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)` to the last argument of any calls to `InterpreterApi.create()`.\n8. Replace all other occurrences of the `org.tensorflow.lite.Interpreter` class with `org.tensorflow.lite.InterpreterApi`.\n\nIf you want to use stand-alone LiteRT and the Play services API\nside-by-side, you must use LiteRT (TF Lite) version 2.9 or later.\nLiteRT (TF Lite) version 2.8 and earlier versions are not compatible with the\nPlay services API version."]]