在Foreground服务中运行网络代码后,仍然收到“网络使用率过高(背景)”警告

Che*_*eng 7 android

通过引用正确的方式来解决和解决“网络使用过多(背景)”

经过几个月的调试,我们现在可以在Foreground服务中运行所有与网络相关的代码。

但是,我们仍然在Android Vital中收到“网络使用率过高(背景)”警告。

在此处输入图片说明

执行前台服务代码时,通知UI始终会显示在状态栏区域中。

在此处输入图片说明

当我们“退出”我们的应用程序时,我们使用来启动前台服务WorkManagerWorkManager启动前台服务后,会立即返回。

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);
Run Code Online (Sandbox Code Playgroud)

边注

我们认为我们没有发送大量数据。如您所见,我们的最新版本处于最低范围(每小时0-5 MB)

在此处输入图片说明


知道为什么我们仍然会收到“网络使用率过高(背景)”的信息吗?显然,我们不再在后台执行任何联网呼叫。

我们利用https://developer.android.com/reference/android/app/Service.html#startForeground(int,%20android.app.Notification)https://developer.android.com/reference/android/content/ Context.html#startForegroundService(android.content.Intent)


Sim*_*mon 6

您正在使用Worker调用ForegroundService。从Worker的文档中:

Worker类在运行时由WorkManager实例化,并且 doWork()方法在预先指定的后台线程上调用(请参阅Configuration.getExecutor())。此方法用于同步处理您的工作,这意味着一旦您从该方法返回,便会认为Worker已经完成并将被销毁。(...)如果由于任何原因抢占了作品,则不会重复使用相同的Worker实例。这意味着doWork()在每个Worker实例中仅被调用一次。如果需要重新运行工作单元,则会创建一个新的工作程序。

A ForegroundServiceService处于前台状态的a,这意味着,如果系统需要CPU或您的应用已关闭,则系统不会终止该进程。这个,也只有那个。我找不到能证明这一点的Android Vital文档,所以这只是我的怀疑,但我很肯定是这样:这意味着,无论您是否使用ForegroundServiceAndroid Vital仍然很重要这作为背景工作。

将应用的移动网络使用率提高到前台的一种正确方法是DownloadManager使用适当的可见性设置集进行呼叫(如您提供的链接中所述)。请告诉我是否有帮助-否则,我们将尝试其他尝试。顺便说一句,您是否能够将统计信息缩小到特定的API版本?(在9.0和8.0中有一些后台线程更改,因此这也可能是一个提示)