Code Monkey home page Code Monkey logo

open_file's Introduction

open_file

pub package

A plug-in that can call native APP to open files with string result in flutter, support iOS(DocumentInteraction) / android(intent) / PC(ffi) / web(dart:html)

Usage

To use this plugin, add open_file as a dependency in your pubspec.yaml file.

If you want to open an external file, You need to request permission start in 3.3.0, This is an example

dependencies:
  #androidx
  open_file: ^lastVersion 
  #support
  #open_file: ^1.3.0

Example

import 'package:open_file/open_file.dart';

OpenFile.open("/sdcard/example.txt");
//OpenFile.open("/sdcard/example.txt", type: "text/plain", uti: "public.plain-text");

Support

android

{
            {".3gp",    "video/3gpp"},
            {".torrent","application/x-bittorrent"},
            {".kml",    "application/vnd.google-earth.kml+xml"},
            {".gpx",    "application/gpx+xml"},
            {".csv",    "application/vnd.ms-excel"},
            {".apk",    "application/vnd.android.package-archive"},
            {".asf",    "video/x-ms-asf"},
            {".avi",    "video/x-msvideo"},
            {".bin",    "application/octet-stream"},
            {".bmp",    "image/bmp"},
            {".c",      "text/plain"},
            {".class",  "application/octet-stream"},
            {".conf",   "text/plain"},
            {".cpp",    "text/plain"},
            {".doc",    "application/msword"},
            {".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls",    "application/vnd.ms-excel"},
            {".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe",    "application/octet-stream"},
            {".gif",    "image/gif"},
            {".gtar",   "application/x-gtar"},
            {".gz",     "application/x-gzip"},
            {".h",      "text/plain"},
            {".htm",    "text/html"},
            {".html",   "text/html"},
            {".jar",    "application/java-archive"},
            {".java",   "text/plain"},
            {".jpeg",   "image/jpeg"},
            {".jpg",    "image/jpeg"},
            {".js",     "application/x-javascript"},
            {".log",    "text/plain"},
            {".m3u",    "audio/x-mpegurl"},
            {".m4a",    "audio/mp4a-latm"},
            {".m4b",    "audio/mp4a-latm"},
            {".m4p",    "audio/mp4a-latm"},
            {".m4u",    "video/vnd.mpegurl"},
            {".m4v",    "video/x-m4v"},
            {".mov",    "video/quicktime"},
            {".mp2",    "audio/x-mpeg"},
            {".mp3",    "audio/x-mpeg"},
            {".mp4",    "video/mp4"},
            {".mpc",    "application/vnd.mpohun.certificate"},
            {".mpe",    "video/mpeg"},
            {".mpeg",   "video/mpeg"},
            {".mpg",    "video/mpeg"},
            {".mpg4",   "video/mp4"},
            {".mpga",   "audio/mpeg"},
            {".msg",    "application/vnd.ms-outlook"},
            {".ogg",    "audio/ogg"},
            {".pdf",    "application/pdf"},
            {".png",    "image/png"},
            {".pps",    "application/vnd.ms-powerpoint"},
            {".ppt",    "application/vnd.ms-powerpoint"},
            {".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop",   "text/plain"},
            {".rc",     "text/plain"},
            {".rmvb",   "audio/x-pn-realaudio"},
            {".rtf",    "application/rtf"},
            {".sh",     "text/plain"},
            {".tar",    "application/x-tar"},
            {".tgz",    "application/x-compressed"},
            {".txt",    "text/plain"},
            {".wav",    "audio/x-wav"},
            {".wma",    "audio/x-ms-wma"},
            {".wmv",    "audio/x-ms-wmv"},
            {".wps",    "application/vnd.ms-works"},
            {".xml",    "text/plain"},
            {".z",      "application/x-compress"},
            {".zip",    "application/x-zip-compressed"},
            {"",        "*/*"}
}

when Conflict with other plugins about FileProvider, add code below in your /android/app/src/main/AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="xxx.xxx.xxxxx">
    <application>
        ...
        <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="${applicationId}.fileProvider"
                android:exported="false"
                android:grantUriPermissions="true"
                tools:replace="android:authorities">
            <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/filepaths"
                    tools:replace="android:resource" />
        </provider>
    </application>
</manifest>

furthermore add code below in your /android/app/src/main/res/xml/filepaths.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <external-path name="external_storage_directory" path="." />
</resources>

when Android dependency 'com.android.support:appcompat-v7' has different version for the compile error, add code below in your /android/build.gradle

subprojects {
    project.configurations.all {
        resolutionStrategy.eachDependency { details ->
            if (details.requested.group == 'com.android.support'
                    && !details.requested.name.contains('multidex') ) {
                details.useVersion "27.1.1"
            }
        }
    }
}

IOS with UTI (DocumentInteraction Auto)

{
            {".rtf",    "public.rtf"},
            {".txt",    "public.plain-text"},
            {".html",   "public.html"},
            {".htm",    "public.html"},
            {".xml",    "public.xml"},
            {".tar",    "public.tar-archive"},
            {".gz",     "org.gnu.gnu-zip-archive"},
            {".gzip",   "org.gnu.gnu-zip-archive"},
            {".tgz",    "org.gnu.gnu-zip-tar-archive"},
            {".jpg",    "public.jpeg"},
            {".jpeg",   "public.jpeg"},
            {".png",    "public.png"},
            {".avi",    "public.avi"},
            {".mpg",    "public.mpeg"},
            {".mpeg",   "public.mpeg"},
            {".mp4",    "public.mpeg-4"},
            {".3gpp",   "public.3gpp"},
            {".3gp",    "public.3gpp"},
            {".mp3",    "public.mp3"},
            {".zip",    "com.pkware.zip-archive"},
            {".gif",    "com.compuserve.gif"},
            {".bmp",    "com.microsoft.bmp"},
            {".ico",    "com.microsoft.ico"},
            {".doc",    "com.microsoft.word.doc"},
            {".xls",    "com.microsoft.excel.xls"},
            {".ppt",    "com.microsoft.powerpoint.​ppt"},
            {".wav",    "com.microsoft.waveform-​audio"},
            {".wm",     "com.microsoft.windows-​media-wm"},
            {".wmv",    "com.microsoft.windows-​media-wmv"},
            {".pdf",    "com.adobe.pdf"}
}

open_file's People

Contributors

alexv525 avatar amir-p avatar crazecoder avatar daniel-mf avatar g123k avatar jawa0919 avatar kluverua avatar lizhuogui avatar marcusgregory avatar mit-mit avatar mludovico avatar mx1up avatar nicorobine avatar piotrzpl avatar princeteck avatar sebas642 avatar sergeysor avatar shinriyo avatar vibhav2799 avatar wk1017553772 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

open_file's Issues

Bug of opening apk file in huawei mate9

在华为mate9手机上使用 open_file打开任何Apk文件,会导致应用自己在桌面的图标消失,我尝试定位了一下问题:

  1. 应用管理里还能看到原应用,需要卸载重新安装才能看到原有应用的图标。
  2. 该现象发生在安装apk之前,也就是说在跳出安装应用页面和权限验证之前,apk图标就消失了

设备名称:HUAWEI Mate 9
EMUI版本:8.0.0
Android版本:8.0.0

conversion to androidX

the newest build of flutter migrates to androidX. i needed to do this:

//import android.support.v4.content.FileProvider;
import androidx.core.content.FileProvider;

//import android.support.v4.app.ActivityCompat;
import androidx.core.app.ActivityCompat;

//import android.support.v4.content.ContextCompat;
import androidx.core.content.ContextCompat;

//import android.support.v4.content.PermissionChecker;
import androidx.core.content.PermissionChecker;

to get this to build.

The provider node of multi_image_picker is different from yours.

multi_image_picker

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths_public"/>
        </provider>

open_file

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true"
            >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths"
                />
        </provider>

更新flutter1.2出错

/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:12: 错误: 程序包android.support.annotation不存在
import android.support.annotation.RequiresApi;
^
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:13: 错误: 程序包android.support.v4.content不存在
import android.support.v4.content.FileProvider;
^
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:14: 错误: 找不到符号
import android.support.v4.app.ActivityCompat;
^
符号: 类 ActivityCompat
位置: 程序包 android.support.v4.app
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:15: 错误: 程序包android.support.v4.content不存在
import android.support.v4.content.ContextCompat;
^
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:16: 错误: 程序包android.support.v4.content不存在
import android.support.v4.content.PermissionChecker;
^
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:278: 错误: 找不到符号
@RequiresApi(api = Build.VERSION_CODES.M)
^
符号: 类 RequiresApi
位置: 类 OpenFilePlugin
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:292: 错误: 找不到符号
@RequiresApi(api = Build.VERSION_CODES.M)
^
符号: 类 RequiresApi
位置: 类 OpenFilePlugin
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:300: 错误: 找不到符号
@RequiresApi(api = Build.VERSION_CODES.O)
^
符号: 类 RequiresApi
位置: 类 OpenFilePlugin
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:309: 错误: 找不到符号
@RequiresApi(api = Build.VERSION_CODES.M)
^
符号: 类 RequiresApi
位置: 类 OpenFilePlugin
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:328: 错误: 找不到符号
@RequiresApi(api = Build.VERSION_CODES.M)
^
符号: 类 RequiresApi
位置: 类 OpenFilePlugin
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:65: 错误: 找不到符号
return ContextCompat.checkSelfPermission(activity, permission) == PermissionChecker.PERMISSION_GRANTED;
^
符号: 变量 ContextCompat
位置: 类 OpenFilePlugin
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:65: 错误: 找不到符号
return ContextCompat.checkSelfPermission(activity, permission) == PermissionChecker.PERMISSION_GRANTED;
^
符号: 变量 PermissionChecker
位置: 类 OpenFilePlugin
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:89: 错误: 找不到符号
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
^
符号: 变量 ActivityCompat
位置: 类 OpenFilePlugin
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:129: 错误: 找不到符号
Uri uri = FileProvider.getUriForFile(context, packageName + ".fileProvider", new File(filePath));
^
符号: 变量 FileProvider
位置: 类 OpenFilePlugin
/Volumes/macdata/data/flutter/.pub-cache/hosted/pub.dartlang.org/open_file-1.3.0/android/src/main/java/com/crazecoder/openfile/OpenFilePlugin.java:284: 错误: 找不到符号
ActivityCompat.requestPermissions(activity,
^
符号: 变量 ActivityCompat
位置: 类 OpenFilePlugin
15 个错误

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':open_file:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details.

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org
    更新了一下flutter 报错了

Does nothing for .docx files on Android Emulator

Issue

Opening a .docx file on the Android Emulator does nothing. File is not opened and no error is thrown.

The last related log is

2019-08-29 12:08:14.136 1969-2863/system_process I/ActivityManager: START u0 {act=android.intent.action.VIEW cat=[android.intent.category.DEFAULT] dat=content://com.pacakge.whatever.fileProvider/cache-path/somefileofmine.docx typ=application/vnd.openxmlformats-officedocument.wordprocessingml.document flg=0x20000001} from uid 10087

Example code

File file = File("${tempDir.path}/somefileofmine.docx");
await OpenFile.open(file.path);

Setup

Device: Android Nexus 5X (Emulator)
Target: Android 9.0 (Google APIs)

EDIT - More Details

Works as expected on physical device (huawei honor 10 lite) and iOS Simulator.

Could be an issue with android emulator not having an app which can open the .docx file. I think OpenFile should then throw an exception instead of doing nothing.

File not opening after download

I am downloading a pdf via http and storing the file in the externalStorageDirectory via path_provider. After calling OpenFile.open on the directory, yet it just a black screen.
I am able to locate and open the file from file manager.

Could this be the issue with Android Fileprovider?

iOS - Open File

Hi,

First of all, great work on the plugin! It really helped me a lot with a Flutter App I'm currently busy with.

I just have a question regarding the iOS implementation:
I noticed that in Android, when calling open, it actually opens the .jpeg/.pdf in the relevant app on the device. When calling open on an iOS simulator, it opens a dialog from the bottom giving me the options to "Share" the file via AirDrop, ICloud Photo Sharing and also a "Save to Files" option. Is this standard behaviour?

I would expect it to just open the .jpeg/.pdf in the relevant app, just like in Android?

I haven't been able to test this on an actual iOS device yet, so it might be a simulator issue.
I just wanted to confirm this behaviour.
Please let me know if this is how the plugin should work or am I missing something here?

Keep up the great work!

Regards,
Daryll Fourie

Filter selectable files by multiple file extensions

It would be great to define multiple file extensions in combination with the "FileType.CUSTOM" parameter. For instance, if I want the user to be able to select only text and PDF files I can't restrict this using a single file extension.

org.xml.sax.SAXParseException; systemId: file:/E:/FlutterProject/download/android/app/src/main/AndroidManifest.xml;

我的 AndroidManifest.xml 配置











        <meta-data
            android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
            android:value="true" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.fileProvider"
        android:exported="false"
        android:grantUriPermissions="true"
        tools:replace="android:authorities">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths"
            tools:replace="android:resource" />
    </provider>
</application>
---

grade.properties 配置


org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true

build,gradle 配置


buildscript {
ext.kotlin_version = '1.3.0'
repositories {
google()
jcenter()
}

dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}

}

allprojects {
repositories {
google()
jcenter()
}
}

rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
delete rootProject.buildDir
}


报错截图

image

😭有人会吗帮忙解决一下
I need help

apk 安装版本判断有问题

应该是if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {} 是N, 而不是M,如果是M, 6.0系统会受到影响

怎么使用Android x啊,搞了一天了

我看了你的源代码,因为要打开文件,所以要使用:FileProvider类,可是我跟本找不到这个类,怎么才能import 这些库啊
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;

这是我的Androidmanifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.nionco.flowersm">

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="flowersm"
        android:icon="@mipmap/ic_launcher"
        tools:ignore="GoogleAppIndexingWarning">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- This keeps the window background of the activity showing
                 until Flutter renders its first frame. It can be removed if
                 there is no splash screen (such as the default splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true"
            >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"
                tools:replace="android:resource"
                />
        </provider>
    </application>


</manifest>

这是我的build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.nionco.flowersm"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.core:core:1.0.1'
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.work:work-runtime:2.0.1-rc01'
}

求指导啊,搞了一天了

Platform exception thrown when trying to open file

Upon opening a file an unknown exception is thrown:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

I have added the "provider" code to AndroidManifest.xml, but that did not help

URI Read permission is not granted on Android M

Android M (API level 23) requires FLAG_GRANT_READ_URI_PERMISSION to be sent as part of intent to another app to get access to the shared file in user or temp folder.

That cause "The document path is not valid" or similar error the target app on Marshmallow platform.

Current implementation of the plugin add this flag from Android N. Should be changed to M.
OpenFilePlugin.java:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

android.content.ActivityNotFoundException: No Activity found to handle Intent

遇到一个问题,Android上出现的,如果手机上没有安装可以打开word文档的app时,打开word文档报错:android.content.ActivityNotFoundException: No Activity found to handle Intent{ act=android.intent.action.VIEW cat=[andr oid.intent.category.DEFAULT] dat=content://com.crazecoder.openfileexample.fileProvider/external-path/test.docx typ=application/vnd.openxmlformats-officedo cument.wordprocessingml.document flg=0x20000001 }

E/MethodChannel#open_file( 7299): Failed to handle method call E/MethodChannel#open_file( 7299): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW cat=[andr oid.intent.category.DEFAULT] dat=content://com.crazecoder.openfileexample.fileProvider/external-path/test.docx typ=application/vnd.openxmlformats-officedo cument.wordprocessingml.document flg=0x20000001 } E/MethodChannel#open_file( 7299): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805) E/MethodChannel#open_file( 7299): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1514) E/MethodChannel#open_file( 7299): at android.app.Activity.startActivityForResult(Activity.java:4028) E/MethodChannel#open_file( 7299): at android.app.Activity.startActivityForResult(Activity.java:3989) E/MethodChannel#open_file( 7299): at android.app.Activity.startActivity(Activity.java:4312) E/MethodChannel#open_file( 7299): at android.app.Activity.startActivity(Activity.java:4280) E/MethodChannel#open_file( 7299): at com.crazecoder.openfile.OpenFilePlugin.startActivity(OpenFilePlugin.java:135) E/MethodChannel#open_file( 7299): at com.crazecoder.openfile.OpenFilePlugin.onMethodCall(OpenFilePlugin.java:87) E/MethodChannel#open_file( 7299): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:201) E/MethodChannel#open_file( 7299): at io.flutter.view.FlutterNativeView$PlatformMessageHandlerImpl.handleMessageFromDart(FlutterNativeView.java:188) E/MethodChannel#open_file( 7299): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:202) E/MethodChannel#open_file( 7299): at android.os.MessageQueue.nativePollOnce(Native Method) E/MethodChannel#open_file( 7299): at android.os.MessageQueue.next(MessageQueue.java:323) E/MethodChannel#open_file( 7299): at android.os.Looper.loop(Looper.java:141) E/MethodChannel#open_file( 7299): at android.app.ActivityThread.main(ActivityThread.java:5684) E/MethodChannel#open_file( 7299): at java.lang.reflect.Method.invoke(Native Method) E/MethodChannel#open_file( 7299): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:746) E/MethodChannel#open_file( 7299): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636) E/flutter ( 7299): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, No Activity found to handle Intent { act=and roid.intent.action.VIEW cat=[android.intent.category.DEFAULT] dat=content://com.crazecoder.openfileexample.fileProvider/external-path/test.docx typ=applic ation/vnd.openxmlformats-officedocument.wordprocessingml.document flg=0x20000001 }, null) E/flutter ( 7299): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:564:7) E/flutter ( 7299): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:302:33) E/flutter ( 7299): <asynchronous suspension> E/flutter ( 7299): #2 OpenFile.open (package:open_file/open_file.dart:10:27) E/flutter ( 7299): <asynchronous suspension> E/flutter ( 7299): #3 _MyAppState.openFile (package:open_file_example/main.dart:18:36) E/flutter ( 7299): <asynchronous suspension> E/flutter ( 7299): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:513:14) E/flutter ( 7299): #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:568:30) E/flutter ( 7299): #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:120:24) E/flutter ( 7299): #7 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9) E/flutter ( 7299): #8 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7) E/flutter ( 7299): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:369:9) E/flutter ( 7299): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12) E/flutter ( 7299): #11 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11) E/flutter ( 7299): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:214:19) E/flutter ( 7299): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:192:22) E/flutter ( 7299): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:149:7) E/flutter ( 7299): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7) E/flutter ( 7299): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7) E/flutter ( 7299): #17 _rootRunUnary (dart:async/zone.dart:1136:13) E/flutter ( 7299): #18 _CustomZone.runUnary (dart:async/zone.dart:1029:19) E/flutter ( 7299): #19 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7) E/flutter ( 7299): #20 _invoke1 (dart:ui/hooks.dart:223:10) E/flutter ( 7299): #21 _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5) E/flutter ( 7299):

Android issue

Launching lib\main.dart on Redmi Note 5 in debug mode...
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:preDebugBuild'.
> Android dependency 'androidx.versionedparcelable:versionedparcelable' has different version for the compile (1.0.0-rc01) and runtime (1.0.0) classpath. You should manually set the same version via DependencyResolution

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
*******************************************************************************************
The Gradle failure may have been because of AndroidX incompatibilities in this Flutter app.
See https://goo.gl/CP92wY for more information on the problem and how to fix it.
*******************************************************************************************
Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

gradle.properties

org.gradle.jvmargs=-Xmx1536M
android.enableJetifier=true
android.useAndroidX=true

app/android/build.gradle

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
subprojects {
    project.configurations.all {
        resolutionStrategy.eachDependency { details ->
            if (details.requested.group == 'com.android.support'
                    && !details.requested.name.contains('multidex') ) {
                details.useVersion "27.1.1"
            }
        }
    }
}

app/android/app/build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.zimbronapps.biografias"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 5
        versionName "v1.5"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

signingConfigs {
    release {
        keyAlias keystoreProperties['keyAlias']
        keyPassword keystoreProperties['keyPassword']
        storeFile file(keystoreProperties['storeFile'])
        storePassword keystoreProperties['storePassword']
    }
}
buildTypes {
    release {
        signingConfig signingConfigs.release
    }
}
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Save configs for each file type separately

While opening file, which cant be opened with standard tools - plugin open program selector for file.
When program will be selected for file - this preferences used for all file types.
It have sense to add some configs and open app selector for each file type separately.

Example:
*.epub - opened with Google Chrome - so only for *.epub files Google Chrome should be used
While trying to open *.jks - plugin should open app selector.

Unable to open in iOS

Work fine in Android, but does not open any file iOS (either in Simulator or Actual device).

Console warning

[VERBOSE-2:engine.cc(157)] Could not prepare to run the isolate.
[VERBOSE-2:engine.cc(116)] Engine not prepare and launch isolate.
[VERBOSE-2:FlutterViewController.mm(398)] Could not launch engine with configuration.

I/flutter ( 4433): the /assets/res/file.pdf file is not exists

Hi there,

I try to open a file with your package and when I try to print the _result I get the following error:
I/flutter ( 4433): the /assets/res/dutyplan.pdf file is not exists

I importet your package using import 'package:open_file/open_file.dart';
and I made sure to specify the PDF file in my pubspec.yaml
flutter: assets: - assets/res/dutyplan.pdf

Do you have any ideas whats going wrong? Thanks in advance.
Below you find the code I'm using, which was copied from the example and modified.
Same error when I try to open a .csv or .txt file.

  void loadPDF() {
    openFile('/assets/res/dutyplan.pdf').then((_result) {
      print(_result);
    });
  }

  Future<String> openFile(filePath) async {
    return await OpenFile.open(filePath);
  }

not work with permission_handler 3.0.0

  1. permission_handler requests storage permission
  2. if already has storage permission, nothing happened
  3. if grant storage permission success, the app will crash....

so I comment line 61: registrar.addRequestPermissionsResultListener(plugin), and everything works well ~

Error message when opening a downloaded file

I receive the following error message:

Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference'

I download a file using dio and try to open it using this code flow:

Response<dynamic> response = await dio.download(url,downloadFilePath);
      if(response.statusCode == 200){
        OpenFile.open(downloadFilePath);    
      }

This is de stacktrace:
androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:605) androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579) androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417) com.crazecoder.openfile.OpenFilePlugin.startActivity(OpenFilePlugin.java:130) com.crazecoder.openfile.OpenFilePlugin.onMethodCall(OpenFilePlugin.java:93) io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222) io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96) io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:643) android.os.MessageQueue.nativePollOnce(Native Method) android.os.MessageQueue.next(MessageQueue.java:336) android.os.Looper.loop(Looper.java:174) android.app.ActivityThread.main(ActivityThread.java:7356) java.lang.reflect.Method.invoke(Native Method) com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

How can I fix this?

resource android:attr/fontVariationSettings not found.

Execution failed for task ':app:processDebugResources'.

Android resource linking failed
Output: /Volumes/macdata/workspace/BeenetApp/build/app/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml:226: error: resource android:attr/fontVariationSettings not found.
/Volumes/macdata/workspace/BeenetApp/build/app/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml:226: error: resource android:attr/ttcIndex not found.
error: failed linking references.

请问是啥问题,一天了,实在没办法了。。

Gradle task assembleDebug failed with exit code 1

Gradle task assembleDebug failed with exit code 1

#0 throwToolExit (package:flutter_tools/src/base/common.dart:28:3)
#1 _buildGradleProjectV2 (package:flutter_tools/src/android/gradle.dart:751:5)

#2 buildGradleProject (package:flutter_tools/src/android/gradle.dart:494:14)

#3 buildApk (package:flutter_tools/src/android/apk.dart:34:9)

#4 AndroidDevice.startApp (package:flutter_tools/src/android/android_device.dart:486:13)

#5 FlutterDevice.runHot (package:flutter_tools/src/resident_runner.dart:378:54)

#6 HotRunner.run (package:flutter_tools/src/run_hot.dart:253:39)

#7 RunCommand.runCommand (package:flutter_tools/src/commands/run.dart:472:37)

#8 FlutterCommand.verifyThenRunCommand (package:flutter_tools/src/runner/flutter_command.dart:490:18)
#9 _asyncThenWrapperHelper. (dart:async-patch/async_patch.dart:77:64)
#10 _rootRunUnary (dart:async/zone.dart:1132:38)
#11 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#12 _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
#13 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
#14 Future._propagateToListeners (dart:async/future_impl.dart:668:32)
#15 Future._complete (dart:async/future_impl.dart:473:7)
#16 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#17 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:28:18)
#18 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:294:13)
#19 RunCommand.usageValues (package:flutter_tools/src/commands/run.dart)
#20 _asyncThenWrapperHelper. (dart:async-patch/async_patch.dart:77:64)
#21 _rootRunUnary (dart:async/zone.dart:1132:38)
#22 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#23 _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
#24 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
#25 Future._propagateToListeners (dart:async/future_impl.dart:668:32)
#26 Future._complete (dart:async/future_impl.dart:473:7)
#27 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#28 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:28:18)
#29 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:294:13)
#30 AndroidDevice.isLocalEmulator (package:flutter_tools/src/android/android_device.dart)
#31 _asyncThenWrapperHelper. (dart:async-patch/async_patch.dart:77:64)
#32 _rootRunUnary (dart:async/zone.dart:1132:38)
#33 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#34 _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
#35 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
#36 Future._propagateToListeners (dart:async/future_impl.dart:668:32)
#37 Future._complete (dart:async/future_impl.dart:473:7)
#38 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#39 _AsyncAwaitCompleter.complete. (dart:async-patch/async_patch.dart:33:20)
#40 _rootRun (dart:async/zone.dart:1120:38)
#41 _CustomZone.run (dart:async/zone.dart:1021:19)
#42 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
#43 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:963:23)
#44 _rootRun (dart:async/zone.dart:1124:13)
#45 _CustomZone.run (dart:async/zone.dart:1021:19)
#46 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
#47 _CustomZone.bindCallbackGuarded. (dart:async/zone.dart:963:23)
#48 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#49 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#50 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:116:13)
#51 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:173:5)

Incompatibility with firebase_messaging - Android

Even with new Projects without code i have this problem:

That`s my pubspec.yaml:

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  firebase_messaging: ^5.0.2 # Remove this and no error
  open_file: ^2.0.2

If i try to run the app, or build the apk, the following error appears:

D8: Program type already present: android.support.v4.os.ResultReceiver  
                                                                        
FAILURE: Build failed with an exception.                                
                                                                        
* What went wrong:                                                      
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForRelease'.
> com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:  A LONG LIST OF FILES
Program type already present: android.support.v4.os.ResultReceiver    
  Learn how to resolve the issue at https://developer.android.com/studio/build/dependencies#duplicate_classes.
                                                                        
* Try:                                                                  
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
                                                                        
* Get more help at https://help.gradle.org                              
                                                                        
BUILD FAILED in 1s                                                      
*******************************************************************************************
The Gradle failure may have been because of AndroidX incompatibilities in this Flutter app.
See https://goo.gl/CP92wY for more information on the problem and how to fix it.
*******************************************************************************************
Gradle task assembleRelease failed with exit code 1

CSV file support on android and ios

Is there any chance to add support for .csv files?

#46
In the above issue there is a workaround to open .csv files but it only works if you have ms excel installed. If you want to open the file with google sheets it will say that the file is corrupted when it is not since if you access the same file from any other file explorer or app (whatsapp, telegram etc) it opens up just fine in google sheets.

Error on AndroidManifest.xml

Hello, i got error on new version 1.0.7 as the image shown below
error1

and my pubspec.yaml
error2

On previous version i don't encounter this error, but after upgrade to 1.0.7 and image_picker to 0.4.6 this error show up.

Thanks for the awesome library.

下载后的apk文件解析软件包时出现问题

使用flutter_downloader成功下载apk文件到本地目录/storage/emulated/0/Download
选择使用软件包安装程序打开时,显示解析软件包时出现问题

androidmanifest.xml配置如下

<provider
      android:name="android.support.v4.content.FileProvider"
      android:authorities="${applicationId}.fileProvider"
      android:exported="false"
      android:grantUriPermissions="true"
      tools:replace="android:authorities">
      <meta-data
         android:name="android.support.FILE_PROVIDER_PATHS"
         android:resource="@xml/provider_paths"
         tools:replace="android:resource" />
</provider>

provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

No file opened in IOS after second run

Hi there,

I am able to open the file after i run the code on the device. Tried multiple times and still ok. However after I press run again, it does not open the file when I click on the button. There was no error. Basically it was a success and the filepath was correct. But nothing opened. This only happens after I run the code from android studio the second time.

File Provider for image_picker error

Error below:

/Users/vibhavkotriwala/Desktop/work/4ceed_app/android/app/src/main/AndroidManifest.xml:14:13-74 Error:
Attribute provider#android.support.v4.content.FileProvider@authorities value=(com.example.myapp.flutter.image_provider) from [:image_picker] AndroidManifest.xml:14:13-74
is also present at [:open_file] AndroidManifest.xml:12:13-64 value=(com.example.myapp.fileProvider).
Suggestion: add 'tools:replace="android:authorities"' to element at AndroidManifest.xml:12:9-20:20 to override.
/Users/vibhavkotriwala/Desktop/work/4ceed_app/android/app/src/main/AndroidManifest.xml:19:17-72 Error:
Attribute meta-data#android.support.FILE_PROVIDER_PATHS@resource value=(@xml/flutter_image_picker_file_paths) from [:image_picker] AndroidManifest.xml:19:17-72
is also present at [:open_file] AndroidManifest.xml:17:17-50 value=(@xml/filepaths).
Suggestion: add 'tools:replace="android:resource"' to element at AndroidManifest.xml to override.

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:processDebugManifest'.

IllegalArgumentException: Couldn't find meta-data for provider with authority {packageId}.fileProvider

Issue

When OpenFile.open(filePath); is fired, this exception is thrown:

E/MethodChannel#open_file( 3078): Failed to handle method call
E/MethodChannel#open_file( 3078): java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.example.musiker.fileProvider
E/MethodChannel#open_file( 3078): 	at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:606)
E/MethodChannel#open_file( 3078): 	at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
E/MethodChannel#open_file( 3078): 	at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417)
E/MethodChannel#open_file( 3078): 	at com.crazecoder.openfile.OpenFilePlugin.startActivity(OpenFilePlugin.java:130)
E/MethodChannel#open_file( 3078): 	at com.crazecoder.openfile.OpenFilePlugin.onMethodCall(OpenFilePlugin.java:88)
E/MethodChannel#open_file( 3078): 	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222)
E/MethodChannel#open_file( 3078): 	at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96)
E/MethodChannel#open_file( 3078): 	at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:643)
E/MethodChannel#open_file( 3078): 	at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#open_file( 3078): 	at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#open_file( 3078): 	at android.os.Looper.loop(Looper.java:160)
E/MethodChannel#open_file( 3078): 	at android.app.ActivityThread.main(ActivityThread.java:6694)
E/MethodChannel#open_file( 3078): 	at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#open_file( 3078): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/MethodChannel#open_file( 3078): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/flutter ( 3078): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Couldn't find meta-data for provider with authority com.example.musiker.fileProvider, null)

Example code

OpenFile.open(filePath);

Setup

Device: Xiaomi Mi A2 Lite
Android version: 9

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.my.app">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="musiker"
        android:icon="@mipmap/ic_launcher">
        <activity>
            ...
        </activity>

        <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="${applicationId}.fileProvider"
                android:exported="false"
                android:grantUriPermissions="true"
                tools:replace="android:authorities">
            <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/filepaths"
                    tools:replace="android:resource" /> 
        </provider>
        <provider
            android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
            android:authorities="${applicationId}.flutter_downloader.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>

Dependencies

...
dio: ^2.1.16
flutter_downloader: ^1.2.1
path_provider: ^1.2.0
path: ^1.6.2
open_file: ^2.0.3
...

Open file from URL

Is it possible, to open a file from a remote url address?

Or do I have to download the file separately to a temp folder?

total crash when 'No Activity found'

App gets killed when I try to open docx file. Would it make sense to just add try/catch for startActivityForResult to prevent that?

E/MethodChannel#open_file(21430): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW cat=[android.intent.category.DEFAULT] dat=content://com.example.xxx.fileProvider/cache-path/Word.docx typ=application/vnd.openxmlformats-officedocument.wordprocessingml.document flg=0x20000001 }
E/MethodChannel#open_file(21430): 	at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2007)
E/MethodChannel#open_file(21430): 	at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
E/MethodChannel#open_file(21430): 	at android.app.Activity.startActivityForResult(Activity.java:4586)
E/MethodChannel#open_file(21430): 	at android.app.Activity.startActivityForResult(Activity.java:4544)
E/MethodChannel#open_file(21430): 	at com.crazecoder.openfile.OpenFilePlugin.onMethodCall(OpenFilePlugin.java:65)
E/MethodChannel#open_file(21430): 	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:191)
E/MethodChannel#open_file(21430): 	at io.flutter.view.FlutterNativeView.handlePlatformMessage(FlutterNativeView.java:163)
E/MethodChannel#open_file(21430): 	at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#open_file(21430): 	at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#open_file(21430): 	at android.os.Looper.loop(Looper.java:160)
E/MethodChannel#open_file(21430): 	at android.app.ActivityThread.main(ActivityThread.java:6669)
E/MethodChannel#open_file(21430): 	at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#open_file(21430): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/MethodChannel#open_file(21430): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Opening camera on image_picker

I am getting the error below only when I use open_file with image_picker. If I remove open_file from pubspec.yaml, the camera opens normally.

E/flutter (12347): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (12347): PlatformException(error, Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference, null)
E/flutter (12347): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:547:7)
E/flutter (12347): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:279:18)
E/flutter (12347):
E/flutter (12347): #2 ImagePicker.pickImage (package:image_picker/image_picker.dart:47:40)
E/flutter (12347):
E/flutter (12347): #3 UploadFilesToDatasetState.getImage (file:///Users/vibhavkotriwala/Desktop/work/4ceed_app/lib/pages/upload_to_dataset.dart:20:35)
E/flutter (12347):
E/flutter (12347): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:494:14)
E/flutter (12347): #5 _InkResponseState.build. (package:flutter/src/material/ink_well.dart:549:30)
E/flutter (12347): #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter (12347): #7 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:161:9)
E/flutter (12347): #8 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:123:7)
E/flutter (12347): #9 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (12347): #10 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:147:20)
E/flutter (12347): #11 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
E/flutter (12347): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
E/flutter (12347): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
E/flutter (12347): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
E/flutter (12347): #15 _invoke1 (dart:ui/hooks.dart:134:13)
E/flutter (12347): #16 _dispatchPointerDataPacket (dart:ui/hooks.dart:91:5)

Conflict with image_provider plugin

Conflict when use togather with image_provider plugin,

/home/k/xwork/dartsugar/android/app/src/main/AndroidManifest.xml:12:13-64 Error:
	Attribute provider#android.support.v4.content.FileProvider@authorities value=(com.yathit.dartsugar.fileProvider) from [:open_file] AndroidManifest.xml:12:13-64
	is also present at [:image_picker] AndroidManifest.xml:14:13-74 value=(com.yathit.dartsugar.flutter.image_provider).
	Suggestion: add 'tools:replace="android:authorities"' to <provider> element at AndroidManifest.xml:10:9-18:20 to override.
/home/k/xwork/dartsugar/android/app/src/main/AndroidManifest.xml:17:17-50 Error:
	Attribute meta-data#android.support.FILE_PROVIDER_PATHS@resource value=(@xml/filepaths) from [:open_file] AndroidManifest.xml:17:17-50
	is also present at [:image_picker] AndroidManifest.xml:19:17-72 value=(@xml/flutter_image_picker_file_paths).
	Suggestion: add 'tools:replace="android:resource"' to <meta-data> element at AndroidManifest.xml to override.

Plugin intercepting permission results from other plugins on android

I have some native code in my app that requests microphone access. On android, if I accept the pop-up prompt, the app crashes. I traced the cause of the crash to this plugin in the startActivity function at the File file = new File(filePath);. I believe this is because in the onRequestPermissionsResult function, it calls startActivity after the processing of the permission result is complete regardless of what the permission was or whether this plugin was the one that requested it. This causes startActivity to fire even though filePath is still null.

I believe this is related to #31.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.