下面列出了怎么用android.net.ConnectivityManager的API类实例代码及写法,或者点击链接到github查看源代码。
public static boolean isRoaming()
{
try
{
ConnectivityManager connectivityManager = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
if (netInfo != null)
return netInfo.isRoaming();
}
catch (Exception e)
{
FileLog.e(e);
}
return false;
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo anInfo : info) {
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
public static boolean isCtwap(Context context)
{
if (!"CN".equalsIgnoreCase(((TelephonyManager)context.getSystemService("phone")).getSimCountryIso()))
{
return false;
}
ConnectivityManager connectivitymanager = (ConnectivityManager)context.getSystemService("connectivity");
if (connectivitymanager == null)
{
return false;
}
NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
if (networkinfo == null)
{
return false;
}
String s = networkinfo.getExtraInfo();
if (TextUtils.isEmpty(s) || s.length() < 3)
{
return false;
}
return s.contains("ctwap");
}
public static boolean isNetworkOnlineFast() {
try {
ensureCurrentNetworkGet(false);
if (currentNetworkInfo == null) {
return true;
}
if (currentNetworkInfo.isConnectedOrConnecting() || currentNetworkInfo.isAvailable()) {
return true;
}
NetworkInfo netInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
netInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
}
} catch (Exception e) {
FileLog.e(e);
return true;
}
return false;
}
public static GetHomeBundlesRequest of(int limit, int offset, OkHttpClient httpClient,
Converter.Factory converterFactory, BodyInterceptor bodyInterceptor,
TokenInvalidator tokenInvalidator, SharedPreferences sharedPreferences,
WSWidgetsUtils widgetsUtils, BaseRequestWithStore.StoreCredentials storeCredentials,
String clientUniqueId, boolean isGooglePlayServicesAvailable, String partnerId,
boolean accountMature, String filters, Resources resources, WindowManager windowManager,
ConnectivityManager connectivityManager,
AdsApplicationVersionCodeProvider versionCodeProvider, List<String> packageNames,
AppBundlesVisibilityManager appBundlesVisibilityManager) {
return new GetHomeBundlesRequest(
new Body(limit, offset, WidgetsArgs.createDefault(resources, windowManager)), httpClient,
converterFactory, bodyInterceptor, tokenInvalidator, sharedPreferences, widgetsUtils,
storeCredentials, clientUniqueId, isGooglePlayServicesAvailable, partnerId, accountMature,
filters, resources, windowManager, connectivityManager, versionCodeProvider, packageNames,
appBundlesVisibilityManager);
}
/**
* 获取网络状态
*
* @param context
* @return
*/
public static int getNetworkState(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// Wifi
NetworkInfo.State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
return NETWORN_WIFI;
}
// 3G
state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState();
if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
return NETWORN_MOBILE;
}
return NETWORN_NONE;
}
/**
* 获取当前网络类型
*
* @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
*/
public static int getNetworkType(Context context) {
int netType = 0;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null) {
return netType;
}
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_MOBILE) {
String extraInfo = networkInfo.getExtraInfo();
if (!TextUtils.isEmpty(extraInfo)) {
if (extraInfo.toLowerCase(Locale.getDefault()).equals("cmnet")) {
netType = NETTYPE_CMNET;
} else {
netType = NETTYPE_CMWAP;
}
}
} else if (nType == ConnectivityManager.TYPE_WIFI) {
netType = NETTYPE_WIFI;
}
return netType;
}
@VisibleForTesting
AndroidChannel(final ManagedChannel delegate, @Nullable Context context) {
this.delegate = delegate;
this.context = context;
if (context != null) {
connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
configureNetworkMonitoring();
} catch (SecurityException e) {
Log.w(
LOG_TAG,
"Failed to configure network monitoring. Does app have ACCESS_NETWORK_STATE"
+ " permission?",
e);
}
} else {
connectivityManager = null;
}
}
private boolean isWifiOrEthernetConnection() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// In flight mode.
return false;
}
if (!ni.isConnected()) {
// No network connection.
return false;
}
switch (ni.getType()) {
case ConnectivityManager.TYPE_WIFI:
case ConnectivityManager.TYPE_WIMAX:
case ConnectivityManager.TYPE_ETHERNET:
return true;
default:
return false;
}
}
/**
* 打印当前各种网络状态
*
* @return boolean
*/
public static boolean printNetworkInfo(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
LogUtils.i(TAG, "NetworkInfo[" + i + "]isAvailable : " + info[i].isAvailable());
LogUtils.i(TAG, "NetworkInfo[" + i + "]isConnected : " + info[i].isConnected());
LogUtils.i(TAG, "NetworkInfo[" + i + "]isConnectedOrConnecting : " + info[i].isConnectedOrConnecting());
LogUtils.i(TAG, "NetworkInfo[" + i + "]: " + info[i]);
}
LogUtils.i(TAG, "\n");
} else {
LogUtils.i(TAG, "getAllNetworkInfo is null");
}
}
return false;
}
@Override
public void onReceive(Context context, Intent intent) {
if (mNetworkListener == null) {
return;
}
if (intent.getAction() != null
&& intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
boolean isNetworkAvailable = NetworkStateUtil.isNetworkAvailable(context);
if (isNetworkAvailable) {
mNetworkListener.onNetworkState(NetworkState.CONNECTED);
} else {
mNetworkListener.onNetworkState(NetworkState.DISCONNECTED);
}
}
}
private boolean isMobileDataConnection() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// In flight mode.
return false;
}
if (!ni.isConnected()) {
// No network connection.
return false;
}
switch (ni.getType()) {
case ConnectivityManager.TYPE_BLUETOOTH:
case ConnectivityManager.TYPE_MOBILE:
case ConnectivityManager.TYPE_MOBILE_DUN:
case ConnectivityManager.TYPE_MOBILE_HIPRI:
return true;
default:
return false;
}
}
public static int getNetworkState(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// Wifi
State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
if (state == State.CONNECTED || state == State.CONNECTING) {
return STATE_WIFI;
}
// 3G
state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState();
if (state == State.CONNECTED || state == State.CONNECTING) {
return STATE_MOBILE;
}
return STATE_DISCONNECT;
}
@Override
public void linkStart() {
if(register)
return;
register = true;
Log.d(TAG, "[+] Starting Wifi");
wifiMan = (WifiManager) RumbleApplication.getContext().getSystemService(Context.WIFI_SERVICE);
wifiInf = wifiMan.getConnectionInfo();
macAddress = wifiInf.getMacAddress();
if (WifiUtil.isWiFiApEnabled() || WifiUtil.isEnabled()) {
linkConnected();
}
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Handler handler = new Handler(getLooper());
RumbleApplication.getContext().registerReceiver(mReceiver, filter, null, handler);
if(!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
}
public static boolean isAllowedToDownloadMetadata(final Context context) {
switch (PreferenceUtil.getInstance(context).autoDownloadImagesPolicy()) {
case "always":
return true;
case "only_wifi":
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
return netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI && netInfo.isConnectedOrConnecting();
case "never":
default:
return false;
}
}
public void getStatus(View view) {
TextView textView = findViewById(R.id.textView);
if (isOnline()) {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
textView.setText(networkInfo.getTypeName());
} else {
textView.setText("Offline");
}
}
/**
* 检查WIFI是否连接
*/
public static boolean isWifiConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) App.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return wifiInfo != null;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Connectivity changed");
ServerConnectionManager.getInstance(context).notifyConnectivityChanged(!intent
.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE));
ServerPingScheduler.getInstance(context).onWifiStateChanged(
ServerConnectionManager.isWifiConnected(context));
}
public static boolean isConnectedToWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected()
&& ni.getType() == ConnectivityManager.TYPE_WIFI;
}
/**
* Get the connectivity state as reported by the Android system
*
* @param context Android context
* @return the connectivity state as reported by the Android system
*/
private static boolean getSystemConnectivity(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return false;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork.isConnectedOrConnecting();
} catch (Exception exception) {
return false;
}
}
/**
* Starts watching for changes. Must be called from a thread that has an associated {@link
* Looper}. Listener methods are called on the caller thread.
*/
public void start() {
Assertions.checkNotNull(Looper.myLooper());
requirementsWereMet = requirements.checkRequirements(context);
IntentFilter filter = new IntentFilter();
if (requirements.getRequiredNetworkType() != Requirements.NETWORK_TYPE_NONE) {
if (Util.SDK_INT >= 23) {
registerNetworkCallbackV23();
} else {
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
}
}
if (requirements.isChargingRequired()) {
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
}
if (requirements.isIdleRequired()) {
if (Util.SDK_INT >= 23) {
filter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
} else {
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
}
}
receiver = new DeviceStatusChangeReceiver();
context.registerReceiver(receiver, filter, null, new Handler());
logd(this + " started");
}
/**
* test if there is some connection
* @param ctx
* @return
*/
public static boolean verifyConnectivity(Context ctx)
{
ConnectivityManager connectivityManager = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
return netInfo!=null && netInfo.isConnectedOrConnecting();
}
public WifiState getWifiState() {
if (Environment.isEmulator()) {
return WifiState.CONNECTED;
} else {
switch (wifiManager.getWifiState()) {
case WifiManager.WIFI_STATE_ENABLED:
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
return WifiState.CONNECTED;
} else {
switch (WifiInfo.getDetailedStateOf(wifiManager.getConnectionInfo().getSupplicantState())) {
case SCANNING:
return WifiState.SCANNING;
case AUTHENTICATING:
case CONNECTING:
case OBTAINING_IPADDR:
return WifiState.CONNECTING;
default:
return WifiState.ENABLED;
}
}
case WifiManager.WIFI_STATE_ENABLING:
return WifiState.ENABLING;
default:
return WifiState.DISABLED;
}
}
}
public static boolean hasInternetConnection(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getApplicationContext().
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if(!(networkInfo != null && networkInfo.isConnected())) {
return false;
} else
return true;
}
public static GetAdsRequest of(Location location, String keyword, Integer limit,
String clientUniqueId, boolean googlePlayServicesAvailable, String oemid, boolean mature,
OkHttpClient httpClient, Converter.Factory converterFactory, String q,
SharedPreferences sharedPreferences, ConnectivityManager connectivityManager,
Resources resources, AdsApplicationVersionCodeProvider versionCodeProvider) {
GetAdsRequest adsRequest =
new GetAdsRequest(clientUniqueId, googlePlayServicesAvailable, oemid, mature,
converterFactory, httpClient, q, sharedPreferences, connectivityManager, resources,
versionCodeProvider);
adsRequest.setLocation(location);
adsRequest.setKeyword(keyword);
adsRequest.setLimit(limit);
return adsRequest;
}
/**
* 判断是否是wifi连接
*/
public static boolean isWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}
@Override
public boolean getWiFiNetworkAvailable() {
if (!mHasNetworkStatePermission) {
// if we're unable to check network state, assume we have a network
return true;
}
final NetworkInfo wifi = mConnectionManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return wifi != null && wifi.isConnected();
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) {
updateSimState(intent);
notePhoneDataConnectionState();
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
action.equals(ConnectivityManager.INET_CONDITION_ACTION)) {
notePhoneDataConnectionState();
}
}
public static boolean isNetworkConnected(Context context) {
boolean isConnected = false;
try {
isConnected = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo().isConnectedOrConnecting();
} catch (Exception e) {
e.printStackTrace();
}
return isConnected;
}
private void register() {
try {
context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}