简体   繁体   English

调用File.toURI()时的ANR

[英]ANR when calling File.toURI()

The Google Play developer console, has reported that the File.toURI() method has caused an ANR (application not responding) error: Google Play开发者控制台报告说File.toURI()方法导致了ANR(应用程序未响应)错误:

at libcore.io.Posix.stat(Native Method)
at libcore.io.ForwardingOs.stat(ForwardingOs.java:131)
at java.io.File.isDirectory(File.java:529)
at java.io.File.getAbsoluteName(File.java:1104)
at java.io.File.toURI(File.java:1062)
at com.mypackage.myclass.<init>(SourceFile:1234)

Is there an alternative way to do this on the main thread (because using a background thread seems like overkill)? 是否有另一种方法可以在主线程上执行此操作(因为使用后台线程似乎过大)?

Doing tasks directly on the UI or main thread is not recommended. 不建议直接在UI或主线程上执行任务。 In your case, try AsyncTask . 在您的情况下,请尝试AsyncTask Look here for an example. 请看这里的例子。

If the file path is already an absolute path and you already know whether the File is a directory: 如果文件路径已经是绝对路径,并且您已经知道文件是否是目录:

public static String toURI(File f, boolean isDirectory) {
    try {
        String sp = slashify(f.getPath(), isDirectory);
        if (sp.startsWith("//")) {
            sp = "//" + sp;
        }
        return new URI("file", null, sp, null);
    } 
    catch (URISyntaxException x) {
        throw new Error(x);         // Can't happen
    }
}

private static String slashify(String path, boolean isDirectory) {
    String p = path;
    if (File.separatorChar != '/')
        p = p.replace(File.separatorChar, '/');
    if (!p.startsWith("/"))
        p = "/" + p;
    if (!p.endsWith("/") && isDirectory)
        p = p + "/";
    return p;
}

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

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