Cannot get current location coordinates - android

I want to get current longitude and latitude as int
So I use this code
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
....Notify
}
if (gps_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
if (network_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
locationManager.removeUpdates(this);
Unfortunately longitude and latitude are always null.
I have all permission needed in the manifest.
How can I fix this issue?

Well this is what i use for location listener
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class LocationUtils implements LocationListener{
Context context;
private String provider;
private LocationManager locationManager;
private String latitude="no value";
private String longitude="no value";
public LocationUtils(Context context) {
this.context=context;
// Get the location manager
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
latitude="no value";
longitude="no value";
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
/*Toast.makeText(context, "Provider " + provider + " has been selected.",
Toast.LENGTH_SHORT).show();*/
// System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
/*Toast.makeText(context, "Location not available",
Toast.LENGTH_SHORT).show();*/
}
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latitude = lat + "";
longitude = lng + "";
/* Toast.makeText(context, " lat: "+lat +" Long:"+lng,
Toast.LENGTH_SHORT).show(); */
}
#Override
public void onProviderDisabled(String provider) {
//Toast.makeText(context, "Disabled provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
//Toast.makeText(context, "Enabled new provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
}
Now in your activity u can get
LocationUtils appLocationManager = new LocationUtils(getContext());
String latitude = appLocationManager.getLatitude();
String longitude = appLocationManager.getLongitude();
Also add
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
in your manifest file

First check the GPS enabled in your device.
Check all the permissions included in the manifest
You are fetching the last known location using the GPS provider so remove that line and fetch the location individually for both the provider(There should be possible that your GPS is not available at that time so you did not get the location and you are fetching the last known location using the GPS so it can be null and if location will be null then it will not goes inside the conditions like if(network_enabled) and if(gps_enabled).).
In short check the Last known location of GPS if it is null then try to get the location using the Location provider and use that location.

public class SMS_Service extends Service {
private final String LOGTAG = "SMS_Service";
String latLongString;
String addressString;
double altitude;
int LAC;
int mcc = 0;
int mnc = 0;
String pn_no;
Altitude_Details ld = new Altitude_Details();
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.e(LOGTAG, "created");
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e(LOGTAG, "destroyed");
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e(LOGTAG, "started");
SmsManager sms = SmsManager.getDefault();
// get phone number from shared preference
SharedPreferences default1 = getSharedPreferences("Device",
MODE_WORLD_WRITEABLE);
pn_no = default1.getString("Phone_NO", "");
Log.e("phone_no in sms service", pn_no);
String From = intent.getStringExtra("From");
String Msg = intent.getStringExtra("Msg"); // get message from intent
Log.e("ON start:", "" + From);
Log.e("ON start:", "" + Msg);
String number = From.substring(7, 11);
Log.e("ON start: SUBSTRING", "" + number);
// check msg for Location keyword match or not
if (Msg.equals("LOCATION") && pn_no.equals(number)) {
Log.e("location:", "Location found");
TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tel.getNetworkOperator();
// find MNC and MCC
if (networkOperator != null) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
Log.e("MCC", "" + mcc);
Log.e("MNC", "" + mnc);
}
// find LAC for GSM
if (tel.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
final GsmCellLocation location = (GsmCellLocation) tel
.getCellLocation();
if (location != null) {
LAC = location.getLac();
Log.e("cell location", "LAC: " + location.getLac()
+ " CID: " + location.getCid());
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
// update method return latest location
updateWithNewLocation(location);
// location change then listner called
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
// send mcc,mnc,latitude,longitude,altitude,address,Link in message
String Url = "http://itouchmap.com/latlong.html";
sms.sendTextMessage(pn_no, null, "\nLocation:\n" + "MCC: " + mcc
+ "\nMNC: " + mnc + "\nLAC:" + LAC + latLongString
+ "\nAltitude:" + altitude + "feet"
+ "\nGo to Below site:\n" + Url, null, null);
sms.sendTextMessage(pn_no, null, "\nAddress:\n" + addressString,
null, null);
// stop service automatically
SMS_Service.this.stopSelf();
}
else {
Log.e("loation:", "Location not found");
SMS_Service.this.stopSelf();
}
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
// TODO Auto-generated method stub
addressString = "\nno address found";
// check location get or not from provider
if (location != null) {
// get latitude and longitude
double latitude = location.getLatitude();
double longitude = location.getLongitude();
latLongString = "\nLat:" + latitude + "\nLong:" + longitude;
Log.e("location", "" + latLongString);
// get altitude from method
altitude = ld.getElevationFromGoogleMaps(latitude, longitude);
Log.e("Altitude", "" + altitude);
// find address from latitude and longitude
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
}
addressString = sb.toString();
Log.e("Address", "" + addressString);
} catch (IOException e) {
}
} else {
latLongString = "\n No location found";
Log.e("location", "" + latLongString);
}
}
}
hey you can make the service and use this code to get altitude and latitude and decode this using class

Try This code
double longitude,latitude;
int lon,lat;
getcurrentloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(GpsLocationFinder.this, "Enable Your GPS", Toast.LENGTH_LONG).show();
}else{
LocationResult locationResult=new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
longitude=location.getLongitude();
latitude=location.getLatitude();
lon=(int)longitude;
lat=(int)latitude;
Toast.makeText(GpsLocationFinder.this, "Current Longitude"+longitude+" Current Latitude"+latitude,Toast.LENGTH_LONG).show();
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(GpsLocationFinder.this, locationResult);
}
}
});
And the MyLocation Class is Below
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
double longitude,latitude;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
//Log.e("GPS DISTANCE","GPS Enabled");
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
//don't start listeners if no provider is enabled
//try{
try{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 100, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 30000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}

Related

how to find location through gps on my phone

I actually wrote the below code on the onclick method of a button,but it is giving null pointer exception,plzz help
public void submit(View v)
{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double mesg1=location.getLatitude();
double mesg2=location.getLongitude();
}
http://developer.android.com/reference/android/location/LocationManager.html
You should register a listener for location updates - see requestLocationUpdates() method.
Also add ACCESS_FINE_LOCATION permission to your Manifest.
hey follows few steps to get proper and accurate current location.
This way provided you current location both by interent as well as gps.
Step 1.
Put this class in your code.
GetCurLocation.java
public class GetCurLocation implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public static LocationClient mLocationClient;
LocationRequest mLocationRequest;
public static LocationManager locationmanager;
float accuracy = 500;
Activity context;
boolean getLocRegularly = false;
int interval = 1000;
float Radius;
GoogleMap gmap;
SetOnLocationFoundListner OLF;
public interface SetOnLocationFoundListner {
public void onLocationFound(Location location, boolean getLocRegularly,
GoogleMap gmap);
}
public void RemoveUpdates() {
try {
if (mLocationClient != null)
mLocationClient.removeLocationUpdates(this);
if (locationmanager != null)
locationmanager.removeUpdates(LocUpByLocMgr);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* radius should be in meters
*/
public GetCurLocation(Activity activity, int interval,
boolean getLocRegularly, GoogleMap gmap,
SetOnLocationFoundListner OLF, float Radius) {
this.OLF = OLF;
this.gmap = gmap;
this.context = activity;
this.getLocRegularly = getLocRegularly;
this.interval = interval;
this.Radius = Radius;
if (servicesConnected()) {
mLocationClient = new LocationClient(context, this, this);
mLocationClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(interval);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(interval);
}
locationmanager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
locationmanager.requestLocationUpdates(provider, interval, 0,
LocUpByLocMgr);
}
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
(Activity) context, 0);
if (dialog != null) {
}
return false;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location location = mLocationClient.getLastLocation();
Log.e("testing",
location.getLatitude() + "," + location.getLongitude()
+ "," + location.getAccuracy());
if (location.getAccuracy() < Radius) {
OLF.onLocationFound(location, getLocRegularly, gmap);
locationmanager.removeUpdates(LocUpByLocMgr);
} else
mLocationClient.requestLocationUpdates(mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LC", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LC", location.getAccuracy() + " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient.removeLocationUpdates(this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
android.location.LocationListener LocUpByLocMgr = new android.location.LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LM", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LM", location.getAccuracy()
+ " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient
.removeLocationUpdates(GetCurLocation.this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
Step 2.
implement setonlocationfoundlistener in class where you want current location,
and declear one more method in your oncreate and after you will get one location found method and it return location and you can get location.getlatitude and location.getlongitude.
GetCurLocation gcl = new GetCurLocation(activity, 0, true, null, this,
2000);
Step 3. make permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
thats all. thanks
public void loc1(View v)
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
Toast.makeText(getApplicationContext(), "latitude",Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "longitude",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
String longitude = "0.00";
String latitude = "0.00";
}
}
}
}

How to get complete details of current location using GPS & Location Manager

I am using GPS to get longitude and latitude of a location, but now I want to get each and every detail of location like: country, city, state, zip code, street number and so on.
Maximum details of current location.
Code:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
String country;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled
(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation
(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation
(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
private void initmainIntent() {
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
if (location != null) {
Geocoder gcd = new Geocoder(getApplicationContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.size() > 0) {
String s = "Address Line: "
+ addresses.get(0).getAddressLine(0) + "\n"
+ addresses.get(0).getFeatureName() + "\n"
+ "Locality: "
+ addresses.get(0).getLocality() + "\n"
+ addresses.get(0).getPremises() + "\n"
+ "Admin Area: "
+ addresses.get(0).getAdminArea() + "\n"
+ "Country code: "
+ addresses.get(0).getCountryCode() + "\n"
+ "Country name: "
+ addresses.get(0).getCountryName() + "\n"
+ "Phone: " + addresses.get(0).getPhone()
+ "\n" + "Postbox: "
+ addresses.get(0).getPostalCode() + "\n"
+ "SubLocality: "
+ addresses.get(0).getSubLocality() + "\n"
+ "SubAdminArea: "
+ addresses.get(0).getSubAdminArea() + "\n"
+ "SubThoroughfare: "
+ addresses.get(0).getSubThoroughfare()
+ "\n" + "Thoroughfare: "
+ addresses.get(0).getThoroughfare() + "\n"
+ "URL: " + addresses.get(0).getUrl();
locationNotFound.setVisibility(View.GONE);
locationFound.setVisibility(View.VISIBLE);
foundLocationText.setText(s);
}
} catch (IOException e) {
e.printStackTrace();
}
background(location.getLatitude(), location.getLongitude());
}
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
}
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
public boolean getLocation(Context context, LocationResult result) {
// I use LocationResult callback class to pass location value from
// MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
if (location != null) {
System.out.println(location.getLatitude());
}
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Here is the Tutorial to Get Current location and City name using GPS
Once you get GPS co-ordinates
By using Geocoder class you can every details
See below code snip is for getting Current City Same way you can go for other details also.
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed : Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: "
+ cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Update (as per comment)
If you want to send this details to any contact via SMS.
I would say this page may help you
Using this code you can find the address like street, State, Country and Pin.
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
String address = "";
if (addresses != null && addresses.size() >= 0) {
address = addresses.get(0).getAddressLine(0);
if (addresses != null && addresses.size() >= 1) {
address += ", " + addresses.get(0).getAddressLine(1);
}
if (addresses != null && addresses.size() >= 2) {
address += ", " + addresses.get(0).getAddressLine(2);
}
}
And you need to run this code in separate thread or in AsyncTask because it will internally call the network connection.
I somehow spent many hours to complete this task. In the below code the onMapReady device location is detected and shows a marker at that location. On click on the marker the location address is shown.
public class StoreFinder extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private static final int Request_User_Location_Code = 99;
private double latitude;
double longitude;
private int ProximityRadius = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkUserLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if (googleApiClient == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else
{
Toast.makeText(this, "Permission Denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
lastLocation = location;
if (currentUserLocationMarker != null)
{
currentUserLocationMarker.remove();
}
/*----------to get City-Name from coordinates ------------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(latitude, latitude, 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getAddressLine(0);
} catch (IOException e) {
e.printStackTrace();
}
String s = cityName;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(s);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(16));
if (googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (LocationListener) this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

How to use locationManager?

I try to add a location from the GPS but i always get null. Can you please help and show me what I did wrong?
I would like to always receive the location in onCreate. If no location is received
"No provider received" appears instead of the location. The problem is i always get the message.
//Location variables
private TextView gps;
private LocationManager locationManager;
private String locationProvider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_draw);
initializeData();
}
private void initializeData()
{
gps = (TextView) findViewById(R.id.GPS);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationProvider = locationManager.getBestProvider(new Criteria(), true);
if(locationProvider!=null)
{
gps.setText("Upload image location: "+ locationProvider);
}
else
{
gps.setText("Upload image location: No provider Found" );
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
private void showLocation(Location location)
{
if(location==null)
gps.append("\nUnknown location");
else
{
double lat = location.getLatitude();
double lng = location.getLongitude();
gps.append("\n\nLocation lat: " +lat+
", long: " + lng+"\n"
+ getAddress(lat, lng));
}
}
public void onLocationChanged(Location location) {
showLocation(location);
}
public void onProviderDisabled(String provider) {
gps.append("\nProvider Disabled: " +provider);
}
public void onProviderEnabled(String provider) {
gps.append("\nProvider Enabled: " +provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
gps.append("\nProvider Status Changed: " + provider+ ",status: "+
status);
}
public String getAddress(double lat, double lng)
{
Geocoder geocoder = new Geocoder(this);
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String str = obj.getCountryName();
str+="\n" + obj.getCountryCode();
str+="\n" + obj.getLocality(); //current city
str+="\n" + obj.getAddressLine(0);
return str;
}
catch (IOException e) {
return "Error: " +e.getMessage();
}
}
1)You need to request updates from provider:
newLocation = requestUpdatesFromProvider(
LocationManager.GPS_PROVIDER, "error string");
2)Register a Listener:
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Do something
} );}

Getting latitude and longitude by GPS

I am trying to fetch GPS latitude and longitude on a mobile device. My code below works -- i.e. it provides all the information in the desired manner -- when the device's "use wireless networks" setting is selected, but not when "use GPS satellites" is selected, in which case I don't get any information.
Here's the code:
void getLatitudeAndLongitude() {
boolean gpsEnabled = false;
LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.e("mLocation#####", "" + mLocMan);
try {
gpsEnabled = mLocMan
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
boolean networkEnabled = false;
try {
networkEnabled = mLocMan
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
Location mCurrentLocation = null;
// network*****************
if (networkEnabled)
mCurrentLocation = mLocMan
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// gps********************
if (gpsEnabled)
mCurrentLocation = mLocMan
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d("current location", "" + mCurrentLocation);
LocationProvider mGpsProv = null;
if (mGpsProv == null && mLocMan != null) {
mGpsProv = mLocMan.getProvider(LocationManager.GPS_PROVIDER);
}
if (mLocMan != null) {
mylocationlistener mGpsLocListener = new mylocationlistener();
mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0 /* minTime ms */, 0 /* minDistance in meters */,
mGpsLocListener);
Log.d("Provoider1", "NETWORK_PROVIDER");
}
if (mLocMan != null && mGpsProv != null) {
mylocationlistener mGpsLocListener = new mylocationlistener();
mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0 /* minTime ms /, 0 / minDistance in meters */, 0,
mGpsLocListener);
Log.d("Provoider2", "GPS_PROVIDER");
}
}
class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
Log.e("location==", "" + location);
Log.e("getLatitude", location.getLatitude() + "");
Log.e("getLongitude", location.getLongitude() + "");
if (GlobalConfig.DEBUG)
Log.d("setUpIndividualWork", "location==" + location);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 1000);
onGPSUpdate(location);
Geocoder gcd = new Geocoder(setUpIndividualWorkOut.this,
Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
userCurrentLocation = addresses.get(0).getLocality();
Log.e("current location by GPS ", ""
+ addresses.get(0).getLocality());
}
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
I will be very thankful for your response.
I use it like this:
The class LocationHelper:
public class LocationManagerHelper {
private static final String TAG = LocationManagerHelper.class.getSimpleName();
private Context mContext;
private LocationManager mLocationManager;
private GeoUpdateHandler mLocationListener = new GeoUpdateHandler();
public LocationManagerHelper(Context context) {
this.mContext = context;
}
public GeoUpdateHandler GetLocationListener() {
return mLocationListener;
}
public void SetLocationManager(LocationManager locationManager) {
mLocationManager = locationManager;
}
public LocationManager GetLocationManager() {
return mLocationManager;
}
public void Stop() {
if (mLocationManager != null) {
mLocationManager.removeUpdates(mLocationListener);
}
}
private class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
}
//The using:
private LocationManagerHelper mLocationManagerHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InitializeComponent(getArguments());
mLocationManagerHelper = new LocationManagerHelper(getActivity());
try {
Criteria criteria = new Criteria();
mLocationManagerHelper.SetLocationManager((LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE));
mLocationManagerHelper.GetLocationManager().requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, mLocationManagerHelper.GetLocationListener());
String provider = mLocationManagerHelper.GetLocationManager().getBestProvider(criteria, false);
Location location = mLocationManagerHelper.GetLocationManager().getLastKnownLocation(provider);
if (location != null) {
mLongitude = location.getLongitude();
mLatitude = location.getLatitude();
}
} catch (Exception ex) {
Log.e(TAG, "GPS", ex);
}
}
try this...
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener lmh = new MyLocationListener();
String mlocProvider;
Criteria hdCrit = new Criteria();
hdCrit.setAccuracy(Criteria.ACCURACY_COARSE);
mlocProvider = locationManager.getBestProvider(hdCrit, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1000, lmh);
Location currentLocation = locationManager.getLastKnownLocation(mlocProvider);
double currentLatitude = currentLocation.getLatitude();
double currentLongitude = currentLocation.getLongitude();
Log.e("lat",""+currentLatitude);
Log.e("lng",""+currentLongitude);
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is:" +
"Latitud = "+ loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}/* End of Class MyLocati
Try this:
package loca.loca;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class LocationActivity extends Activity {
double x,y;
Timer timer;
LocationManager lm;
boolean gps_enabled = false;
boolean network_enabled = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gps_enabled && !network_enabled) { Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "nothing is enabled", duration);
toast.show();
}
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer=new Timer();
timer.schedule(new GetLastLocation(), 20000);
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer.cancel();
x =location.getLatitude();
y = location.getLongitude();
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "gps enabled "+x + "\n" + y, duration);
toast.show();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer.cancel();
x = location.getLatitude();
y = location.getLongitude();
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "network enabled"+x + "\n" + y, duration);
toast.show();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
{x = gps_loc.getLatitude();
y = gps_loc.getLongitude();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration);
toast.show();
}
else
{x = net_loc.getLatitude();
y = net_loc.getLongitude();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "network lastknown "+x + "\n" + y, duration);
toast.show();
}
}
if(gps_loc!=null){
{x = gps_loc.getLatitude();
y = gps_loc.getLongitude();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration);
toast.show();
}
}
if(net_loc!=null){
{x = net_loc.getLatitude();
y = net_loc.getLongitude();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "network lastknown "+x + "\n" + y, duration);
toast.show();
}
}
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "no last know avilable", duration);
toast.show();
}
}}

location problem

Hi to all im new to android and i have a small problem and i would really appreciate if someone can help me
first im trying to show all available location providers and its not working and 2nd when ever i run the it i don't get any location information from the best available provider (i have my wifi and network providers on)
thanks in advance
package com.paad.whereami;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class WhereAmI extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
boolean enabledOnly = true;
List<String> providers = locationManager.getProviders(enabledOnly);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setSpeedRequired(true);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 1,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "No address found";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {}
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString + "\n" + addressString);
}
}
I had also same problem before, after searching a lot...came to solution and makes it possibale to get instant location of device through following code...actuallu we can not have gps responce instantly so we can have our location on the basis of cell-tower or wifi. so enable one of them to get instant location of your device..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leopard_screen);
FindLocation(this);
}
public void FindLocation(Context context) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (network_enabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
Log.i("########## Network provider is enabled", "Network Provider");
} else {
Toast.makeText(LeopardScreen.this,
"Network provider is not enabled", 2000);
}
if (gps_enabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListenerGPS);
Log.i("########## GPS provider is enabled", "GPS Provider");
} else {
Toast.makeText(LeopardScreen.this, "GPS provider is not enabled",
2000);
}
if(!network_enabled && !gps_enabled) {
currentLocation = getMyLastKnownLocation();
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
Log.i("######## Both location provider disabled",
"getMylastKnownLocation = "+String.valueOf(currentLatitude)
+ " : " + String.valueOf(currentLongitude));
Toast.makeText(LeopardScreen.this,"LastKnownLocation\n"+String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 3000).show();
Intent intent = new Intent(LeopardScreen.this, mainActivity.class);
startActivity(intent);
}
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
handler.removeCallbacks(runnable);
Log.i("######## Inside FindLocation", "Inside FindLocation");
Toast.makeText(
LeopardScreen.this,"Network Location \n"+
String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
LocationListener locationListenerGPS = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateLocation(location);
Log.i("########## Inside onLocationChangedGPS", String
.valueOf(currentLatitude)
+ " : " + String.valueOf(currentLongitude));
Toast.makeText(
LeopardScreen.this,
"GPS Location \n" + String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
public Location getMyLastKnownLocation () {
Location locNetwrok = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location locGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(locNetwrok != null)
return locNetwrok;
else if(locGPS != null)
return locGPS;
return null;
}
void updateLocation(Location location) {
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
Log.i("######## Inside LeopardScreen locationChanged",
"locationChanged");
}
Don't Forgot to add in Menifeast
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>

Categories

Resources