我如何使用Workmanager进行后台上传工作,我有一个应用程序可以通过FTP将文件备份到PC,并且我想学习新的方法,因为在我的手机上,旧方法只有在我安装了应用程序后才能工作并在我关闭应用程序时运行,后台任务停止。 索尼可以帮助我设置工作经理吗?
class Working(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
private val TAG = ""
private val SERVER = ""
private val USERNAME = ""
private val PASSWORD = ""
private val PATH = ""
private val timer = Timer()
override fun doWork(): ListenableWorker.Result {
Log.i(TAG, "UploadJobService onStartJob")
UploadFile(applicationContext).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, PATH, SERVER, USERNAME, PASSWORD)
var uploadTask = UploadFile(applicationContext)
timer.schedule(UploadTick(uploadTask, applicationContext),0, 1 * 10000)
return UploadTick.Result.SUCCESS
}
internal class UploadTick(task: UploadFile, ctx: Context): TimerTask() {
private val SERVER = ""
private val USERNAME = ""
private val PASSWORD = ""
private val PATH = ""
private var _task = task
private val _context = ctx
override fun run() {
Log.d("UploadTick", _task.status.toString())
if(_task.status == AsyncTask.Status.PENDING) {
_task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, PATH, SERVER, USERNAME, PASSWORD)
} else if(_task.status == AsyncTask.Status.FINISHED) {
_task = UploadFile(_context)
_task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, PATH, SERVER, USERNAME, PASSWORD)
}
}
}
companion object {
private val TAG = UploadTick::class.java.simpleName
}
}
答案 0 :(得分:2)
两种解决方案:
使用警报管理器和IntentService定期调度任务,即使应用程序在后台运行也是如此:
final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final Intent i = new Intent(context, UpdateService.class);
if (pendingIntent == null) {
pendingIntent = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
}
manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), INTERVAL_TIME_MILLIS, pendingIntent);
}
使用工作管理器并定期安排它,如下所示:
WorkManager.getInstance().enqueue(new
PeriodicWorkRequest.Builder(FiveDayDataApiDownloader.class, 24,
TimeUnit.HOURS).setConstraints(new
Constraints.Builder().setRequiresBatteryNotLow(true).build()).build());