除了原生 API 之外,您还可以使用 Java API(可从 Java 或 Kotlin 代码中使用)访问 Google Play 服务中的 LiteRT。具体而言,Google Play 服务中的 LiteRT 可通过 LiteRT 解释器 API 使用。
使用 Interpreter 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"]],["最后更新时间 (UTC):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."]]