日常网络运营的最佳方式

Optimal way for a daily network operation

我现在有点困惑。 "correct" / "optimal" 在 android 应用程序中进行日常网络操作的方式是什么? 伪代码:

If newDay
    HTTP Request to server
    If responseOfRequest equals something
        Do something
    If HTTP Request is unsuccessfull (no internet, server down, ...)
        Try again in 1 hour

我怎样才能做到这一点?我考虑过 JobService 但我的 minSDK 低于 Android 5.

干杯, DDerTyp

你需要的是service到运行后台逻辑和alarm.

先了解一点理论:

https://developer.android.com/training/scheduling/alarms.html#tradeoffs

重复警报是一种相对简单的机制,灵活性有限。它可能不是您应用程序的最佳选择,尤其是当您需要触发网络操作时。设计不当的警报会导致电池耗尽并给服务器带来沉重负担。 如果您拥有托管应用程序数据的服务器,使用 Google 云消息传递 (GCM) 结合同步适配器是比 AlarmManager 更好的解决方案。

https://developer.android.com/training/sync-adapters/running-sync-adapter.html

默认情况下,当设备关闭时,所有警报都会被取消。

您需要在开始时在应用中的某个位置设置闹钟,但要保存一个标志,因为您不想在用户每次打开应用时都设置此闹钟

if (!appSettings.isAlarmSetUp()) {
    final AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    final Intent i = new Intent(context, CustomService.class);
    final Intent intentNotRepeat = new Intent(context, CustomService.class);
    final PendingIntent pi = PendingIntent.getService(context, 0, i, 0);

    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AlarmManager.INTERVAL_HALF_HOUR, AlarmManager.INTERVAL_DAY, pi);

    appSettings.setAlarmSetUp(true);
}

这里是关于警报的更多信息: https://developer.android.com/training/scheduling/alarms.html#type

如您所见,此警报正在唤醒 CustomService,您将在其中执行所有逻辑

public class CustomService extends IntentService {

    public CustomService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // Request to server
        client.requestToServer()
                .subscribe(response -> {
                                // Successful response
                                doSomething(response);
                            }
                        },
                        error -> {
                                // Error
                                createAlarmInOneHour();
                        });
    }
}