Unable to find user location using GPS - android

public class LocationtesterActivity extends Activity {
/** Called when the activity is first created. */
LocationManager locManager;
// LocationListener locListener;
Button b;
String provider;
TextView lat, alt, longi;
// Here i am first checking if both GPS and network options are enabled in Lovation and Security Settings or not.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.button1);
lat = (TextView) findViewById(R.id.lattitude);
alt = (TextView) findViewById(R.id.altitude);
longi = (TextView) findViewById(R.id.longitude);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locManager.getBestProvider(criteria, true);
System.out.println("best provider is :" + provider);
if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| !locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
System.out.println("in provider enablement");
createGpsDisabledAlert();
}
else {
System.out.println("in location update request");
locManager.requestLocationUpdates(provider, 0, 0,
new MyLocationListener());
}
}
// for displaying the Dialogue Box
// if GPS or network not enabled
// and also taking to location and security screen
private void createGpsDisabledAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Your GPS or network provider is disabled! Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable provider",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
showGpsOptions();
}
});
builder.setNegativeButton("Do nothing",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions() {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(gpsOptionsIntent, 5);
}
// //////ends/////
// Code to check whether user enabled GPS and Network provider in settings
// if not then show the dialogue box again
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 5 && resultCode == 0) {
if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createGpsDisabledAlert();
// Toast.makeText(this,
// "provider not enabled. Click the button for settings",
// 2000).show();
} else {
Intent i=new Intent(this, LocationtesterActivity.class);
startActivity(i);
Toast.makeText(this, "User has enabled the provider", 1000)
.show();
}
}
}
// Method to display the current location
protected void showCurrentLocation() {
Location location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
lat.setText("" + location.getLatitude());
longi.setText("" + location.getLongitude());
Toast.makeText(LocationtesterActivity.this, message,
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(LocationtesterActivity.this, "no last known location", 1000).show();
}
}
// Inner class for LocationListener
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
System.out.println("in location changed");
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
lat.setText("" + location.getLatitude());
longi.setText("" + location.getLongitude());
// alt.setText("" + location.getAltitude());
Toast.makeText(LocationtesterActivity.this, message,
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LocationtesterActivity.this,
"Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LocationtesterActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LocationtesterActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
I am using the above code to find the User Location.
1.I am getting always GPS as the best provider according to my criteria but that is fine to me.
2.Thing is that why am i not able to get any location values ?
Even with Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); i am not getting any thing.
Please help me in getting the location values.

GPS take some time due to slow and not available inside the building .You just check it outside the building.
And
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); only works if once GPS get any location previously.

Two things,
Have u set "android.permission.ACCESS_FINE_LOCATION" permission in manifest file ??
clear all data of Google map application and then try to load map for get current location on map, If Google map give your current location then your application can fetch current location.
Its good habit to use best criteria for fetching location.
sometimes devices can not read current location. I also face this problem but at that time i check Google Map / Direction application and reset my GPS.

Related

wierd location, distance output for maps using gps

after some time where i run my app, the distance remains 0 which is correct since i am not moving, but after 20-30 min in between it gain to 8-18 meters, i forgot. even more later, it grow to hundred. over time the marker gets more dispersed.
how can i pinpoint a location and if i never move, stop changing?
if i move, from my room to my living room, should be 4-7meters about i think, the distance never increase.
for those who done similar stuff before, does the blue dot and red marker goes together. my blue dot is not correct most of the time
i really do not know where i can improve my codes or what is the cause of the output..
My MainActivity File
public class MainActivity extends FragmentActivity implements LocationListener{
protected LocationManager locationManager;
private GoogleMap googleMap;
Button btnStartMove,btnPause,btnResume,btnStop;
static double n=0;
Long s1,r1;
double dis=0.0;
Thread t1;
EditText userNumberInput;
boolean bool=false;
int count=0;
double speed = 1.6;
double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
double dist = 0;
TextView distanceText;
float[] result;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES =1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 4000; //in milliseconds
boolean startDistance = false;
boolean startButtonClicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
if(isGooglePlay())
{
setUpMapIfNeeded();
}
distanceText=(TextView)findViewById(R.id.Distance);
btnStartMove=(Button)findViewById(R.id.Start);//start moving
//prepare distance...........
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
btnStartMove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
lat3 = location.getLatitude();
lon3 = location.getLongitude();
startButtonClicked=true;
Toast.makeText(MainActivity.this,
"start is true",
Toast.LENGTH_LONG).show();
}
});
if(location!= null)
{
//Display current location in Toast
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
//Display current location in textview
//latitude.setText("Current Latitude: " + String.valueOf(location.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(location.getLongitude()));
}
else if(location == null)
{
Toast.makeText(MainActivity.this,
"Location is null",
Toast.LENGTH_LONG).show();
}
}
private void setUpMapIfNeeded() {
if(googleMap == null)
{
Toast.makeText(MainActivity.this, "Getting map",
Toast.LENGTH_LONG).show();
googleMap =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.displayMap)).getMap();
if(googleMap != null)
{
setUpMap();
}
}
}
private void setUpMap()
{
//Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
//Get locationManager object from System Service LOCATION_SERVICE
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
if(provider == null)
{
onProviderDisabled(provider);
}
//set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Get current location
Location myLocation = locationManager.getLastKnownLocation(provider);
if(myLocation != null)
{
onLocationChanged(myLocation);
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
private boolean isGooglePlay()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS)
{
Toast.makeText(MainActivity.this, "Google Play Services is available",
Toast.LENGTH_LONG).show();
return(true);
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
}
return (false);
}
#Override
public void onLocationChanged(Location myLocation) {
System.out.println("speed " + myLocation.getSpeed());
// if(myLocation.getSpeed() > speed)//return 0 in actual
// {
//show location on map.................
//Get latitude of the current location
double latitude = myLocation.getLatitude();
//Get longitude of the current location
double longitude = myLocation.getLongitude();
//Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
//show distance............................
if(startDistance == true)
{
Toast.makeText(MainActivity.this,
"Location has changed",
Toast.LENGTH_LONG).show();
if(myLocation != null)
{
//latitude.setText("Current Latitude: " + String.valueOf(loc2.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(loc2.getLongitude()));
float[] results = new float[1];
Location.distanceBetween(lat3, lon3, myLocation.getLatitude(), myLocation.getLongitude(), results);
System.out.println("Distance is: " + results[0]);
dist += results[0];
DecimalFormat df = new DecimalFormat("#.##"); // adjust this as appropriate
if(count==1)
{
distanceText.setText(df.format(dist) + "meters");
}
lat3=myLocation.getLatitude();
lon3=myLocation.getLongitude();
count=1;
}
}
if(startButtonClicked == true)
{
startDistance=true;
}
//}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
}}
i tried changing the min time and distance to all sorts of data and it remains the same. i never really move my phone most of the time in the above output. one time i move out for short while but distance did not increase. for those that done similar running app, which part do i need to change..i can't spot where is something wrong..
The thing is, as long as you're not using GPS your position can be very inaccurate since it's only using the internet and your mobile network information. The accuracy of such measurements can vary greatly, from 10-20 meters up to 2000-3000+ meters. That said, even staying on the same network and in the same location sometimes the accuracy changes and with it your position changes. So you might see your accurate location now, in a few minutes you might be a kilometer away from where you really are on the map. And in case you're using GPS, keep in mind that GPS isn't always available (ie. when you're indoors) and takes some time to start up.
you might want to use only GPS which would make your app unusable in case you're not outside, or you could come up with an algorithm to check if you really are at the new location (use the locations accuracy, time since last location update, or something like that).

android inaccurate gps on google maps v2

1)my android app needs to calculate the accumulate distance when the user press start. when i run, it wait a while then start calculating. which i think may be ok. but when i am not moving, the meters also accumulated by itself.
when i tested it while moving it outside, the blue dot is inaccurate and keeps jumping about. this will makes the distance inaccurate. now i retest i think the red marker is me as it displays the "you are here" one time i tested it. it is all over the place. how do i improve the gps accuracy.
From what it seems, the meters inaccuracy is due to the gps jumping around and not the calculation. i wanted to make a dot follow me and not many markers appearing where i have been..
2)also, i tried displaying this on emulator but failed(googles maps v2). i did install some apk with newely created emulator but failed too. is it illegal even if it works? also i need to display on the same emulator as my team. as a last resort i can display on my phone.
3)to make google maps v2 work on other computer what do i need to do. my research says i need to sign the API key but so far i found are google maps v1 version.
my java file
public class MainActivity extends FragmentActivity implements LocationListener{
protected LocationManager locationManager;
private GoogleMap googleMap;
Button btnStartMove,btnPause,btnResume,btnStop;
static double n=0;
Long s1,r1;
double dis=0.0;
Thread t1;
EditText userNumberInput;
boolean bool=false;
int count=0;
double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
double dist = 0;
TextView distanceText;
float[] result;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 0;
boolean startDistance = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
if(isGooglePlay())
{
setUpMapIfNeeded();
}
distanceText=(TextView)findViewById(R.id.Distance);
btnStartMove=(Button)findViewById(R.id.Start);//start moving
btnStartMove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
startDistance = true;
}
});
//prepare distance...........
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
if(location!= null)
{
//Display current location in Toast
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
//Display current location in textview
//latitude.setText("Current Latitude: " + String.valueOf(location.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(location.getLongitude()));
lat3 = location.getLatitude();
lon3 = location.getLongitude();
}
else if(location == null)
{
Toast.makeText(MainActivity.this,
"Location is null",
Toast.LENGTH_LONG).show();
}
}
private void setUpMapIfNeeded() {
if(googleMap == null)
{
Toast.makeText(MainActivity.this, "Getting map",
Toast.LENGTH_LONG).show();
googleMap =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.displayMap)).getMap();
if(googleMap != null)
{
setUpMap();
}
}
}
private void setUpMap()
{
//Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
//Get locationManager object from System Service LOCATION_SERVICE
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
if(provider == null)
{
onProviderDisabled(provider);
}
//set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Get current location
Location myLocation = locationManager.getLastKnownLocation(provider);
if(myLocation != null)
{
onLocationChanged(myLocation);
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
private boolean isGooglePlay()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS)
{
Toast.makeText(MainActivity.this, "Google Play Services is available",
Toast.LENGTH_LONG).show();
return(true);
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
}
return (false);
}
#Override
public void onLocationChanged(Location myLocation) {
//show location on map.................
//Get latitude of the current location
double latitude = myLocation.getLatitude();
//Get longitude of the current location
double longitude = myLocation.getLongitude();
//Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
//show distance............................
if(startDistance == true)
{
Toast.makeText(MainActivity.this,
"Location has changed",
Toast.LENGTH_LONG).show();
if(myLocation != null)
{
//latitude.setText("Current Latitude: " + String.valueOf(loc2.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(loc2.getLongitude()));
float[] results = new float[1];
Location.distanceBetween(lat3, lon3, myLocation.getLatitude(), myLocation.getLongitude(), results);
System.out.println("Distance is: " + results[0]);
dist += results[0];
DecimalFormat df = new DecimalFormat("#.##"); // adjust this as appropriate
if(count==1)
{
distanceText.setText(df.format(dist) + "meters");
}
lat3=myLocation.getLatitude();
lon3=myLocation.getLongitude();
count=1;
}
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
}}
first screenshot, second after a while in seconds, third after 1 hour about.
at the thrid shot, the screen always return back to the place where there are many red markers and not the blue dot. the toast "location has changed" keeps staying on the screen
the main problem is to ensure accurate distance by ensuring accurate gps. i have been troubled a long time by this, i even take away the map from my application since i can't solve it but now i need it.
To remove the jumping locations, ignore all that have location.getSpeed() < speedThreshold.
Choose a speed threshold according to your app needs, but over 5km/h.
(GPS is inacurate if you stand or move slowly)
Additional Info: see my answer at different-gps-location-reading-of-same-physical-location-on-windows-phone-geocoo

Get user location LAT LNG using GPS and network

I am trying to get lat and lng and want to show that in a text box I want both mean Network address and GPS address so I have done this But every time I am getting only one address at a time
public class GetLocationMainActivity extends Activity {
double nlat;
double nlng;
double glat;
double glng;
LocationManager glocManager;
LocationListener glocListener;
LocationManager nlocManager;
LocationListener nlocListener;
TextView textViewNetLat;
TextView textViewNetLng;
TextView textViewGpsLat;
TextView textViewGpsLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location_main);
//All textView
textViewNetLat = (TextView)findViewById(R.id.textViewNetLat);
textViewNetLng = (TextView)findViewById(R.id.textViewNetLng);
textViewGpsLat = (TextView)findViewById(R.id.textViewGpsLat);
textViewGpsLng = (TextView)findViewById(R.id.textViewGpsLng);
}
#Override
public void onDestroy() {
//Remove GPS location update
if(glocManager != null){
glocManager.removeUpdates(glocListener);
Log.d("ServiceForLatLng", "GPS Update Released");
}
//Remove Network location update
if(nlocManager != null){
nlocManager.removeUpdates(nlocListener);
Log.d("ServiceForLatLng", "Network Update Released");
}
super.onDestroy();
}
//This is for Lat lng which is determine by your wireless or mobile network
public class MyLocationListenerNetWork implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
nlat = loc.getLatitude();
nlng = loc.getLongitude();
//Setting the Network Lat, Lng into the textView
textViewNetLat.setText("Network Latitude: " + nlat);
textViewNetLng.setText("Network Longitude: " + nlng);
Log.d("LAT & LNG Network:", nlat + " " + nlng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "Network is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling Network !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public class MyLocationListenerGPS implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
glat = loc.getLatitude();
glng = loc.getLongitude();
//Setting the GPS Lat, Lng into the textView
textViewGpsLat.setText("GPS Latitude: " + glat);
textViewGpsLng.setText("GPS Longitude: " + glng);
Log.d("LAT & LNG GPS:", glat + " " + glng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "GPS is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling GPS !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public void showLoc(View v) {
//Location access ON or OFF checking
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
boolean networkWifiStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.NETWORK_PROVIDER);
//If GPS and Network location is not accessible show an alert and ask user to enable both
if(!gpsStatus || !networkWifiStatus)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(GetLocationMainActivity.this);
alertDialog.setTitle("Make your location accessible ...");
alertDialog.setMessage("Your Location is not accessible to us.To give attendance you have to enable it.");
alertDialog.setIcon(R.drawable.warning);
alertDialog.setNegativeButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
});
alertDialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Toast.makeText(getApplicationContext(), "Remember to give attandance you have to eanable it !", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
alertDialog.show();
}
//IF GPS and Network location is accessible
else
{
nlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
nlocListener = new MyLocationListenerNetWork();
nlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000 * 1, // 1 Sec
1, // 1 meter
nlocListener);
glocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
glocListener = new MyLocationListenerGPS();
glocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000 * 1, // 1 Sec
1, // 1 meter
glocListener);
}
}
}
Have you enable both NETWORK-LOCATION and GPS-LOCATION in Settings yet? As far as I know for Android ICS (4.x) and newer, due to the Security issue, you can't enable/disable location access programmatically. Try to test it on Android 2.x. Hope this helps.
You can use the new fused provider to get the user location quickly without confuse.
Location issues has been simplified with the new Google Play Services such as choosing best provider automatically depending on your priority.
Here is an example request;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(20000) // 20 seconds
.setFastestInterval(16) // 16ms = 60fps
.setNumUpdates(4)
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
Make sure you updated the Google Play Services in the SDK Manager and check out this link to get info about how to get users location with the new Play Services.
http://developer.android.com/training/location/retrieve-current.html

Finding the users location

I am developing an android application. I need to find the location of the user as soon as he/she logs in to the application. I do not want maps to be displayed, the location should be identified without the user's knowledge. Is it possible to do this using the Google maps API? or is there any other way to do this?
Thanks
The best way to do this is to use the PASSIVE location provider like so:
LocationManager lm = (LocationManager)yourActivityContext.getSystemService(Context.LOCATION_SERVICE);
Location lastKnown = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
This returns the last known location received by the operating system, so this may be stale, but you can check when the location was retrieved, and by which provider by querying the location object.
In conclusion, the user will have no idea that you've gotten a location except that your app will require the proper location permission(s).
Try this,
protected LocationManager locationManager;
Context context;
public String gps_loc;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 10, new MyLocationListener());
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
gps_loc = String.format("%1$s" +"-"+"%2$s",location.getLongitude(), location.getLatitude());
Toast.makeText(Clockin.this, gps_loc, Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(class.this, "Provider status changed", Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(class.this,"Provider disabled by the user. GPS turned off",Toast.LENGTH_SHORT).show();
final AlertDialog alertDialog = new AlertDialog.Builder(class.this).create();
alertDialog.setTitle("Activate GPS...");
alertDialog.setButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
});
alertDialog.show();
}
public void onProviderEnabled(String s) {
Toast.makeText(class.this,"Provider enabled by the user. GPS turned on", Toast.LENGTH_SHORT).show();
}
}

Message not showing on emulator screen

Here is the code to find the current location, but nothing shows on the screen after pressing the retreive button.
I have reset adb and tried to send the data from emulator control manually. But when I send data using emulator control, then the emulator restarts but never shows the home screen.
Please help. Thanks in advance.
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
In you code you might not be receiving the current location(this is because in you need to push your location manually through emulator control).
Just have else case also in showCurrentLocation() and check whether the location object is null or not like below.
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(LbsGeocodingActivity.this, "location is null",
Toast.LENGTH_LONG).show();
}
}
On our first attempts to use the location sensors we had similar problems. Two things help the most in order to get the best results from GPS.
On the emulator the Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); causes a lot force closes.
And most important. Its far more stable to input the gps data through telnet. telnet localhost 5554 (You can see the port on the emulators window title). The command for a new gps fix is: geo fix lat lng

Categories

Resources