持久背景服务

时间:2013-07-09 15:03:53

标签: android

我有一个将签名的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
}

1 个答案:

答案 0 :(得分:0)

尝试在Service类的onStartCommand方法中添加START_STICKY