How to detect when WIFI Connection has been established in Android?

前端 未结 13 706
庸人自扰
庸人自扰 2020-11-22 05:34

I need to detect when I have network connectivity over WIFI. What broadcast is sent to establish that a valid network connection has been made. I need to validate that a v

相关标签:
13条回答
  • 2020-11-22 06:16

    Android O removed the possibility to receive the implicit broadcasts for a wifi state change. So if your app is closed, you'll not be able to receive them. The new WorkManager has the ability to run when your app is closed, so I've experimented a bit with it and it seems to work quite well:

    Add this to your dependencies:

    implementation "android.arch.work:work-runtime:1.0.0-alpha08"
    

    WifiConnectWorker.kt

    class WifiConnectWorker : Worker() {
    
        override fun doWork(): Result {
            Log.i(TAG, "I think we connected to a wifi")
            return Result.SUCCESS
        }
    }
    

    MainActivity.kt

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.main_activity)
    
            val workManager = WorkManager.getInstance()
    
            // Add constraint to start the worker when connecting to WiFi
            val request = OneTimeWorkRequest.Builder(WifiConnectWorker::class.java)
                .setConstraints(Constraints.Builder()
                    .setRequiredNetworkType(UNMETERED)
                    .build())
                .build()
    
            // The worker should be started, even if your app is closed
            workManager.beginUniqueWork("watch_wifi", REPLACE, request).enqueue()
        }
    }
    

    Keep in mind that this was just a quick test for a one-time notification. There is more work to do to always get notified when WiFi is turned on and off.

    PS: When the app is force quit, the worker is not started, it seems WorkManager is canceling the requests then.

    0 讨论(0)
提交回复
热议问题