繁体   English   中英

Flutter:当应用程序在后台时使用路径提供程序

[英]Flutter: Using path provider when app is in background

我目前正在尝试在我的 Flutter 应用程序中实现 FCM 和本地通知。 我已经成功地为普通通知配置了 FCM 和本地通知,但我也有不同类型的通知,我想用图像显示,当我的应用程序在前台时,通知显示没有错误,但是当我终止时应用程序/将其移至后台尝试使用路径提供程序保存图像时出现异常。

例外:

MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)

我假设发生此错误是因为当应用程序不在前台时路径提供程序方法通道已关闭,我能做些什么来解决这个问题吗? 或者,如果不是flutter_local_notifications插件需要 bitmap 的文件路径,我可以实现保存图像并以不同的方式获取在后台工作的路径(没有路径提供程序)? (我实际上想要显示的是来自这样一个链接的图像: https://is1-ssl.mzstatic.com/image/thumb/WNUBiv2P6YSklHn9eA5nlg/1000x1000bb.jpeg

保存图像:

 static Future<String> saveImage(Image image) {
    final completer = Completer<String>();
    image.image.resolve(ImageConfiguration()).addListener(ImageStreamListener((imageInfo,_) async {
      final byteData = await imageInfo.image.toByteData(format: ImageByteFormat.png);
      final pngBytes = byteData.buffer.asUint8List();
      final fileName = pngBytes.hashCode;
      final directory = await getApplicationDocumentsDirectory();
      final filePath = '${directory.path}/$fileName';
      final file = File(filePath);
      await file.writeAsBytes(pngBytes);
      completer.complete(filePath);
    }));
    return completer.future;
  }

您还需要在 Application.java 中注册路径提供程序。

import io.flutter.plugins.pathprovider.PathProviderPlugin;

...

    @Override
    public void registerWith(PluginRegistry registry) {
PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"));
    }

现在 flutter 使用 Kotlin 作为 android 端的默认语言,这里是 Kotlin 代码:

override fun registerWith(registry: PluginRegistry) {
    io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
    PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"))
}

发生此错误是因为您没有在 android MainAcitivity 中注册 flutter 插件。

您必须更改MainActivityonCreate方法,如下所示:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this.getFlutterEngine());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM