2015-10-06 123 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