Check internet connection in android (not network connection)

前端 未结 7 913
孤城傲影
孤城傲影 2020-12-20 03:44

I have a problem with checking internet connection in android at runtime. I use some different methods to check internet connection but i don\'t know which one is better . b

7条回答
  •  一向
    一向 (楼主)
    2020-12-20 03:59

    You can use below code to check whether network connection is available or not.

    public class NetworkConnection {
        public Context context;
    
        public NetworkConnection(Context applicationContext) {
            this.context=applicationContext;
        }
    
        public boolean isOnline() {
            ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                return true;
            }
            return false;
        }
    }
    

    public class MainActivity extends AppCompatActivity {
        NetworkConnection nt_check;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            nt_check=new NetworkConnection(context);
            if(nt_check.isOnline()) {
                // do logic
            } else {
                // show message network is not available.
            }
        }
    }
    

提交回复
热议问题