You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
TermApp/app/src/main/java/com/xypower/mpapp/NetworkChangedReceiver.java

89 lines
3.5 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.xypower.mpapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import java.lang.ref.WeakReference;
public class NetworkChangedReceiver extends BroadcastReceiver {
private WeakReference<MicroPhotoService> mService;
public NetworkChangedReceiver() {
super();
mService = null;
}
public NetworkChangedReceiver(MicroPhotoService service) {
mService = new WeakReference<>(service);
}
private String getConnectionType(int type) {
String connType = "";
if (type == ConnectivityManager.TYPE_MOBILE) {
connType = "3G";
} else if (type == ConnectivityManager.TYPE_WIFI) {
connType = "WIFI";
}
return connType;
}
@Override
public void onReceive(Context context, Intent intent) {
if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {// 监听wifi的打开与关闭与wifi的连接无关
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
Log.e("TAG", "wifiState:" + wifiState);
switch (wifiState) {
case WifiManager.WIFI_STATE_DISABLED:
break;
case WifiManager.WIFI_STATE_DISABLING:
break;
}
}
// 监听wifi的连接状态即是否连上了一个有效无线路由
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
Parcelable parcelableExtra = intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (null != parcelableExtra) {
// 获取联网状态的NetWorkInfo对象
NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
//获取的State对象则代表着连接成功与否等状态
NetworkInfo.State state = networkInfo.getState();
//判断网络是否已经连接
boolean isConnected = state == NetworkInfo.State.CONNECTED;
// Log.e("TAG", "isConnected:" + isConnected);
if (isConnected) {
} else {
}
}
}
// 监听网络连接包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
//获取联网状态的NetworkInfo对象
NetworkInfo info = intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (info != null) {
// If connected and available
MicroPhotoService service = mService.get();
if (service != null) {
if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI
|| info.getType() == ConnectivityManager.TYPE_MOBILE) {
// Log.i("TAG", getConnectionType(info.getType()) + "连上");
}
} else {
// Log.i("TAG", getConnectionType(info.getType()) + "断开");
}
}
}
}
}
}