android 判断当前网络是否可用

判断是否有可用的网络实现代码:

package com.example.isnetworkdemo;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Context context = MainActivity.this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //判断是否有可用的网络
        if(isNetworkVilible(context)){
             Toast.makeText(getApplicationContext(), "当前有可用网络!", Toast.LENGTH_LONG).show();
        }else{
             Toast.makeText(getApplicationContext(), "当前无可用网络!", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 检查当前网络是否可用
     * @param context
     * @return
     */
    public boolean isNetworkVilible(Context context) {
        // 获取手机ConnectivityManager连接管理对象
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            //获取当前正在使用网络
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }
}
 运行结果:

android 判断当前网络是否可用_第1张图片

android 判断当前网络是否可用_第2张图片

你可能感兴趣的:(android)