使用 Android 中的 JobScheduler 检测网络状态变化 [英] Detect Network State change using JobSchedulers in Android

查看:29
本文介绍了使用 Android 中的 JobScheduler 检测网络状态变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Android N,您无法为 CONNECTIVITY_CHANGE 意图静态注册广播接收器.

With Android N, You cannot statically register a Broadcast receivers for CONNECTIVITY_CHANGE intent.

来自 http://developer.android.com/preview/features/background-optimization.html#connectivity-actionGoogle 文档建议使用 Job Scheduler 来执行此任务.

From http://developer.android.com/preview/features/background-optimization.html#connectivity-action Google documentation suggest using Job Schedulers to perform this task.

是否可以在 Android 中使用 Job Scheduler 检测网络状态变化(LTE 到 wifi),反之亦然?

Is it possible to detect network state change (LTE to wifi) and vice versa using Job Schedulers in Android?

推荐答案

是和否.

JobInfo.Builder.setRequiredNetworkType() 方法允许您安排作业在满足特定网络条件时运行.

The JobInfo.Builder.setRequiredNetworkType() method allows you to schedule jobs to run when specific network conditions are met.

网络类型可以是三个值之一:

The network type can be one of three values:

  • JobInfo.NETWORK_TYPE_NONE:无需网络连接.
  • JobInfo.NETWORK_TYPE_UNMETERED:未计量的 WiFi 或以太网连接.
  • JobInfo.NETWORK_TYPE_ANY:任何网络连接(WiFi 或蜂窝网络).
  • JobInfo.NETWORK_TYPE_NONE: No network connectivity required.
  • JobInfo.NETWORK_TYPE_UNMETERED: An unmetered WiFi or Ethernet connection.
  • JobInfo.NETWORK_TYPE_ANY: Any network connection (WiFi or cellular).

现在,问题是……没有 NETWORK_TYPE_CELLUAR.您不能让您的应用仅在在蜂窝网络上时唤醒.(你为什么要这样做?)

Now, the catch... there's no NETWORK_TYPE_CELLUAR. You can't have your app only wake up when it's only on cellular. (Why would you want to do that?)

另一个问题... WiFi 连接可以按流量计费或不按流量计费.计量连接通常是移动热点之类的东西,这可以自动检测到(热点可以发送一个特殊的 DHCP 选项),或者用户可以在每个网络的基础上从 WiFi 设置手动切换它.

The other catch... WiFi connections can be metered or unmetered. Metered connections are typically things like mobile hotspots, and this can either be automatically detected (there's a special DHCP option the hotspot can send), or the user can manually toggle it on a per-network basis from WiFi Settings.

所以,是的,您可以对 JobScheduler 作业设置网络类型约束.但是,不,您没有获得所需的粒度级别.

So, yes, you can set network-type constraints on your JobScheduler job. However, no, you don't get the level of granularity you're asking for.

正如@CommonsWare 所提到的,这个想法是您通常希望在网络连接未计量时安排与网络相关的作业,除非您有充分的理由.(使用 setRequiresCharging(true) 以节省电池电量,将作业推迟到交流电源可用也是一个好主意.)

As @CommonsWare mentioned, the idea is that you usually want to schedule network-related jobs to occur when network connectivity is unmetered, unless you have a good reason. (It's also a good idea to defer jobs until AC power is available, using setRequiresCharging(true), to conserve battery.)

这篇关于使用 Android 中的 JobScheduler 检测网络状态变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆