首页 > 解决方案 > android连接到网络监听器背景

问题描述

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

标签: android

解决方案


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();

推荐阅读