在固定间隔后从安卓后台执行 REST 调用



我是Android新手,我想知道执行后台操作的最有效方法,这是一个带有JSON Body的简单POST请求,它将在固定的时间间隔后被击中。哪种方式是意图服务或异步任务。

创建一个 JobScheduler,如下所示

public static void scheduleJob(Context context) {
ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setMinimumLatency(1 * 1000); // wait at least
builder.setOverrideDeadline(3 * 1000); // maximum delay
charging or not
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
}

创建以下接收器

public class MyStartServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Util.scheduleJob(context);
}
}

在 Android 清单中为BOOT_COMPLETED事件注册接收器。

<receiver android:name="MyStartServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

创建作业服务并将代码添加到 onStartJob

public class TestJobService extends JobService {
private static final String TAG = "SyncService";
@Override
public boolean onStartJob(JobParameters params) {
Intent service = new Intent(getApplicationContext(), LocalWordService.class);
getApplicationContext().startService(service);
Util.scheduleJob(getApplicationContext()); // reschedule the job
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
return true;
}
}

有关更多详细信息,请参阅:链接此处

请参考此链接: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 
}
}

您可以将FirebaseJobDispatcher用于低于和高于棒棒糖的 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>

在创建方法的主要活动上添加以下内容:

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 级棒棒糖及更高版本,则应使用JobSchedulerWorkManager

对于工作管理器:

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

对于作业计划程序:

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

最新更新