ConnectionDetector.java
public class ConnectionDetector {
private Context mContext;
public ConnectionDetector(Context context) {
mContext = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
ConnectionChangeReceiver.java
public class ConnectionChangeReceiver extends BroadcastReceiver {
private final String TAG = ConnectionChangeReceiver.class.getSimpleName();
private static int lastType = -1;//1 网络断开,-1 网络连接
private boolean mFirstReg = true;//首次注册时候会触发一次,所以做多了个首次注册的判断
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// 检查连接状态
ConnectionDetector cd = new ConnectionDetector(context);
Boolean isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
if (lastType != -1) {
Toast.makeText(context, "网络连接中断", Toast.LENGTH_LONG).show();
Log.i(TAG, "网络连接中断");
}
lastType = -1;
} else {
if (lastType != 1 && !mFirstReg) {
Toast.makeText(context, "网络连接上", Toast.LENGTH_LONG).show();
Log.i(TAG, "网络连接上");
}
lastType = 1;
}
mFirstReg = false;
}
}
使用方法:
public class MainActivity extends Activity {
private ConnectionChangeReceiver mNetworkStateReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNetworkStateReceiver = new ConnectionChangeReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver, filter);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(mNetworkStateReceiver);
}
}