|
| 1 | +package com.github.pwittchen.reactivenetwork.kotlinapp |
| 2 | + |
| 3 | +import android.net.wifi.ScanResult |
| 4 | +import android.os.Bundle |
| 5 | +import android.support.v7.app.AppCompatActivity |
| 6 | +import android.util.Log |
| 7 | +import android.widget.ArrayAdapter |
| 8 | +import com.github.pwittchen.reactivenetwork.library.ReactiveNetwork |
| 9 | +import kotlinx.android.synthetic.activity_main.access_points |
| 10 | +import kotlinx.android.synthetic.activity_main.connectivity_status |
| 11 | +import rx.Subscription |
| 12 | +import rx.android.schedulers.AndroidSchedulers |
| 13 | +import rx.schedulers.Schedulers |
| 14 | +import java.util.* |
| 15 | + |
| 16 | +class MainActivity : AppCompatActivity() { |
| 17 | + private var wifiSubscription: Subscription? = null |
| 18 | + private var connectivitySubscription: Subscription? = null |
| 19 | + |
| 20 | + companion object { |
| 21 | + private val TAG = "ReactiveNetwork" |
| 22 | + } |
| 23 | + |
| 24 | + override fun onCreate(savedInstanceState: Bundle?) { |
| 25 | + super.onCreate(savedInstanceState) |
| 26 | + setContentView(R.layout.activity_main) |
| 27 | + } |
| 28 | + |
| 29 | + override fun onResume() { |
| 30 | + super.onResume() |
| 31 | + val reactiveNetwork: ReactiveNetwork = ReactiveNetwork() |
| 32 | + |
| 33 | + connectivitySubscription = reactiveNetwork.observeConnectivity(this) |
| 34 | + .subscribeOn(Schedulers.io()) |
| 35 | + .observeOn(AndroidSchedulers.mainThread()) |
| 36 | + .subscribe { connectivityStatus -> |
| 37 | + connectivity_status.text = connectivityStatus.toString(); |
| 38 | + Log.d(TAG, connectivityStatus.toString()) |
| 39 | + } |
| 40 | + |
| 41 | + wifiSubscription = reactiveNetwork.observeWifiAccessPoints(this) |
| 42 | + .subscribeOn(Schedulers.io()) |
| 43 | + .observeOn(AndroidSchedulers.mainThread()) |
| 44 | + .subscribe { scanResults -> displayAccessPoints(scanResults) } |
| 45 | + } |
| 46 | + |
| 47 | + private fun displayAccessPoints(scanResults: List<ScanResult>) { |
| 48 | + val ssids = ArrayList<String>() |
| 49 | + |
| 50 | + for (scanResult in scanResults) { |
| 51 | + ssids.add(scanResult.SSID) |
| 52 | + } |
| 53 | + |
| 54 | + access_points.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, ssids) |
| 55 | + } |
| 56 | + |
| 57 | + override fun onPause() { |
| 58 | + super.onPause() |
| 59 | + safelyUnsubscribe(connectivitySubscription) |
| 60 | + safelyUnsubscribe(wifiSubscription) |
| 61 | + } |
| 62 | + |
| 63 | + private fun safelyUnsubscribe(subscription: Subscription?) { |
| 64 | + if (subscription != null && !subscription.isUnsubscribed) { |
| 65 | + subscription.unsubscribe() |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments