Android - NetworkInfo对象的isConnected()与isAvailable()

写Android应用需要检测网络状态,发现有两个方法差不多,不知道如何区别
查了一下资料得出以下结论:

总结有以下5种状态:

在WLAN设置界面

1,显示连接已保存,但标题栏没有,即没有实质连接上,输出为:not connect, available

2,显示连接已保存,标题栏也有已连接上的图标, 输出为:connect, available

3,选择不保存后 输出为:not connect, available

4,选择连接,在正在获取IP地址时 输出为:not connect, not available

5,连接上后 输出为:connect, available

测试代码:

public class MainActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.registerReceiver(mBroadcastReceiver, new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION));
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            Bundle bundle = intent.getExtras();
            NetworkInfo aNetworkInfo = (NetworkInfo) bundle
                    .get(ConnectivityManager.EXTRA_NETWORK_INFO);

            if (aNetworkInfo.isConnected())
            {
                System.out.println("connecte");
            } else
            {
                System.out.println("not connect");
            }

            if (aNetworkInfo.isAvailable())
            {
                System.out.println("available");
            } else
            {
                System.out.println("not available");
            }
            System.out.println("--------------------");
        }
    };
}

你可能感兴趣的:(Android)