android - Android Context 的有效期是多久?

标签 android broadcastreceiver android-context

我正在开发一个在服务器上执行登录的 Android 应用程序。只有在登录之后,网络才能访问 Internet。互联网连接在 30 分钟不活动后丢失。 (这真的很烦人,这就是为什么我要尝试将其自动化...)

所以我的想法是创建一个应用程序,用户(也就是我懒惰的自己)只需输入一次他的凭据,而在他的余生中,登录会在后台自动进行。

当我尝试使用最佳实践来避免电池耗尽时,我首先想到了登录必须满足的条件:

  • 手机必须连接到 Wifi。
  • wifi 有特定名称(因为只有某些 Wifi 需要登录)
  • wifi 没有互联网连接。

我认为:使用 BroadcastReceiver,监听 CONNECTIVITY_ACTION,然后检查必要性。我阅读了有关 Manifest 注册接收器的最新更改,并使用了 Context 注册接收器,然后启动了 JobService。但一段时间后,应用程序不再接收这些操作。

Android Developer website状态:

Context-registered receivers receive broadcasts as long as their registering context is valid.

我想知道上下文实际有效多长时间?这是实现我的目标的正确方法吗?

最佳答案

在同一个地方有解释:

Context-registered receivers receive broadcasts as long as their registering context is valid. For an example, if you register within an Activity context, you receive broadcasts as long as the activity is not destroyed. If you register with the Application context, you receive broadcasts as long as the app is running.

使用 JobService 并使用 setRequiredNetworkType 设置所需的网络类型,不要使用 BroadcastReceiver 处理网络更改。您可以将您的作业设置为在设备重启后保留。

编辑:我将创建一个具有所需网络类型 WIFI 的持久性 JobService(如果设备连接到 WIFI 网络,它应该每次都运行)。如果它运行,我会检查设备是否连接到正确的网络。如果是这种情况,我将开始一个周期 < 30 分钟的新周期性工作。这项工作将检查您是否仍连接到正确的网络并登录(如果需要)。如果设备不再连接到正确的 WIFI,我会终止第二份工作。

关于android - Android Context 的有效期是多久?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48340043/

相关文章:

安卓:上下文对象

android - 如何查看 Android 应用程序特定缓存?

Android JUnit4 测试 - 从哪里获取上下文?

android - 在 Android 中模拟广播

android - 在 cocos2d-x 中有没有更好的方法来获取系统时间?

java - simpledateformat 更改时区

python - 无法使用 NetMQ 在 Unity3d 和 Python 之间发送消息

java - 如何修复错误将字节码转换为 dex 原因 :com. android.dex.DexException :Multiple dex files define Lorg/apache/http/conn/ssl/AbstractVerifier?

android - BroadcastReceiver 问题(接收器未注册错误)

android: 从 Broadcastreceiver 调用函数: 无法启动接收器 ... java.lang.ClassCastException: android.app.ReceiveRestrictedContext