Thursday, December 26, 2013

Check Network and GPS connectivity in Android

////////////For network connectivity

public class Util {
public static boolean isNetworkAvailable(Activity activity) {
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}

}
//////////////////////////////////////////////
//For GPS Connectivity

public class GPSLocation implements LocationListener {
double lat, lng;
LocationManager locationManager;
public Location location = null;
Context contxt;
private String provider;
public boolean isavailable, isgps;

public GPSLocation(Context mcontext) {
this.contxt = mcontext;
locationManager = (LocationManager) contxt
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
isgps = false;
} else {
isgps = true;
}

}

public double getLatitudeGPS() {
return location.getLatitude();
}

public double getLongitudeGPS() {
return location.getLongitude();
}



public void onLocationChanged(Location arg0) {
if (arg0 != null) {

lat = (arg0.getLatitude());
lng = (arg0.getLongitude());
isavailable = true;
} else {
isavailable = false;
}
}

public void onProviderDisabled(String arg0) {

}

public void onProviderEnabled(String provider) {

}

public void onStatusChanged(String provider, int status, Bundle extras) {

}

}
///////////////////////////////////////////////////////////////////////////////////

/////In your class check

if (Util.isNetworkAvailable(HomeActivity.this)) {
if (!gps.isgps) {
myAlert("Please enable GPS for better performance of this application.");
}
try{
startService(new Intent(this, DownloadDataService.class));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateWithNewLocation(location);

}catch (Exception e) {
e.printStackTrace();
}


//////////////////Find your city

public void updateWithNewLocation(Location location) {
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
try {
Geocoder gcd = new Geocoder(HomeActivity.this,
Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) {

current_city = addresses.get(0).getLocality();
Toast.makeText(getApplicationContext(), current_city,
Toast.LENGTH_LONG).show();

}
} catch (Exception e) {

}

No comments:

Post a Comment