2013-07-09 114 views
0

我有一個將簽名的png文件移動到我們的服務器之一的任務。我實現的解決方案是有一個後臺服務來監視它保存的文件夾然後移動它。這很有效,但服務在一段時間後關閉,可能需要一個小時,但我希望它持久。做一些研究導致使用警報管理器或處理程序來保持活動。持續後臺服務

我決定使用處理程序。但是,無論何時調用活動,設備都會掛起,每次刷新時都會佔用更多的內存。罪魁禍首可能是因爲沒有調用'stopWatching()',儘管我可能不正確地處理了這個問題。

SendToPHP.java

public class SendToPHP extends Activity { 
final int FIFTEEN_MINUTES_IN_MILLISECONDS = 900000; 

//The handler will run the function restart at a later time 
//This should prevent the intent service timeout. 
Handler handler = new Handler(); 
Runnable runnable = new Runnable() { 
    public void run() { 
     finish(); 
     startActivity(getIntent()); 
    } 
}; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     Intent mServiceIntent = new Intent(SendToPHP.this, 
       BackgroundService.class); 
     // Starts the IntentService 
     SendToPHP.this.startService(mServiceIntent); 
     handler.postDelayed(runnable, FIFTEEN_MINUTES_IN_MILLISECONDS); 
    } 

} 

BackgroundService.java

@Override 
protected void onHandleIntent(Intent workIntent) { 

    /************* Php script path ****************/ 
    upLoadServerUri = "*redacted*"; 

    //FileObserver monitors files/directories, in this case we want any file that is 
    //created in SignItPictures 
    FileObserver observer = new FileObserver(android.os.Environment 
      .getExternalStorageDirectory().toString() + "/Pictures/SignItPictures", FileObserver.CREATE) { 
     @Override 
     public void onEvent(int event, String file) { 
      uploadFileName = file; 
      uploadFile(uploadFilePath + "/" + uploadFileName); 
     } 
    }; 
    observer.startWatching(); // start the observer 
} 
+0

爲什麼要那樣做?你不能只保存一次就上傳它嗎? – rciovati

+1

「這樣做效果很好,但服務在一段時間後關閉,可能需要一個小時或一些時間,但我希望它持久不變」 - 您的用戶可能會不同意。不要只在服務器上存儲一個服務,而只是在手指上旋轉。只有在積極向用戶傳遞價值時纔在內存中提供服務。問題不在於您的服務正在關閉,而在於Android終止您的流程,爲其他應用程序釋放內存。用戶也會終止你的過程,使用任務管理器等,你不想誘使他們這樣做。 – CommonsWare

+0

@rciovati對於我的實習來說,android設備只是坐在辦公桌旁,接收借用的IT設備的簽名。 在commonsware嗯,我想我可以有一個應用程序,處理整個文件夾,因爲這是事實。 –

回答

0

嘗試在服務類的onStartCommand方法添加START_STICKY