2013-07-09 67 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