在后台服务中上传数据

Uploading Data in Background Service

我想在设备唤醒时大约每 2 分钟上传一次当前用户的位置,或者在设备未唤醒时大约每 5 分钟上传一次。

将后台数据(即使应用程序不是 运行)上传到网络服务器的最佳方式是什么? IntentServiceAlarmManagerAsyncTaskCountdownTimer 之类的东西更好吗?

我已经知道如何获取用户的位置,并且对 AsyncTaskIntentService 进行了一些练习。任何帮助,将不胜感激!谢谢!

既然你想在特定的时间段内完成任务,我建议你使用Firebase Job Scheduler和IntentService。

使用 Firebase Job Dispatcher 有很多优点。

  1. You can give it constraints like "Do a task only on battery or Do a task when charging and with wifi"
  2. This has efficiency built-in

您可以阅读有关 Firebase 作业调度程序的更多信息here

我会推荐Firebase JobDispatcher.

它比 AlarmManager、Jobschedular 和 GCMNetworkManager 有一些优势。 阅读此 blog 了解详情。

用法:

Add the following to your build.gradle's dependencies section:

implementation 'com.firebase:firebase-jobdispatcher:0.8.5'

Create a new MyJobService class.

public class MyJobService extends JobService {
    @Override
    public boolean onStartJob(JobParameters job) {
        // Do some work here

        return false; // Answers the question: "Is there still work going on?"
    }

    @Override
    public boolean onStopJob(JobParameters job) {
        return false; // Answers the question: "Should this job be retried?"
    }
}

Adding it to the manifest

    <service
        android:exported="false"
        android:name=".MyJobService">
        <intent-filter>
            <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
        </intent-filter>
    </service>

Scheduling a job

FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));

Job myJob = dispatcher.newJobBuilder()
        // the JobService that will be called
        .setService(MyJobService.class)
        // uniquely identifies the job
        .setTag("my-unique-tag")
        // one-off job
        .setRecurring(false)
        // don't persist past a device reboot
        .setLifetime(Lifetime.UNTIL_NEXT_BOOT)
        // start between 0 and 60 seconds from now
        .setTrigger(Trigger.executionWindow(0, 60))
        // don't overwrite an existing job with the same tag
        .setReplaceCurrent(false)
        // retry with exponential backoff
        .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
        // constraints that need to be satisfied for the job to run
        .setConstraints(
                // only run on an unmetered network
                Constraint.ON_UNMETERED_NETWORK,
                // only run when the device is charging
                Constraint.DEVICE_CHARGING
        )
        .build();

dispatcher.mustSchedule(myJob);

有两种更好的方法可以帮助您:

1.当应用唤醒时

You can use handler for timer purpose and from the handle call IntentService for location update. IntentService will work in different Thread and will finished itself after work completion. Handler Example

2。当应用程序不是 运行

You have to use AlarmManager and from the Alarm Receiver you will call IntentService for location update. AlarmManager Example

希望对您有所帮助。