Pages

Ads 468x60px

Monday, August 19, 2013

Android: Verify Device Internet Connection


This code verifies either device is connected to network or not.


// Verify Network Connection
protected boolean isNetworkConnected(Activity context) {
boolean connectedWifi = false; // connected to WiFi
   boolean connectedMobile = false; // connected to Mobile

   ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo[] netInfo = connectivityManager.getAllNetworkInfo();
   for (NetworkInfo ni : netInfo) {
       if (ni.getTypeName().equalsIgnoreCase("WIFI"))
           if (ni.isConnected())
            connectedWifi = true;
       if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
           if (ni.isConnected())
            connectedMobile = true;
   }
   return connectedWifi || connectedMobile;
}

Android: Show Alert Dialog to enable GPS



This code will show alert dialog to enable GPS on the device.


// Show Alert Dialog to enable GPS
protected void showGPSAlert(final Context context) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder
.setMessage(
"GPS is disabled on your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Open Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// set intent to open settings
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}