How to get longitude and latitude by GPS in Android? - android

I can get longitude and latitude by network provider, but unable to get it by GPS. How can I do that?
public void onCreate(Bundle savedInstanceState) {
...
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (mLocation != null) {
gp1 = getGeoByLocation(mLocation);
gp2 = gp1;
refreshMapView();
if( !mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000,
10, mLocationListener);
}else{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000,
10, mLocationListener);
}
private GeoPoint getGeoByLocation(Location location) {
GeoPoint gp = null;
try {
if (location != null) {
double geoLatitude = location.getLatitude() * 1E6;
double geoLongitude = location.getLongitude() * 1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}

Get lat long using GPS in every 10 min.
// Des: Start Device's GPS and get current latitude and longitude
public void GPS() throws IOException {
// Des: This is a background service and called after every 10 minutes and fetch latitude-longitude values
background = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < j; i++) {
if (ProjectStaticVariable.GPSExit == true ) {
try {
Thread.sleep(600000); //10 minutes
mainhandler.sendMessage(mainhandler.obtainMessage());
j++;
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
});
background.start();
mainhandler = new Handler() {
public void handleMessage(Message msg) {
// Check Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
lat_long_Service_flag = true;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener(getApplicationContext());
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, mlocListener);
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
}
};
}
// Des: Location Listener through which we get current latitude and longitude
public class MyLocationListener implements LocationListener {
public MyLocationListener(Context mContext) {}
public MyLocationListener(Runnable runnable) {}
#Override
public void onLocationChanged(Location loc) {
longitude = loc.getLongitude();
latitude = loc.getLatitude();
final_latitude = Double.toString(latitude);
final_longitude = Double.toString(longitude);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

Related

android - can't get gps coordinate

I want to get user coordinate, the gps is on , I've asked for permission it has the permissions.
the location is set , I've my locations on other apps like google map but in my application , it doesn't work :
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
LocationManager mlocManager = null;
LocationListener mlocListener;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
startService();
}
public class FetchCordinates extends AsyncTask<String, Integer, String> {
AlertDialog.Builder a;
AlertDialog dialog;
public double lati = 0.0;
public double longi = 0.0;
public LocationManager mLocationManager;
public FetchCordinates.VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new FetchCordinates.VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
a = new AlertDialog.Builder(Admins.this);
a.setMessage("در حال به دست آوردن موقعیت جغرافیایی...");
a.setPositiveButton(("بیخیال"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
FetchCordinates.this.cancel(true);
}
});
dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
Log.v("this","got the location");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0 && !isCancelled()) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
it shows me the dialog for getting the location but it never get the current location .
What's wrong with my code ?
Please provide what you wrote in your Manifest.xml file. Maybe there is something wrong with the permissions.
You need
android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION
for API 5.0 or higher also:
android.hardware.location.gps

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";
}
}
}
}

Can't Get Location using LocationManager in Background Service

I have created an application that stores your location in database at periodic time in Background service but, it doesn't get location. my code is...
public class LocationService extends Service {
private Double myLat, myLong;
private Location location;
private LocationManager locManager;
private LocationListener locationListener;
private boolean NETWORK_ENABLED, GPS_ENABLED, PASSIVE_ENABLED;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
myLat = 0.00;
myLong = 0.00;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LocationService.this.location = location;
LocationService.this.myLat = location.getLatitude();
LocationService.this.myLong = location.getLongitude();
Toast.makeText(getApplicationContext(), "onLocationChanged", Toast.LENGTH_LONG).show();
insertToDatabase();
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
getMyCurrentLocation();
}
private void getMyCurrentLocation() {
location = null;
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
NETWORK_ENABLED = false; GPS_ENABLED = false; PASSIVE_ENABLED = false;
NETWORK_ENABLED = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (NETWORK_ENABLED) {
Toast.makeText(getApplicationContext(), "Network Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 45 * 1000l, 1f, locationListener);
}
if (location == null) {
//setGPSOn();
GPS_ENABLED = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(GPS_ENABLED) {
Toast.makeText(getApplicationContext(), "GPS Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0l, 1f, locationListener);
}
//setGPSOff();
}
if (location == null) {
PASSIVE_ENABLED = locManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
if(PASSIVE_ENABLED) {
Toast.makeText(getApplicationContext(), "Passive Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0l, 1f, locationListener);
}
}
try {
location = locManager.getLastKnownLocation(locManager.getBestProvider(new Criteria(), true));
} catch(NullPointerException e) {}
if (location != null) {
myLat = location.getLatitude();
myLong = location.getLongitude();
insertToDatabase();
} else {
Location loc = null;
try {
loc = getLastKnownLocation(this);
} catch(NullPointerException e) {}
if (loc != null) {
myLat = loc.getLatitude();
myLong = loc.getLongitude();
insertToDatabase();
}
}
locManager.removeUpdates(locationListener);
}
private Location getLastKnownLocation(Context context) {
Location location = null;
LocationManager locationmanager = (LocationManager)context.getSystemService("location");
List<?> list = locationmanager.getAllProviders();
boolean i = false;
Iterator<?> iterator = list.iterator();
do {
if(!iterator.hasNext())
break;
String s = (String)iterator.next();
if(i != false && !locationmanager.isProviderEnabled(s))
continue;
Location location1 = locationmanager.getLastKnownLocation(s);
if(location1 == null)
continue;
else {
float f = location.getAccuracy();
float f1 = location1.getAccuracy();
if(f >= f1) {
long l = location1.getTime();
long l1 = location.getTime();
if(l - l1 <= 600000L)
continue;
}
}
location = location1;
i = locationmanager.isProviderEnabled(s);
} while (true);
return location;
}
}
this doesn't give me any location.... and my app is also doesn't Crash or gives any Exception.
I have properly register all permissions in Manifest file...
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
I can't find what to do?
any help will be appreciated
thanks in advance for Help...
I think your problem is that you remove the listener right away:
locManager.removeUpdates(locationListener); // comment this one out
in getMyCurrentLocation();
You should try to remove your listener in some other places.

set Timeout for GPS listening

I'm able to get location update from network provider but when it comes to gps it takes a lot of time for the data to be picked. I want to keep a particular time for which only the GPS listener will work and then move on to network provider after sometime. How to fix this issue ?
This is my code..
public void gpslocation()
{
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
updateLocationForGeo(location);
//update(location);
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
System.out.println(provider+ "enabled provider");
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println(provider+ "disabled provider");
networklocation();
}
};
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, 10 * 1000, (float) 10.0,locationListener);
}
public void networklocation()
{
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
updateLocationForGeo(location);
//update(location);
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
System.out.println(provider+ "enabled provider");
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println(provider+ "disabled provider");
isGpsProvidersDisabled=true;
}
};
String timeProvider = LocationManager.NETWORK_PROVIDER;
locationManager.requestLocationUpdates(timeProvider, 1 * 1000, (float) 10.0, locationListener);
}
public void updateLocationForGeo(Location location){
System.out.println("location updated");
double dev_lat = location.getLatitude();
double dev_lang = location.getLongitude();
boolean out_of_range=false;
for(int i=0; i<arrayLength; i++){
double lattDiff = Math.toRadians(latarr[i]-dev_lat);
double longDiff = Math.toRadians(lonarr[i]-dev_lang);
double distance=(Math.sin(lattDiff/2)*Math.sin(lattDiff/2))+(Math.sin(longDiff/2)*Math.sin(longDiff/2)*Math.cos( Math.toRadians(latarr[i]))*Math.cos( Math.toRadians(dev_lat)));
System.out.println(distance+" distance" );
double c= (2 * Math.atan2(Math.sqrt(distance), Math.sqrt(1-distance)));
double radius=radarr[i]* 1.60934;
double d = 6371 * c;
if(d>radius)
{
out_of_range=true;
continue;
}
else{
System.out.println("enjoy");
out_of_range=false;
break;
}
}
Any help would be greatly appreciated.
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);
public class MyLocationListener implements LocationListener {
private Address mAddresses;
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
Geocoder gcd = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
mAddresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e) {
}
String cityName = (mAddresses != null) ? mAddresses.get(0)
.getLocality() : TimeZone.getDefault().getID();
String countryName = (mAddresses != null) ? mAddresses.get(0)
.getCountryName() : Locale.getDefault().getDisplayCountry()
.toString();
mCurrentSpeed.setText("Longitude"+loc.getLongitude()+" Latitude"+loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

Why current location of android phone don't change when i change location?

I get location of android phone as:
android.location.Location locationA;
LocationManager locationManager;
Criteria cri = new Criteria();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String tower = locationManager.getBestProvider(cri, false);
locationA = locationManager.getLastKnownLocation(tower);
if (locationA != null) {
// lat = (double) (locationA.getLatitude() * 1E6);
// longi = (double) (locationA.getLongitude() * 1E6);
double lat = locationA.getLatitude();
double longi = locationA.getLongitude();
TextView txt = (TextView) findViewById(R.id.textView1);
String td = String.valueOf(lat) + "," + String.valueOf(longi);
txt.setText(td);
}
Why current location of android phone don't change when i change location and get again current location?
check the time of your location using locationA.getTime(). if it was not up to date wait for a new location and then stop.
private static Location currentLocation;
private static Location prevLocation;
public void yourMethod()
{
locationManager.requestLocationUpdates(provider, MIN_TIME_REQUEST,
MIN_DISTANCE, locationListener);
}
private static LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
gotLocation(location);
}
};
private static void gotLocation(Location location) {
prevLocation = currentLocation == null ?
null : new Location(currentLocation);
currentLocation = location;
if (isLocationNew()) {
// do something
locationManager.removeUpdates(locationListener);
}
}
private static boolean isLocationNew() {
if (currentLocation == null) {
return false;
} else if (prevLocation == null) {
return false;
} else if (currentLocation.getTime() == prevLocation.getTime()) {
return false;
} else {
return true;
}
}

Categories

Resources