//网络是否连接
//权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
//网络连接管理器
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获得网络信息
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if(info!=null){
return true;
}
return false;
}
//是否是wifi
public boolean isWifi(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if(info!=null&&info.getType()==ConnectivityManager.TYPE_WIFI){
return true;
}
return false;
}
//是否是流量
public boolean isGPS(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if(info!=null&&info.getType()==ConnectivityManager.TYPE_MOBILE){
return true;
}
return false;
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* boolean available = NetWorkUtils.isNetWorkAvailable(this);
if (available) {
Toast.makeText(MainActivity.this, "网络连接成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
}*/
/*boolean wifi = NetWorkUtils.isWifi(this);
if (wifi) {
Toast.makeText(MainActivity.this, "wifi网络连接成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "wifi网络连接失败", Toast.LENGTH_SHORT).show();
}*/
boolean mobile = NetWorkUtils.isMobile(this);
if (mobile) {
Toast.makeText(MainActivity.this, "手机流量网络连接成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "手机流量网络连接失败", Toast.LENGTH_SHORT).show();
}
}
}