网络连接管理ConnectivityManager

 public static int getNetType(Context context) {
        int mState = -1;// 代表无网络
        //网络连接管理类
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //NetworkInfo是 网络状态类;
        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return  mState;
        }
        //获取网络类型
        int type = networkInfo.getType();
        if (type == ConnectivityManager.TYPE_WIFI) { //wifi网络
            mState = 1;
            return mState;
        }else if(type == ConnectivityManager.TYPE_MOBILE){ //手机网络
            mState = 0;
            return mState;

        }


        return mState;
    }

在主线程被调用

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        int netType = NetStateUtil.getNetType(MainActivity.this);

        if (netType != -1) {
            initdata();
        }else {
            Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
        }
        

    }

    private void initdata() {

        Toast.makeText(this, "我有网络哈哈哈哈", Toast.LENGTH_SHORT).show();
    }
}

你可能感兴趣的:(咨询)