You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Flutter中获取Android指定应用的APK文件路径方法

在Flutter中获取指定应用的APK路径

你已经通过installed_apps拿到了已安装应用列表,要获取目标应用实际运行的APK路径,可按以下步骤实现:

1. 确认目标应用的包名

从installed_apps返回的列表项中提取目标应用的包名(通常字段名为packageName),这是定位APK的核心标识。

2. 通过MethodChannel调用原生Android代码获取路径

Flutter没有直接提供该API,需要借助原生Android代码实现,再通过MethodChannel将结果传递回Dart层:

Android端原生实现

在项目的android/app/src/main/kotlin/[你的包名]/MainActivity.kt中添加代码:

import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    private val CHANNEL = "com.your.app/apk_path"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "getApkPath") {
                val packageName = call.argument<String>("packageName")
                if (packageName == null) {
                    result.error("INVALID_ARGUMENT", "包名不能为空", null)
                    return@setMethodCallHandler
                }
                try {
                    val packageInfo: PackageInfo = packageManager.getPackageInfo(packageName, 0)
                    val apkPath = packageInfo.applicationInfo.sourceDir
                    result.success(apkPath)
                } catch (e: PackageManager.NameNotFoundException) {
                    result.error("PACKAGE_NOT_FOUND", "未找到目标应用", e)
                }
            } else {
                result.notImplemented()
            }
        }
    }
}

Flutter端调用代码

在Dart文件中创建工具类并调用原生方法:

import 'package:flutter/services.dart';

class ApkPathHelper {
  static const MethodChannel _channel = MethodChannel('com.your.app/apk_path');

  static Future<String?> getApkPath(String packageName) async {
    try {
      final String? path = await _channel.invokeMethod('getApkPath', {'packageName': packageName});
      return path;
    } on PlatformException catch (e) {
      print("获取路径失败: ${e.message}");
      return null;
    }
  }
}

// 使用示例
void fetchTargetApkPath() async {
  String targetPackage = "com.example.targetapp"; // 替换为目标应用包名
  String? apkPath = await ApkPathHelper.getApkPath(targetPackage);
  if (apkPath != null) {
    print("APK路径: $apkPath");
    // 此处可将路径展示给用户
  }
}

3. 注意事项

  • packageInfo.applicationInfo.sourceDir会直接返回应用实际运行的APK完整路径,无需手动判断是系统应用(/system路径)还是第三方应用(/data路径),原生API会自动返回正确路径。
  • 该操作不需要额外申请权限,属于正常的应用信息查询范畴。

内容的提问来源于stack exchange,提问作者Jan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 13:42:08