Search code examples
androidwifigprs

how can i check net connection in android?


i have developed one application in that i have to check whether net is connected or not i use following code but its not working. can any one resolve my problem. my code is

public class AbcActivity extends Activity {
    Button b;
    private static final String tag = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                netCheckin();
            }
        });
    }
        private void netCheckin() {

            try {

                ConnectivityManager nInfo = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                nInfo.getActiveNetworkInfo().isConnectedOrConnecting();

                Log.d(tag, "Net avail:"
                        + nInfo.getActiveNetworkInfo().isConnectedOrConnecting());

                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                   Toast.makeText(getApplicationContext(), "net on", Toast.LENGTH_LONG).show();
                    Log.d(tag, "Network available:true");

                } else {
                     Toast.makeText(getApplicationContext(), "net OFF", Toast.LENGTH_LONG).show();
                    Log.d(tag, "Network available:false");

                }

            } catch (Exception e) {
               Log.e("error",""+e);
            }
        }

    }

i have give the android:name="android.permission.ACCESS_NETWORK_STATE"/> in my manifest file in above code my problem is when net is enable or disable it gives same output as "net on" (toast message).


Solution

  • At the top of your onCreate method , use

    if(!checkInternetConnection()){
                // network connnectivity error , show some dialog here and exit from the app 
    
            }
    

    where

    private boolean checkInternetConnection() {
    
                ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                // ARE WE CONNECTED TO THE NET
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) {
    
                    return true;
    
                } else {
                    Log.v("", "Internet Connection Not Present");
                    return false;
                }
            }
    

    Hope this wil help you.