2015-10-06 100 views
1

我的应用程序使用序列化来存储数据。 Save()函数在Activity的onStop()方法中被调用。由于数据很小,一切都很好。今天的序列化需要一段时间,我很惊讶找到一种方法来破坏数据。如何禁止在写入文件时终止应用程序

如果我通过主页按钮退出应用程序,然后快速手动杀死应用程序窗体背景活动屏幕(长按Home按钮),我的数据似乎丢失了。我认为它是因为应用程序被写入文件并被中断。

有没有机会禁止杀死进程,直到我的save()方法起作用?我正在考虑自己重写序列化,并且时间可能会更快,但据我了解,有时候这个问题会再次发生。

谢谢。

//活动代码:

@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(); 

    } 
+0

我想创建一个后台服务来获得这项任务完成。 – RyanB

+0

您是否在使用IntentService?好吧,我会检查它。谢谢。 – Kruiller

+0

我检查了这一点。 IntentService在应用程序查杀时死亡。 =( – Kruiller

回答

1

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

保存()在辛格尔顿:

 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. 
    } 
+0

,实际上没有帮助,但很高兴它工作:) – RyanB