gpt4 book ai didi

android - 如何设置WorkManager在后台上传

转载 作者:搜寻专家 更新时间:2023-11-01 09:22:43 26 4
gpt4 key购买 nike

我如何使用 workmanager 进行后台上传工作,我有一个应用程序可以通过 FTP 将我的文件备份到电脑上,我想学习新的方法,因为在我的手机上,只有当我有应用程序时,旧的方法才有效并在我关闭应用程序时运行,后台任务停止。谁能帮我设置 workmanager

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
}

最佳答案

两种解决方案:

  1. 使用带有 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);
    }
  2. 使用工作管理器并像这样定期安排它:

    WorkManager.getInstance().enqueue(new 
    PeriodicWorkRequest.Builder(FiveDayDataApiDownloader.class, 24,
    TimeUnit.HOURS).setConstraints(new
    Constraints.Builder().setRequiresBatteryNotLow(true).build()).build());

关于android - 如何设置WorkManager在后台上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53353619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com