I am using this code. but getting null in longitude and latitude.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Take a look at this tutorial: A Deep Dive Into Location
Basically, if you want to get the approximate location using the last known location, you should iterate through all the possible providers with a loop like this:
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
if ((time > minTime && accuracy < bestAccuracy)) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
}
else if (time < minTime &&
bestAccuracy == Float.MAX_VALUE && time > bestTime){
bestResult = location;
bestTime = time;
}
}
}
You can use the LocationManager. See the example:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
And place it in Manisfest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
did you added
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Permission to manifest file
Try This
public class LocationDemo extends Activity implements LocationListener {
private static final String TAG = "LocationDemo";
private static final String[] S = { "Out of Service",
"Temporarily Unavailable", "Available" };
private TextView output;
private LocationManager locationManager;
private String bestProvider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the output UI
output = (TextView) findViewById(R.id.output);
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// List all providers:
List<String> providers = locationManager.getAllProviders();
for (String provider : providers) {
printProvider(provider);
}
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
output.append("\n\nBEST Provider:\n");
printProvider(bestProvider);
output.append("\n\nLocations (starting with last known):");
Location location = locationManager.getLastKnownLocation(bestProvider);
printLocation(location);
}
/** Register for the updates when Activity is in foreground */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(bestProvider, 20000, 1, this);
}
/** Stop the updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
printLocation(location);
}
public void onProviderDisabled(String provider) {
// let okProvider be bestProvider
// re-register for updates
output.append("\n\nProvider Disabled: " + provider);
}
public void onProviderEnabled(String provider) {
// is provider better than bestProvider?
// is yes, bestProvider = provider
output.append("\n\nProvider Enabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
output.append("\n\nProvider Status Changed: " + provider + ", Status="
+ S[status] + ", Extras=" + extras);
}
private void printProvider(String provider) {
LocationProvider info = locationManager.getProvider(provider);
output.append(info.toString() + "\n\n");
}
private void printLocation(Location location) {
if (location == null)
output.append("\nLocation[unknown]\n\n");
else
output.append("\n\n" + location.toString());
}
}
// main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ScrollView android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="#+id/output" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
implementation 'com.google.android.gms:play-services-location:11.6.0'
public class LocationExample Eextends AppCompatActivity implements LocationListener {
double latitude, longitude;
LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getLocation()
}
void getLocation() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//GlobalToast.toastMessage(this, "please provide location permission.");
return;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 400, this);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 400, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("location", "change");
Log.d("latitude", String.valueOf(latitude));
Log.d("longitude", String.valueOf(longitude));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(getApplicationContext(), "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
}
Related
I am trying to get Current Location using either GPS or Network Provider. My device's GPS is enabled but I'm not getting Latitude and Longitude.
GpsTracker.java:
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;
boolean canGetLocation = false;
Location location;
public double latitude;
public double longitude;
// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// metters
// 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 Network Provider Enabled get lat/long using GPS Services
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
}
// 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();
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
}
Service.Java
public class WifiScaningService extends IntentService {
GpsTracker gpsTracker;
double latitude;
double longitude;
public WifiScaningService() {
super("WifiScaningService");
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Log.e("service call","service call");
}
#Override
protected void onHandleIntent(Intent intent) {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
gpsTracker = new GpsTracker(this);
String stringLatitude = String.valueOf(gpsTracker.latitude);
latitude = Double.parseDouble(stringLatitude);
Log.e("Latitude",stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
longitude = Double.parseDouble(stringLongitude);
Log.e("Longitude",stringLongitude);
return START_STICKY;
}
}
I have included necessary permissions in AndroidManifest.xml file. Required to show current location.
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
uses-permission android:name="android.permission.INTERNET"/>
MainActivity:
import android.location.Address;
import android.location.Location;
import com.example.havadurumumenu.MyLocationManager.LocationHandler;
public class MainActivityextends Activity implements LocationHandler{
public MyLocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentLocation();
}
});
}
public void currentLocation(){
locationManager = new MyLocationManager();
locationManager.setHandler(this);
boolean isBegin = locationManager.checkProvidersAndStart(getApplicationContext());
if(isBegin){
//if at least one of the location providers are on it comes into this part.
}else{
//if none of the location providers are on it comes into this part.
}
}
#Override
public void locationFound(Location location) {
Log.d("LocationFound", ""+location);
//you can reach your Location here
//double latitude = location.getLatitude();
//double longtitude = location.getLongitude();
locationManager.removeUpdates();
}
#Override
public void locationTimeOut() {
locationManager.removeUpdates();
//you can set a timeout in MyLocationManager class
txt.setText("Unable to locate. Check your phone's location settings");
}
MyLocationManager:
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
/*---------- Listener class to get coordinates ------------- */
public class MyLocationManager implements LocationListener {
public LocationManager locationManager;
public LocationHandler handler;
private boolean isLocationFound = false;
public MyLocationManager() {}
public LocationHandler getHandler() {
return handler;
}
public void setHandler(LocationHandler handler) {
this.handler = handler;
}
#SuppressLint("HandlerLeak")
public boolean checkProvidersAndStart(Context context){
boolean isBegin = false;
Handler stopHandler = new Handler(){
public void handleMessage(Message msg){
if (!isLocationFound) {
handler.locationTimeOut();
}
}
};
stopHandler.sendMessageDelayed(new Message(), 15000);
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1000, this);
isBegin = true;
}
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1000, this);
isBegin = true;
}
return isBegin;
}
public void removeUpdates(){
locationManager.removeUpdates(this);
}
/**
* To get city name from coordinates
* #param location is the Location object
* #return city name
*/
public String findCity(Location location){
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(AppController.getInstance(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
cityName = addresses.get(0).getLocality();
}
catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
#Override
public void onLocationChanged(Location loc) {
isLocationFound = true;
handler.locationFound(loc);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
public interface LocationHandler{
public void locationFound(Location location);
public void locationTimeOut();
}
}
Also add all the permissions below in your Manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
I Solved by exchanging position of both methods.
First app trying to get location using GPS if GPS is not enabled then using network provider method.
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;
boolean canGetLocation = false;
Location location;
public double latitude;
public double longitude;
// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// metters
// The minimum time beetwen 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 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();
}
}
}
// if Network Provider Enabled get lat/long using GPS Services
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
// e.printStackTrace();
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
}
I'm trying to get GPS values every few seconds and I'm missing some trick. Here's what I've tried:
public class Locn extends ActionBarActivity
{
private LocationManager locationManager;
private String provider;
private Location loc = null;
private Criteria criteria;
... local variables ...
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled. If not send user to the GPS settings
if (!enabled)
{
Toast.makeText(this, "Please enable GPS location service",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else
{
Toast.makeText(this, "GPS location service is enabled",
Toast.LENGTH_SHORT).show();
}
// Define the criteria to select the location provider -> use default
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
// Let Android select the best location provider based on criteria
provider = locationManager.getBestProvider(criteria, true);
...
}
//--------------------------------------
// Set up timer handlers
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable()
{
#Override
public void run()
{
provider = locationManager.getBestProvider(criteria, true);
loc = locationManager.getLastKnownLocation(provider);
milli = System.currentTimeMillis();
longitude = loc.getLongitude();
latitude = loc.getLatitude();
count++;
timerHandler.postDelayed(this, 2000);
}
};
count and milli changes every two seconds but the latitude and longitude do not change at all. (Yes, I'm changing position -- up to 2 miles)
What am I missing here? Does loc have to be cleared before calling getLastKnownLocation again?
Thanks,
Walt
Timer tm =new Timer();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
tm.schedule(new task(),10,10000);//this execute task every 10 seconds
//use the timer task in your main activity
class task extends TimerTask {
public void run() {
Home.this.runOnUiThread(new Runnable() {
public void run() {
longitude = loc.getLongitude();
latitude = loc.getLatitude();
});
}
};
You don't need a Timer. Just use LocationManager.requestLocationUpdates()
From Android documentation:
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
See at: Android LocationManager
Just use like below:
public class MainActivity extends Activity implements LocationListener {
private String provider;
private LocationManager lm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
}
#Override
protected void onResume() {
super.onResume();
lm.requestLocationUpdates(provider, 1000, 10, this);
}
#Override
protected void onPause() {
super.onPause();
lm.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
I am trying to get the location from the best provider. I have enabled the GPS. Also, when I am printing the latitude and longitude, I am getting it from the Network provider.
My question is:
If GPS is enabled, then I want to search for 30 seconds for the location via GPS. After that, if I got the accuracy below 200 meters, then I use that. If the accuracy goes beyond 200 meters, then I search again and get started from the network provider.
After that, I compare both accuracies and take the data of the provider which is more accurate.
Here is my code:
LocationUtil.java
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
public class LocationUtil
{
Activity activity;
Location location;
public LocationUtil(Activity activity)
{
this.activity = activity;
}
public int getLogitudeE6()
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
int lg = (int) (((double) location.getLongitude()) * 1E6);
System.out.println("Longitude :: " + lg);
return lg;
}
public int getLatitudeE6()
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
int lt = (int) (((double) location.getLatitude()) * 1E6);
System.out.println("Latitude :: " + lt);
return lt;
}
public double getLogitude(Location location)
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
this.location = location;
}
return location.getLongitude();
}
public double getLatitude(Location location)
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
this.location = location;
}
return location.getLatitude();
}
public double getAccuracy(Location location)
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
this.location = location;
}
return location.getAccuracy();
}
public double getLogitude()
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
this.location = location;
}
return location.getLongitude();
}
public double getLatitude()
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
this.location = location;
}
return location.getLatitude();
}
}
CaptureMain.java
import java.util.Timer;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class CaptureMain extends Activity implements LocationListener {
/** Called when the activity is first created. */
TextView txtNewLocation;
String strLatBack, strLongBack, strLatitude, strLongitude,strAccuracy;
LocationUtil locationUtil;
Location location;
LocationManager lm;
String bestProvider;
Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtNewLocation = (TextView) findViewById(R.id.txtLocation);
locationUtil = new LocationUtil(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
bestProvider = lm.getBestProvider(criteria, false);
Log.i("Log", "Best provider is : "+bestProvider);
strLatitude = String.valueOf(locationUtil.getLatitude(location));
strLongitude = String.valueOf(locationUtil.getLogitude(location));
strAccuracy = String.valueOf(locationUtil.getAccuracy(location));
txtNewLocation.setText("Latitude :" + strLatitude + ", Longitude :"
+ strLongitude + " , Accuracy "+ strAccuracy);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
System.out.println("On Location change called:: ");
if (location != null) {
this.location = location;
}
strLatitude = String.valueOf(locationUtil.getLatitude(location));
strLongitude = String.valueOf(locationUtil.getLogitude(location));
strAccuracy = String.valueOf(locationUtil.getAccuracy(location));
if (strLatitude.equals("") || strLongitude.equals("")) {
txtNewLocation.setText("Locating current position..");
} else {
txtNewLocation.setText("Latitude :" + strLatitude + ", Longitude :"
+ strLongitude + " , Accuracy "+ strAccuracy);
}
}
#Override
protected void onStart() {
super.onStart();
startListening();
}
#Override
protected void onResume() {
super.onResume();
startListening();
}
#Override
protected void onPause() {
super.onPause();
stopListening();
}
#Override
protected void onDestroy() {
super.onDestroy();
stopListening();
finish();
}
private void stopListening() {
if (lm != null)
lm.removeUpdates(this);
}
private void startListening() {
lm.requestLocationUpdates(bestProvider, 0, 0, this);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Added permission in manifest:
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
I have not studied your algorithm in detail, but 200m is not a good threshold for GPS.
horicontal accuracy should be under 50 m.
only GPS has attribute course and altitude(i am not 100% sure) and speed . check for a valid altitude and course, too.
Course (and speed) is only valid if device moves.
But can you not just simply query the type of location provider? (GPS)
i use the following code for getting the current latitude and longitude in services but it always return null. please help me.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println("provider "+provider);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Try this code for current location:
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10,
10, mlocListener);
public class MyLocationListener implements LocationListener {
public void onProviderDisabled(String provider)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(
VisualCV.this);
dlgAlert.setMessage("Gps Disabled ");
dlgAlert.setTitle("Message");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps enabled", Toast.LENGTH_SHORT ).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public void onLocationChanged(Location loc)
{
// TODO Auto-generated method stub
Latitud = loc.getLatitude();
longtitude = loc.getLongitude();
lang = String.format("%.4f", longtitude);//LONGITUDE
lati = String.format("%.4f", Latitud);//LATITUDE
}
}
Use this piece of code may be it may help you
import com.example.ConfigClass;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class GpsListener {
public static GpsListener refrence = null ;
public LocationManager locationManager = null;
public LocationListener locationListener = null;
public Location location = null;
public static GpsListener getInstance(){
if(refrence == null){
refrence = new GpsListener();
}
return refrence;
}
public void startGpsCallBack(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
public class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public void stopGpsCallBack(){
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
public void startGpsCallbackAgain(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
}
This is my code
First startGpsCallBack, then stop it and then call startGPSCallBackAgain method
Check it and let me know if this solves your problem
Try this.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
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)
{
}
}
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
I find the onLocationChanged function is PERFECTLY working when the location is Changed with the above code.
///////CLASS mylocationlistener
private class mylocationlistener implements LocationListener {
//#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(MainActivity.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
p = new GeoPoint((int)location.getLatitude(),(int)location.getLongitude());
// p = new GeoPoint((int)8.538754,(int)76.950620);
}
}
//#Override
public void onProviderDisabled(String provider) {
}
// #Override
public void onProviderEnabled(String provider) {
}
// #Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
But the Problem is that I want the variable "p" to be filled with the current location , when the program starts, that is Before the First Change Help !!
try this code:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
System.out.println("Location not avilable");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
Log.i(TAG, "Lattitude:" +lat);
Log.i(TAG, "Longitude:" +lng);
}
Before you get fix, you can use coarse location. Check this link:
http://devdiscoveries.wordpress.com/2010/02/04/android-use-location-services/