网络状态判断

package com.wzq.wifidemo;


import android.app.AlertDialog;
import android.os.Bundle;


public class MainActivity extends BaseActivity {


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


        initData();






    }


    private void initData() {
        int netType = getNetType();
        if (netType == -1) {
        //无网络
            AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        // 跳转到设置页面;


            return;
        }
        // new AsyncTask().execute("xxxxxxxx");


    }


}


package com.wzq.wifidemo;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


/**
 * author:Created by WangZhiQiang on 2017-09-05.
 */


public class Utils {


    /**
     * 返回值 -1:没有网络  1:WIFI网络   2:net网络
     */
    public static int getNetype(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();


        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 2;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }
}



package com.wzq.wifidemo;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;


/**
 * author:Created by WangZhiQiang on 2017-10-17.
 * 可以封装一些变量, 方法等等
 */


public abstract class BaseActivity extends AppCompatActivity {




    Context context = BaseActivity.this;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);


    }


    /**
     *
     * @return -1-->代表无网络,  1-->代表wifi,  2-->mobile手机网络
     */
    public int getNetType(){
        int mType = -1;
        //获取系统的连接管理类;
        ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        //NetworkInfo里面封装的联网类型;
        NetworkInfo networkInfo = conManager.getNetworkInfo(conManager.getActiveNetwork());
        //type是底层封装好的网络类型
        int type = networkInfo.getType();


        if (type == conManager.TYPE_WIFI) {
            mType = 1;
        }else if(type == conManager.TYPE_MOBILE){
            mType = 2;
        }else {
            mType = -1;
        }


        return mType;
    }










}

你可能感兴趣的:(网络状态判断)