android - android连接到网络监听器背景
问题描述
在版本(7.0)之后执行此操作的最佳方法是什么我使用“BroadcastReceiver”执行此操作但在版本(7.0)之后问题开始出现我尝试使用“GcmTaskService”和“JobScheduler”但我没有找到正确的方法. 谁能帮我?
解决方案
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();
推荐阅读
- visual-studio-code - Flutter 找不到模拟器所需的文件
- javascript - 用 Python 加密和用 Javascript 解密的问题
- visual-studio - 断点是纯红色的,但永远不会被命中。调用 Debugger.Launch() 要求在新的 VS2019 窗口中以管理员身份运行 Just In Time Debugger
- ios - navigationBarTitle 与 SwiftUI 中的列表标题重叠
- python - 有没有办法让不和谐的机器人自动做某事(没有消息)?
- c++ - 声明没有大小的 c++ 数组
- android - Flutter 相机插件不保存在 DCIM 文件夹中
- eclipse - 在 sts 3.6.0 中启动新的 spring starter 项目时出错
- .net - 在 .NET Framework 中验证/验证没有密钥/公钥的 JWT 令牌?
- javascript - 有没有办法通过 JavaScript 或 jQuery 在数组中移动对象数组而不循环(请仅 ES5 回答)?