用作 Android 4.0 及更高版本已弃用的getActiveNetworkInfo()
替代方法ConnectivityManager.getBackgroundDataSetting()
在更改(受限)时不支持后台数据设置。还有其他选择吗?
这是代码片段:
ConnectivityManager connectivityManager;
connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager != null) {
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info.isConnected() == true) {
System.out.println("running");
Toast.makeText(context, "Background settings enabled", Toast.LENGTH_SHORT).show();
} else {
System.out.println("active network info null");
System.out.println("enable background services");
Toast.makeText(context, "background settings disabled", Toast.LENGTH_SHORT).show();
}
} else {
LogUtil.w(getClass(), "Application does not have ACCESS_NETWORK_STATE Permission");
}
注意:" if(connectivityManager.getBackgroundDataSetting()
" 适用于 2.3.3,但在 android 4.0+ 替换为 " if (info.isConnected() == true)
" 时,即使后台数据设置受到限制,也始终返回 true。