【问题标题】:How to share a file between widget, service and app?如何在小部件、服务和应用程序之间共享文件?
【发布时间】:2012-03-30 12:55:35
【问题描述】:

我正在编写一个应用程序和一个需要数据的伴随小部件。该数据通过网络下载。我打算使用 IntentService 进行下载。该服务会将数据保存为文件。该文件随后被应用程序和小部件使用。

如何防止应用程序和小部件在服务写入文件时读取文件?

当应用程序或小部件正在读取文件时,如何防止服务写入文件?

谢谢!

【问题讨论】:

    标签: android file file-io android-widget intentservice


    【解决方案1】:

    考虑扩展Application并声明一个读写权限字段:

    public class APP extends Application {
        boolean motherMayI;
    
        ...
    }
    

    然后,每当您打开FileInputStreamFileOutputStream

    ...
    if (motherMayI) {
        APP.motherMayI = false;
        FileInputStream input = context.openFileInput("some_file_name");
    
        //read your stuff
    
        input.close()
        APP.motherMayI = true;
    }
    ...
    

    从本质上讲,motherMayI 字段必须为 true 才能让某人读取或写入文件,并且在读取或写入文件时它唯一为 false。

    编辑:

    public FileInputStream getFileInputStream() {
        return context.openFileInput(file_name);
    }
    

    这需要APP 的实例。

    【讨论】:

    • 好的,这似乎是一个简单而好的解决方案。但我不知道应用程序对象的生命周期。不创建activity,只创建widget时是否可用?
    • 我不知道你的问题的确切答案,但我的想法是:小部件读取一个文件,因此必须打开一个FileInputStream。这必须在 Java 中完成,因此Application 对象最有可能可用。如果没有,只需在APP 中创建一个返回FileInputStream 的方法。请参阅编辑以获取说明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多