固定间隔后从android中的后台执行REST调用

时间:2018-09-12 03:59:12

标签: android android-intent

我是Android的新手,我想知道执行后台操作的最有效方法,这是使用JSON Body进行的简单POST请求,它将在固定间隔后被点击。最好的方法是意图服务或异步任务。

2 个答案:

答案 0 :(得分:1)

请参考以下链接:https://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService

请在下面查看我的自定义课程示例。这将每2秒执行一次。

class CustomThreadExecutor {

    private lateinit var scheduledExecutorService: ScheduledExecutorService
    private lateinit var scheduledFuture: ScheduledFuture<*>

    init {
        //Start Scheduler as required
        startScheduler()
    }


    fun startScheduler() {
        scheduledExecutorService = Executors.newScheduledThreadPool(2)

        scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(
                { tempImageFetch() }, 0, 2, TimeUnit.SECONDS)
    }

    fun shutdownScheduler() {
        //Stop before exit the app or when necessary
        scheduledExecutorService.shutdownNow()

    }

    private fun tempImageFetch() {
        //TODO call API
    }
}

答案 1 :(得分:0)

您可以将FirebaseJobDispatcher用于Lollipop之上和之下的API级别。这是github链接:

https://github.com/firebase/firebase-jobdispatcher-android

如何实施:

将以下内容添加到build.gradle的依赖项部分:

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

为您的工作服务上课:

    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?"
        }
    }

在清单上添加此内容:

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

将此添加到您的主要活动onCreate方法上

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

    Bundle myExtrasBundle = new Bundle();
    myExtrasBundle.putString("some_key", "some_value");

    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
        )
        .setExtras(myExtrasBundle)
        .build();

    dispatcher.mustSchedule(myJob);

如果您的应用程序用于API级Lollipop及更高级别,则应使用JobSchedulerWorkManager

对于工作经理:

https://codelabs.developers.google.com/codelabs/android-workmanager/

对于JobScheduler:

http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html