android 判断网络状态

首先需要添加权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


代码:

package com.test;


import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;


public class NetStateActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        if(isConnectedInternet()){
        Toast.makeText(NetStateActivity.this, "Connected", Toast.LENGTH_SHORT).show();
        } else {
        Toast.makeText(NetStateActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
        }
    }
    
    private boolean isConnectedInternet(){
    ConnectivityManager conManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
    if(networkInfo != null){
    return networkInfo.isAvailable();
    }
    return false;
    }
}

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