Flutter:如何让外部应用程序打开文件(例如Android的隐式意图)?

Jef*_*Poe 6 android flutter

我正在构建一个Flutter应用程序,该应用程序本质上是从云中获取数据的。数据类型各不相同,但它们通常是图像,pdf,文本文件或存档文件(zip文件)。

现在,我想触发一个隐式意图,以便用户可以选择自己喜欢的应用程序来处理有效负载。

我已经搜索了答案,并且尝试了以下路线:

  1. url_launcher插件(如如何从Flutter应用程序中打开应用程序中所建议)
  2. android意图
  3. 共享插件

路线3并不是我真正想要的,因为它使用的是平台的“共享”机制(即在Twitter上发布/发送给联系人),而不是打开有效负载。

1号和2号公路的运作方式……以一种不稳定,怪异的方式。我稍后再解释。

这是我的代码流:

import 'package:url_launcher/url_launcher.dart';

// ...
// retrieve payload from internet and save it to an External Storage location
File payload = await getPayload();
String uriToShare = samplePayload.uri.toString();

// at this point uriToShare looks like: 'file:///storage/emulated/0/jpg_example.jpg'
uriToShare = uriToShare.replaceFirst("file://", "content://");

// launch url    
if (await canLaunch(uriToShare)) {
  await launch(uriToShare);
} else {
  throw "Failed to launch $uriToShare";
Run Code Online (Sandbox Code Playgroud)

上面的代码是使用url_launcher插件。如果我使用的是android_intent插件,那么最后几行代码将变为:

// fire intent 
AndroidIntent intent = AndroidIntent(
  action: "action_view",
  data: uriToShare,
);
await intent.launch();
Run Code Online (Sandbox Code Playgroud)

将文件保存到外部目录的所有操作均正常(运行代码后,我可以确认文件存在)

当我尝试共享URI时,事情变得很奇怪。我已经在3种不同的手机上测试了这段代码。其中之一(三星Galaxy S9)将抛出此异常:

I/io.flutter.plugins.androidintent.AndroidIntentPlugin(10312): Sending intent Intent { act=android.intent.action.VIEW dat=content:///storage/emulated/0/jpg_example.jpg }
E/MethodChannel#plugins.flutter.io/android_intent(10312): Failed to handle method call
E/MethodChannel#plugins.flutter.io/android_intent(10312): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.VIEW dat=content:///storage/emulated/0/jpg_example.jpg cmp=com.google.android.gm/.browse.TrampolineActivity } from ProcessRecord{6da6f74 10312:com.safe.fmeexpress/u0a218} (pid=10312, uid=10218) requires com.google.android.gm.permission.READ_GMAIL
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.os.Parcel.readException(Parcel.java:1959)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.os.Parcel.readException(Parcel.java:1905)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.app.IActivityManager$Stub$Proxy.startActivity(IActivityManager.java:4886)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.app.Instrumentation.execStartActivity(Instrumentation.java:1617)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.app.Activity.startActivityForResult(Activity.java:4564)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.app.Activity.startActivityForResult(Activity.java:4522)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.app.Activity.startActivity(Activity.java:4883)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.app.Activity.startActivity(Activity.java:4851)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at io.flutter.plugins.androidintent.AndroidIntentPlugin.onMethodCall(AndroidIntentPlugin.java:141)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:191)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at io.flutter.view.FlutterNativeView.handlePlatformMessage(FlutterNativeView.java:152)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.os.MessageQueue.next(MessageQueue.java:325)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.os.Looper.loop(Looper.java:142)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at android.app.ActivityThread.main(ActivityThread.java:6938)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
E/MethodChannel#plugins.flutter.io/android_intent(10312):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Run Code Online (Sandbox Code Playgroud)

我不知道意图是如何被污染的 cmp=com.google.android.gm/.browse.TrampolineActivity

此异常仅发生在Galaxy S9中。另外两部手机没有给我这个问题。他们确实启动了文件uri,有人问我如何打开文件,但没有提供任何图像处理应用程序(例如Gallery,QuickPic或Google Photos)。

需要澄清的是,url_launcherandroid_intent路线都会得出完全相同的结果。

感觉好像我在这里错过了一步。谁能指出我做错了什么?我是否必须开始使用平台渠道来完成此任务?

关于为什么要做我的一些澄清:

  • 将uri类型从file://转换为content://,因为我正在获取 android.os.FileUriExposedException
  • 将临时文件存储在外部存储中,因为我现在还不想处理授予URI READ PERMISSION的问题。(我尝试过,但是android_intent还没有设置意图标志的方法)

Kri*_*ian 7

既然这个问题得到了解答,一个优秀的flutter插件open_filex已经发布,解决了这个跨平台问题。

当与path_provider结合使用时 - 在以下示例中下载到getTemporaryDirectory(),这将在 iOS 和 Android 上使用关联的应用程序打开给定的 url/文件名(如果已下载,则使用本地文件):

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:open_filex/open_filex.dart';

Future<String> download(String url, String filename) async {
  String dir = (await getTemporaryDirectory()).path;
  File file = File('$dir/$filename');
  if (await file.exists()) return file.path;
  await file.create(recursive: true);
  var response = await http.get(url).timeout(Duration(seconds: 60));

  if (response.statusCode == 200) {
    await file.writeAsBytes(response.bodyBytes);
    return file.path;
  }
  throw 'Download ${url} failed';
}

void downloadAndLaunch(String url, String filename) {
  download(url, filename).then((String path) {
    OpenFilex.open(path);
  });
}
Run Code Online (Sandbox Code Playgroud)

-- 编辑: --
将引用从 更改open_fileopen_filex,因为原始包默认在 android 上请求 REQUEST_INSTALL_PACKAGES 权限。这将从 2022 年 9 月起阻止 Google Play 中的审核。


bof*_*mer 6

很难让它正常工作。以下是一些帮助我ACTION_VIEW从 Flutter启动意图的提示,以及使用 Flutter 下载的文件。

1)FileProvider在android清单中注册一个:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example.myapp.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>
Run Code Online (Sandbox Code Playgroud)

provider_paths.xml

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path name="external_files" path="." />
    </paths>
Run Code Online (Sandbox Code Playgroud)

2)创建一个提供2种方法的自定义平台通道(下面的代码是Kotlin):

getDownloadsDir: 应返回应放置下载文件的数据目录。试试这个:

val downloadsDir = applicationContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).path
result.success(downloadsDir);
Run Code Online (Sandbox Code Playgroud)

previewFile即需要2个字符串参数:pathFile.path在DART)和type(例如, “应用/ PDF”):

val file = File(path);
val uri = FileProvider.getUriForFile(this, "com.example.myapp.provider", file);

val viewFileIntent = Intent(Intent.ACTION_VIEW);
viewFileIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_GRANT_READ_URI_PERMISSION);
viewFileIntent.setDataAndType(uri, type);
try {
  startActivity(viewFileIntent);
  result.success(null);
} catch (e: ActivityNotFoundException) {
  result.error(...);
}
Run Code Online (Sandbox Code Playgroud)

最重要的部分是创建FileProvider. url_launcher 和 android_intent 不起作用,您必须创建自己的平台频道。您可以更改下载路径,但您还必须找到正确的提供程序/权限设置。

在 iOS 上进行这项工作也是可能的,但超出了这个问题的范围。


如果您使用的是 image_picker 插件:

FileProvider与image_picker(0.4.6)插件的当前版本冲突,修复不久将公布。