不推荐使用Android getAllNetworkInfo().有什么选择? [英] Android getAllNetworkInfo() is Deprecated. What is the alternative?
问题描述
我想使用提供getAllNetworkInfo()
方法的ConnectivityManager
来检查Android中的网络可用性. API级别23中不推荐使用此方法.开发人员文档建议改为使用getAllNetworks()
.我尝试过,但无法获得从旧代码中获得的确切功能.请有人可以指导我如何使用getAllNetworks()
方法?
I want to use the ConnectivityManager
which provides the getAllNetworkInfo()
method for checking the availability of network in Android. This method was deprecated in API level 23. And the developer documentation is suggesting to use getAllNetworks()
instead. I tried but couldn't get the exact functionalities which I was getting out of my old code. Please someone could guide me how to use the getAllNetworks()
method?
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
@SuppressWarnings("deprecation")
NetworkInfo[] info = connectivity.getAllNetworkInfo();
//use getAllNetworks() instead
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
推荐答案
当我更新不赞成使用的代码并且仍然希望支持反向Api时.我用这个:
When i update my deprecated code and still want to support backward Api. i use this :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.WANTED API VERSION){
//code
}else{
//code
}
通过这种方式,每个设备都为其使用适当的代码. 示例:
In this way each device use the appropriate code for it. Example:
public class ConnectionDetector {
private Context mContext;
public ConnectionDetector(Context context) {
this.mContext = context;
}
/**
* Checking for all possible internet providers
* **/
public boolean isConnectingToInternet() {
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivityManager.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = connectivityManager.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
return true;
}
}
}else {
if (connectivityManager != null) {
//noinspection deprecation
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo anInfo : info) {
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
LogUtils.d("Network",
"NETWORKNAME: " + anInfo.getTypeName());
return true;
}
}
}
}
}
Toast.makeText(mContext,mContext.getString(R.string.please_connect_to_internet),Toast.LENGTH_SHORT).show();
return false;
}
}
这篇关于不推荐使用Android getAllNetworkInfo().有什么选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!