通过参考处理和解决“网络使用过多(后台)”的正确方法 https://stackoverflow.com/questions/54489501/proper-way-to-tackle-and-resolve-excessive-network-usage-background
经过几个月的调试,我们现在可以在前台服务中运行所有与网络相关的代码。
但是,我们仍然在 Android Vital 中收到“网络使用过多(后台)”警告。
当前台服务代码执行时,通知UI将始终显示在状态栏区域。
当我们“退出”应用程序时,我们启动前台服务,使用WorkManager
. The WorkManager
前台服务启动后立即返回。
public class SyncWorker extends Worker {
@NonNull
@Override
public Result doWork() {
final Intent intent = new Intent(WeNoteApplication.instance(), SyncForegroundIntentService.class);
ContextCompat.startForegroundService(
WeNoteApplication.instance(),
intent
);
return Result.success();
}
}
public class SyncForegroundIntentService extends IntentService {
private static final String TAG = "com.yocto.wenote.sync.SyncIntentService";
public SyncForegroundIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
final Context context = WeNoteApplication.instance();
NotificationCompat.Builder builder = new NotificationCompat.Builder(...
startForeground(SYNC_FOREGROUND_INTENT_SERVICE_ID, builder.build());
// Perform networking operation within foreground service.
stopForeground(true);
边注
我们认为我们没有发送大量数据。正如您所看到的,我们的最新版本处于最低范围(每小时 0 - 5 MB)
知道为什么我们仍然收到“网络使用过多(背景)”吗?显然,我们不再在后台执行任何网络调用。
我们利用https://developer.android.com/reference/android/app/Service.html#startForeground(int,%20android.app.Notification) https://developer.android.com/reference/android/app/Service.html#startForeground(int,%20android.app.Notification) and https://developer.android.com/reference/android/content/Context.html#startForegroundService(android.content.Intent) https://developer.android.com/reference/android/content/Context.html#startForegroundService(android.content.Intent)