简体   繁体   English

Android-将数据保存到内部存储

[英]Android - Saving data to an internal storage

I'm working on a simple to-do list app, and I'm trying to read/write data from/to internal storage. 我正在开发一个简单的待办事项清单应用程序,并且正在尝试从内部存储读取/写入数据。 I'm trying to understand when exactly those read/write methods should be called. 我试图了解什么时候应该调用那些读/写方法。

I know that the activity class has an onCreate() method which will be a reasonable location for my read method, but where should I call my write method? 我知道活动类具有onCreate()方法,这对于我的read方法来说是一个合理的位置,但是我应该在哪里调用我的write方法呢?

I want to call it when the app closes/ends, so I'd assume onDestory() is a good location, but i heard that onDestroy() may not be a good location for data storage operations and i should use onStop() . 我想在应用程序关闭/结束时调用它,所以我假设onDestory()是一个不错的位置,但是我听说onDestroy()可能不是数据存储操作的一个不错的位置,我应该使用onStop()

Any help or ideas? 有什么帮助或想法吗?

Following the table in the Android Developers Guide on the Activity Lifecycle , your app may be killed by the system any time without warning after either onPause() (for Pre-HONEYCOMB devices) or after onStop() . 遵循Activity Lifecycle上Android开发者指南中的表格,在onPause() (对于HONEYCOMB之前的设备)或onStop()之后,您的应用可能会随时被系统杀死,而不会发出警告。 So you probably want to write your data in these methods to make sure nothing gets lost. 因此,您可能希望使用这些方法写入数据,以确保不会丢失任何数据。 So for newer devices (API level 11 and up), onStop() should be fine. 因此,对于较新的设备(API级别为11或更高), onStop()应该很好。 If your app should run on older devices as well, onPause() would be the best place. 如果您的应用程序也应在较旧的设备上运行,那么onPause()将是最佳选择。

It depends on Application Lifecycle. 这取决于应用程序生命周期。

这张照片

And see This . 看看这个

onStop() invokes when user press home button(Hard Key). 当用户按下主页按钮(硬键)时, onStop()调用。

And then, if memory insufficient or another reason, Android Memory Manager will kill your app instant and onDestory() will never called. 然后,如果内存不足或其他原因,Android内存管理器将立即onDestory()您的应用程序,并且永不调用onDestory()

The best thing you have to is make a button to save datas. 您最好要做的就是创建一个按钮来保存数据。 Of course, Include onStop() save routine. 当然,Include onStop()保存例程。

This is Just sample code. 这只是示例代码。 But you get the idea. 但是你明白了。 Create a custom method implementing the code below and call it on some events like "onClick" or any other. 创建实现以下代码的自定义方法,并在“ onClick”之类的其他事件上调用它。

File file;
    FileOutputStream strem = null;
    String line = "Hey this is my name";
    try {
        file = new File("sdcard/newFile.txt");
        strem = new FileOutputStream(file);
        byte[] bytes = line.getBytes();
        strem.write(bytes);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            strem.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

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