0

Possible Duplicate:
Android detect if device has internet connection

I have one program that I allow only android user that has internet connected can access, other user that don't have internet connection alert them to connect to the internet, if not connect problem will exit.

My main activity code is bellow. I want if mobile user has internet connected will show Main Layout, but if not connected alert user to connect Internet first.

How can i do it? Please help me.

My Main Activity:

public class MainSong extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


  //My Profile
    Button myProfile = (Button) findViewById(R.id.myprofile);


    myProfile.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent();
            i.setClassName("aaa.bbb.ccc", "aaa.bbb.ccc.myprofile");
            startActivity(i); }
    });

  //My Songs
    Button mySong = (Button) findViewById(R.id.mysongs);
    mySong.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent();
            i.setClassName("aaa.bbb.ccc", "aaa.bbb.ccc.mysong");
            startActivity(i); }
    });

    //bar album
    Button album = (Button) findViewById(R.id.myalbum);
    album.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent();
            i.setClassName("aaa.bbb.ccc", "aaa.bbb.ccc.myalbum");
            startActivity(i); }
    });

    //bar video
    Button video = (Button) findViewById(R.id.myvideo);
    video.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent();
            i.setClassName("aaa.bbb.ccc", "aaa.bbb.ccc.myvideo");
            startActivity(i); }
    });
}
}

I appreciate for your help.

Community
  • 1
  • 1
SopheakVirak
  • 941
  • 5
  • 13
  • 35

4 Answers4

1

You can check if user is connected to internet or not by using ConnectivityManager as:

public boolean checkNetworkStatus() {

    final ConnectivityManager connMgr = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isAvailable()) {
     if (wifiInfo.getState() == NetworkInfo.State.CONNECTED)
      {
        Toast.makeText(this, "Wifi connection.", Toast.LENGTH_LONG).show();
        return true;
      }
      else
      {
        Toast.makeText(this, "No Connect using wifi connection.", Toast.LENGTH_LONG).show();
        return false;
      }
    } else if (mobile.isAvailable()) {
      if (mobile.getState() == NetworkInfo.State.CONNECTED)
      {
        Toast.makeText(this, "Connected using GPRS connection.", Toast.LENGTH_LONG).show();
        return true;
      }
      else
      {
        Toast.makeText(this, "No Connect using GPRS connection.", Toast.LENGTH_LONG).show();
        return false;
      }

    } else {
        Toast.makeText(this, "No network connection.", Toast.LENGTH_LONG).show();
        return false;
    }       

}

AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
ρяσѕρєя K
  • 127,886
  • 50
  • 184
  • 206
1
//To check whether network connection is available on device or not
public static boolean checkInternetConnection(Context _activity) {
        ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()) 
            return true;
        else
            return false;
    }//checkInternetConnection()

AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Shankar Agarwal
  • 39,320
  • 8
  • 68
  • 66
  • Agarwal, I added your code it's not appear any error but after compile it with no internet connection still I can go to my application as normal. – SopheakVirak May 22 '12 at 03:34
  • you must call this function every time you need net connection and check whehter it returns true or not. if it returns true then net connetion is available and you can proceed else if it returns false then you must show an alert dialog with your message to the user – Shankar Agarwal May 22 '12 at 07:31
1

Here's the code I use in my Android app:

            CharSequence network_fail = "This application requires that you are connected to the Internet.";
            int duration = Toast.LENGTH_SHORT;
            boolean isAvailable = false;

            // Check availability of network connection
            try
            {
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                if(cm == null)
                    isAvailable = false;
                else
                    isAvailable = cm.getActiveNetworkInfo().isAvailable();
            }
            catch(Exception e){}

Put your Internet-reliant code inside this if:

            // Check if user is connected to the Internet, and show an error if they are not.
            if(isAvailable && (isAirplaneModeOn(context) == false))
            {
              // Internet-reliant code
            }
            else
            {
                Toast fail = Toast.makeText(context, network_fail, duration);
                fail.show();
            }

You also need the obligatory <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> in your AndroidManifest.xml file with my code as well.

Alex W
  • 33,401
  • 9
  • 92
  • 97
  • Dear Alex W, can you explain me clear than this? because i don't how to add your code in my Main Activity? – SopheakVirak May 22 '12 at 03:33
  • In my app, I have all of the above code, in the order in which it appears, inside an onClickListener for a button. Example: Button imgButton = (Button)findViewById(R.id.buttonImg); imgButton.setOnClickListener(new OnClickListener(){public void onClick(View arg0){ // PUT CODE HERE }}); ... put that in your main activity and change it to be relevant to a button that you have in your layout – Alex W May 22 '12 at 03:52
0

You should make an BroadcastReceiver that will be triggered when the connectivity status has changed :

     public class BroadCastSampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.registerReceiver(this.mConnReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            if(currentNetworkInfo.isConnected()){
                Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
            }
        }
    };
}

and then in your AndroidManifest you can check if you have connectivity:

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

For reference here here source

Parag Chauhan
  • 33,908
  • 13
  • 83
  • 95