简体   繁体   中英

checking network connection android

Heres my code for checking the network connection of my app.I want my app run only when it is connected to a network and closes it if not. The code was running with no errors but the problem is the alertdialog show many times.

private void checkConnectivity(){

      final Thread checkConnection = new Thread(new Runnable(){
            @Override
            public void run()
            {

                while (checkCon == true){
                if(!isNetworkAvailable(MainActivity.this)) {

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            new AlertDialog.Builder(MainActivity.this)
                            .setMessage("No network connection.")   
                            .setCancelable(false)
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface d, int which) {                                 
                                    checkCon = false;
                                    finish();

                                }
                             }).show();                                                         


                        }
                    });                         
                    } else {
                        checkCon = true;
                    }

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                }}
        });
        checkConnection.start();


  }

Answer by harism, thanks

  private void checkConnectivity(){

      final Thread checkConnection = new Thread(new Runnable(){
            @Override
            public void run()
            {

                while (checkCon == true){
                if(!isNetworkAvailable(MainActivity.this)) {

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            new AlertDialog.Builder(MainActivity.this)
                            .setMessage("No network connection.")   
                            .setCancelable(false)
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface d, int which) {                                 

                                    finish();                                       
                                }

                             }).show(); 
                             checkCon = false;
                        }
                    });                         
                    } else {
                        checkCon = true;
                    }

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                }}
        });
        checkConnection.start();


  }

Add a new method inside your current Activity or Fragment :

private boolean isNetworkAvailable(){
        boolean available = false;
        /** Getting the system's connectivity service */
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        /** Getting active network interface  to get the network's status */
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if(networkInfo !=null && networkInfo.isAvailable())
            available = true;

        /** Returning the status of the network */
        return available;
    }

And here is how to use it. You can use it inside onCreate() method:

if (isNetworkAvailable() == true){ // if network is available
   // do your thing here
   ...
}else{ // "else" means that the network is not available
   // do your thing here
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM