简体   繁体   English

Wifi状态更改(连接或断开与网络的连接)时如何触发JobScheduler?

[英]How to trigger a JobScheduler when Wifi state changes(connected or disconnected from Network)?

I want to run a piece of code when Wifi is connected or disconnected from some router. 当Wifi与某些路由器连接或断开连接时,我想运行一段代码。 I can use service and BrodcastReceiver for this but as of Oreo, the service is killed few minutes after the app is closed (unless in foreground). 我可以为此使用service和BrodcastReceiver ,但是从Oreo开始,该服务将在应用关闭后几分钟BrodcastReceiver (除非在前台)。 So, I am trying to use JobScheduler for this but I can't figure out what triggers to provide for execution of my Job. 因此,我试图为此使用JobScheduler ,但是我不知道是什么触发器为执行Job提供了条件。

Android doesn't want to run your code each time there's a network change. 当网络发生变化时,Android不想运行您的代码。 These changes may occur several times per minute and your code will cause too much battery drain. 这些更改可能每分钟发生几次,并且您的代码将导致过多的电池消耗。

The best you can do is schedule your job to run at regular intervals (which cannot be too short — if you request less than 15 minutes, you won't get it regularly) and check what you need in there. 您能做的最好的事情就是安排您的工作定期执行(这不能太短-如果您要求的时间少于15分钟,您就不会定期得到它)并检查那里需要什么。 You can request that your job runs only when there's network connectivity, but not the opposite (to run when there's no connectivity). 您可以要求作业仅在有网络连接时运行,而不是相反(在没有网络连接时运行)。

You can do this perfectly with the Firebase JobDispatcher. 您可以使用Firebase JobDispatcher完美地做到这一点。

Code to start the job: 启动作业的代码:

fun startNetworkChangeJob() {
    // Create a new dispatcher using the Google Play driver.
    val dispatcher = FirebaseJobDispatcher(GooglePlayDriver(app))

    val myJob = dispatcher.newJobBuilder()
            // the JobService that will be called
            .setService(NetworkChangeJob::class.java)
            // uniquely identifies the job
            .setTag(app.getString(R.string.networkChangeJobId))
            // recurring job
            .setRecurring(true)
            // don't persist past a device reboot
            .setLifetime(Lifetime.FOREVER)
            // start between 0 and 60 seconds from now
            .setTrigger(Trigger.executionWindow(0, 60))
            // don't overwrite an existing job with the same tag
            .setReplaceCurrent(false)
            // retry with exponential backoff
            .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
            // constraints that need to be satisfied for the job to run
            .setConstraints(
                    // only run on an unmetered network
                    Constraint.ON_UNMETERED_NETWORK
            )
            .build()

    dispatcher.mustSchedule(myJob)
}

Then the job itself. 然后是工作本身。 Here you can place your logic to determine what to do: 在这里,您可以放置​​逻辑以确定要做什么:

override fun onStartJob(job: com.firebase.jobdispatcher.JobParameters): Boolean {
    // Runs on the main thread!

    checkIfNeedToStartService()

    return false  // Answers the question: "Is there still work going on?"
}

override fun onStopJob(job: com.firebase.jobdispatcher.JobParameters): Boolean {
    // Runs on the main thread!

    return true // Answers the question: "Should this job be retried?"
}

Be sure to also add the following to your manifest: 确保还要在清单中添加以下内容:

<service
        android:name=".jobs.NetworkChangeJob"
        android:exported="false">
        <intent-filter>
            <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE" />
        </intent-filter>
    </service>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Android 应用程序检测 WiFi 网络中连接的所有设备 - How to detect all the Devices connected in a WiFi network from Android App 用户Wifi从一个网络更改为另一个网络时如何获得通知 - How to get notified when the users Wifi changes from one network to other 网络功能显示为真,当 vpn 连接但.net 断开连接时 - Network Capabilities is showing true, when vpn connected but net disconnected 检查网络连接已连接/已断开 - Check network connection connected/disconnected 如何判断手机是连接到 wifi 网络还是蜂窝网络? - How can you tell if a phone is connected to a wifi network or a cell network? 当 WiFi 和蜂窝数据在 Android Studio 中连接时,如何以编程方式分别对它们进行网络操作? - How do I perform network operation programmatically on WiFi and cellular data separately when both are connected in Android Studio? 在android中更改wifi时如何获取连接的wifi ssid - How to take the connected wifi ssid when change the wifi in android 如何在Android中使用后台服务触发wifi状态更改? - How to trigger wifi state change using a background service in android? 网络断开时更改活动 - Change activity when network is disconnected ActiveMQ静态网络:断开连接后如何丢弃消息? - ActiveMQ Static Network : How do I drop messages when disconnected?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM