android on连接到网络侦听器背景

时间:2018-10-11 14:17:24

标签: android

在版本(7.0)之后执行此操作的最佳方法是什么 我使用“ BroadcastReceiver”进行了此操作,但是在版本(7.0)之后,问题开始出现 我尝试使用“ GcmTaskService”和“ JobScheduler” 但是我没有找到正确的方法。 有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

RxAndroid(https://github.com/ReactiveX/RxAndroid)提供了非常有用的工具来响应异步进程。

与网络连接特别相关的是,您可以使用内置的android NetworkManager和WifiConfiguration开始连接,并使用RxAndroid ReactiveNetwork静态方法观察连接。

WifiConfiguration wifiConfig = new WifiConfiguration();
conf.ssid = "\"SecureNetwork\"" //Note that quote characters are required in the SSID
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

WifiManager wifiManger = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
if (wifiManager == null) {
    //error handling - make sure you have permissions etc
}

int connectionId = wifiManager.addNetwork(conf);
if (connectionId == -1) {
    //Network is already configured - find configuration using wifiManger.getConfiguredNetworks();
}

wifiManager.enableNetwork(connectionId, true); //Attempt to connect to network

//Now use RxAndroid ReactiveNetwork to observe connectivity

ReactiveNetwork.observeNetworkConnectivity(context)
    .filter(ConnectivityPredicate.hasState(NetworkInfo.State.CONNECTED))
    .filter(ConnectivityPredicate.hasType(ConnectivityManager.TYPE_WIFI))
    .flatMap(connectivity -> {
        int currentNetId = wifiManager.getConnectionInfo().getNetworkId();
        if (currentNetId == connectionNetId) {
             return Observable.just(true);
        } else {
             return Observable.error("Not connected to new network")
        }
    .doOnNext(mBoolean -> //Do whatever you want to now that you are connect)
    .doOnError(mError ->> //Handle error)
    .suscribe();