gpt4 book ai didi

java - 如何禁止在写入文件时终止应用程序继续

转载 作者:行者123 更新时间:2023-11-30 01:51:29 24 4
gpt4 key购买 nike

我的应用程序使用序列化来存储数据。 Save()函数在Activity中调用onStop()方法。由于数据很小,所以一切都很好。今天序列化需要时间,我很惊讶地找到了一种破坏数据的方法。

如果我通过主页按钮退出应用程序,然后快速手动关闭应用程序表单后台 Activity 屏幕(长按主页按钮),我的数据似乎丢失了。我认为这是因为应用程序被写入文件并被中断。

是否有机会在我的 save() 方法起作用之前禁止终止进程?本来想自己重写序列化,有时会快点,但据我所知,有时会再次出现这个问题。

谢谢。

// Activity 代码:

@Override
protected void onStop(){
try {
ms.save();
} catch (IOException e) {
e.printStackTrace();
}
super.onStop();
}

// Singleton save fucntion

public void save() throws IOException {
Runnable r = new Runnable()
{
@Override
public void run()
{
try {
FileOutputStream fos;
ObjectOutputStream os;
if (data != null){
fos = context.openFileOutput("Data.dat", Context.MODE_PRIVATE);
os = new ObjectOutputStream(fos);
os.writeObject(data);
os.flush();
os.close();
fos.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
};

Thread t = new Thread(r);
t.start();

}

最佳答案

好的,我在后台使用 IntentService 得到了它。感谢 RyanB 的帮助。

单例中的 save():

        Intent mServiceIntent = new Intent(context, ServiceDatastore.class);
mServiceIntent.setData(Uri.parse("dsf"));
context.startService(mServiceIntent);

ServiceDatastore.java

@Override
protected void onHandleIntent(Intent workIntent) {
final int myID = 1234;
Intent intent = new Intent(); // empty Intent to do nothing in case we click on notification.
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notice = new Notification(R.drawable.icon, getString(R.string.saving), System.currentTimeMillis());
notice.setLatestEventInfo(this, "Saving...", "", pendIntent);

notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notice);

try {
Singleton ms = Singleton.getInstance(this);
FileOutputStream fos;
ObjectOutputStream os;
//copy settings
if (ms.data != null) {
fos = this.openFileOutput("Data.dat", Context.MODE_PRIVATE);
os = new ObjectOutputStream(fos);
os.writeObject(ms.data);
os.flush();
os.close();
fos.close();
}
}
catch (Exception e){
e.printStackTrace();
}
stopForeground(true); // to kill the process if the app was killed.
}

关于java - 如何禁止在写入文件时终止应用程序继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32965546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com