判断网络状态(移动、WiFi、无网络连接)

首先是用到了一个工具类NetWorkUtil;
工具类代码:


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

public class NetWorkUtil {

    public static int netWorkState;
    /**
     * 判断当前手机是否有网络
     * @return
     */
    public static int hasNetWork(Context context) {
        /*
         * 0 没有网络 1 移动网络 2 WIFI
         */
        // 链接管理器
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        // 获取激活的网络信息 // 需要权限
        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();

        if (activeNetworkInfo == null) {
            netWorkState = 0;// 没有网络
        } else {
            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                netWorkState = 1;
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                netWorkState = 2;
            }
        }
        return netWorkState;
    }

}

然后在代码里面判断:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
            if (NetWorkUtil.hasNetWork(getApplicationContext()) == 0) {
            Toast.makeText(getApplicationContext(), "没有网络",
                    Toast.LENGTH_SHORT).show();

        } else if (NetWorkUtil.hasNetWork(getApplicationContext()) == 1) {
            Toast.makeText(getApplicationContext(), "移动网络",
                    Toast.LENGTH_SHORT).show();

        } else {
            Toast.makeText(getApplicationContext(), "WIFI",
                    Toast.LENGTH_SHORT).show();

        }

    }

想要实现在不同网络状态下实现的不同的效果,直接将不同网络状态下面的Toast替换掉就行了,比较懒,Demo就不奉上了,有时间的话再把demo加上去

你可能感兴趣的:(Android开发)