我的任务是将签名的 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);
}
}
后台服务.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
}