I am trying to get location using GPS provider or Network provider but i didn't get location from either GPS or Network.
Here is my code which was working fine some days ago but now it's not working.
I don't understand where i am wrong because all permission are already added in AndroidManifest.xml.
Here is the code which helpful for you to understand.
public class SearchDishoom extends Header implements LocationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchdish);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000000, 100, this);
locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// if gps provider is not enable then popup alertbox
buildAlertMessageNoGps();
} else {
// if gps is one then start searching
locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000000,100, locationListenerGps);
}
}
/*
* Get location (lat-long) from sharedpreference to further use
*/
prefLocation = getSharedPreferences("myLocation", MODE_WORLD_READABLE);
String userLocationLat1 = prefLocation.getString("Lat", String.valueOf(0));
String userLocationlong1 = prefLocation.getString("Long", String.valueOf(0));
String address = prefLocation.getString("Address", "Location not found not found");
userLocationLat = Double.parseDouble(userLocationLat1);
userLocationlong = Double.parseDouble(userLocationlong1);
// set lat-long value in getset class for use of another activity
gs = new GetSet();
gs.setLatitude(userLocationLat);
gs.setLangitude(userLocationlong);
if (userLocationLat == 0 && userLocationlong == 0 && address.equals("")) {
/*
* if lat-long is 0 or null then start searching using
* GPS Provider or Network Provider
*/
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000000,100, locationListenerGps);
}
} else {
// set lat-long value in getset class for use of another activity
gs.setLatitude(userLocationLat);
gs.setLangitude(userLocationlong);
setLocationName(userLocationLat, userLocationlong);
}
}
Here is override onLocationchanged():
#Override
public void onLocationChanged(Location location) {
userLocationLat =location.getLatitude();
userLocationlong =location.getLongitude();
prefLocation = getSharedPreferences("myLocation", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = prefLocation.edit();
prefsEditor.putString("Lat", String.valueOf(userLocationLat));
prefsEditor.putString("Long", String.valueOf(userLocationlong));
gs.setLatitude(userLocationLat);
gs.setLangitude(userLocationlong);
List<Address> addresses;
try {
addresses = new Geocoder(SearchDishoom.this, Locale.getDefault())
.getFromLocation(userLocationLat, userLocationlong, 1);
Address obj = addresses.get(0);
add = obj.getAddressLine(0);
city = obj.getLocality();
addressString = add + "," + city;
gs.setCurrentAddressString(addressString);
prefsEditor.putString("Address", addressString);
prefsEditor.commit();
tvLocation.setText(add + "," + city);
} catch (IOException e) {
showToast("Unable to find location");
}
}
Even i am not getting location using Geocoder, If i enter city name then it show me "Unable to find location".
Here is trick, GeoCoder is working on Emulator but not working on phone(i tried 2 different handset).
My project is build in API 17 and no any logcat error.
Please give me any hint or reference.
Maybe you should check "location access" settings and allow access to your location?..
While I cant immediately tell whats wrong with your code, you should consider maybe using a location library and let others do the heavy lifting. See: https://code.google.com/p/little-fluffy-location-library/
Related
I have a simple class to get the current location of the user it was working with no problem.
after i add a new function before I start get the user current location to check if GPS is open or not, if not opened it take the user to the setting file to open the GPS and then start take his location now I wait very long time and no location comes out. here is the code i use to get the current Location.
SingleShotLocationProvider
public class SingleShotLocationProvider {
public static interface LocationCallback {
public void onNewLocationAvailable(GPSCoordinates location);
}
public static boolean GPSOpen = false;
public static boolean NetworkOpen = false;
// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
NetworkOpen = isNetworkEnabled;
if (isNetworkEnabled) {
Log.i("NETWORK_OPEN", "YES NETWORK Open");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override public void onProviderEnabled(String provider) { }
#Override public void onProviderDisabled(String provider) { }
}, null);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
GPSOpen = isGPSEnabled;
if (isGPSEnabled) {
Log.i("GPS_OPEN", "YES GPS Opened");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override public void onProviderEnabled(String provider) { }
#Override public void onProviderDisabled(String provider) { }
}, null);
}
else {
Toast.makeText(context, "Please Open GPS and retry", Toast.LENGTH_LONG).show();
MainWindow w = (MainWindow)context;
w.DisableTheProgressGPSClosed(); // i have a simple progress bar wait until the app get the location then it GONE
}
}
}
// consider returning Location instead of this dummy wrapper class
public static class GPSCoordinates {
public float longitude = -1;
public float latitude = -1;
public GPSCoordinates(float theLatitude, float theLongitude) {
longitude = theLongitude;
latitude = theLatitude;
}
public GPSCoordinates(double theLatitude, double theLongitude) {
longitude = (float) theLongitude;
latitude = (float) theLatitude;
}
}
}
here is the function I use to check the GPS open or not.
public boolean turnGPSOn()
{
LocationManager L = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!L.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "Please open GPS", Toast.LENGTH_LONG).show();
Intent I = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(I);
return true;
}
return false;
}
here how I use it when the user click the button.
public void GetLocation() {
if (turnGPSOn()) {
return;
}
Log.i("Process_GPS_DATA", "Done process now GPS");
progressBar.setVisibility(View.VISIBLE);
foo(this);
}
foo function which call the GPS class here.
public void foo(final Context context) {
// when you need location
// if inside activity context = this;
SingleShotLocationProvider.requestSingleUpdate(context,
new SingleShotLocationProvider.LocationCallback() {
#Override public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
Log.i("Location", "my location is " + location.latitude + "," + location.longitude);
String BaseLocation = "https://www.google.com/maps/?q=" + location.latitude + "," + location.longitude + "";
StartSendRequest(location.longitude, location.latitude, BaseLocation);
Log.i("Google_URL", BaseLocation);
}
});
}
the problem is everything works fine but I wait a long time and no location are show I don't know why this problem, when i make a test I close the android GPS and then make the test no location are provided I test the same class before add check part and it worked fine.
when i test in emulator with already open GPS it worked and give me a location when i close GPS and then test again it not worked and I wait for long time and nothing show so what I did wrong.
I will need to use Location data in multiple activities of my app and I was wondering if it was necessary to make a new LocationClient in each activity, or if there is a better way to create it once and access it from each activity. Any recommendations on how I should handle this?
I think it would be much better to create a single class for location listener and used it every where in your project.I have just created this in one of my package and in every class where i want to get the location values.I just call this.
LocationSender loc = new LocationSender(YourClass.this);
As i declared lat,lng as static so i can get any where its values.
double latitude = LocationSender.lat;
double longitude = LocationSender.lng;
LocationSender.java
public class LocationSender {
Context context;
LocationManager locationManager;
Location location;
static double lat,lng;
public LocationSender(Context ctx) {
context=ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
// Acquire a reference to the system Location Manager
public void getNewLocation(Location location) throws JSONException
{
String latLongString = "";
if (location != null) {
this.location=location;
lat= location.getLatitude();
lng = location.getLongitude();
latLongString = "Lat:" + String.valueOf(LocationActivity.lat) + "\nLong:" + String.valueOf(LocationActivity.lng);
Log.d("Location Found", latLongString);
} else
{
location=null;
latLongString = "No location found";
}
Toast.makeText(context, latLongString, Toast.LENGTH_LONG).show();
}
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
try {
getNewLocation(location);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onProviderEnabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : Enabled", Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(context, "Provider: "+provider+" : disabled", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(context, "Provider: "+provider+" : status: "+status, Toast.LENGTH_LONG).show();
}
};
}
Also please dont forget to insert location permissions in AndroidManifest.xml :)
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
A service which starts at boot with a LocationListener then sends the position and device data to a web service. The code works perfectly when not part of a service, the service but passes only a first position and not updated.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
onLocationChanged(location);
item.LatitudePhone = f_latitude;
item.LongitudePhone = f_longitude;
} else {
item.LatitudePhone = f_latitude;
item.LongitudePhone = f_longitude;
}
item.Active = false;
return item;
}
/* Request updates at startup */
// #Override
protected void onResume() {
// super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the location listener updates when Activity is paused */
// #Override
protected void onPause() {
// super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
f_latitude = (float) (location.getLatitude());
f_longitude = (float) (location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
If you are using the same code as it is in the service, then problem can be because you are telling the listener not to update in OnPause() method: locationManager.removeUpdates(this); . So maybe after giving one value it stops updating. Try to remove it, so as to let it update. See what happens. Hope this helps else please comment.
I am new to android, can anyone help me for my question....
How to get a current position and tracking in map using GPS without giving any location in a program?????
You want the easy way out ! Use MyLocationOverlay object. you can get the current location by calling the method getLastFix(); . To enable tracking use enableMyLocation(). To add this object to the map you need to add it to your map overlays.
MyLocationOverlay currLoc=new MyLocationOverlay(context,mapKey);
mapView.getAllOverlays.add(currLoc);
currLoc.enableMyLocation();
Location myLastLocation=currLoc.getLastFix();
currLoc.enableCompass();
Do make sure, in onPause() you do this :
currLoc.disableMyLocation(); //to save battery.
you can resume updates in onResume() by calling currLoc.enableMyLocation();
This is the easiest way I could find! and it is quite accurate too
Try ;
String m_BestProvider;
LocationManager m_LocationManager;
LocationListener m_LocationListener = null;
Location m_Location = null;
m_LocationManager = (LocationManager) m_Context.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
m_BestProvider = m_LocationManager.getBestProvider(c, false);
// Define a listener that responds to location updates
m_LocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
m_LocationManager.requestLocationUpdates(m_BestProvider, 0, 0, m_LocationListener);
m_Location = m_LocationManager.getLastKnownLocation(m_BestProvider);
Systme.out.println(m_Location.getLatitude() "," +m_Location.getLongitude());
Add in AndriodManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
public class GPSLocationBased extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationbased);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new Mylocationlistener();
// ---Get the status of GPS---
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS is not enable then it will be on
if(!isGPS)
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
}
//<--registers the current activity to be notified periodically by the named provider. Periodically,
//the supplied LocationListener will be called with the current Location or with status updates.-->
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
/**
*Mylocationlistener class will give the current GPS location
*with the help of Location Listener interface
*/
private class Mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// ---Get current location latitude, longitude, altitude & speed ---
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
float speed = location.getSpeed();
double altitude = location.getAltitude();
Toast.makeText(GPSLocationBased.this,"Latitude = "+
location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Through this code u will get ur lat and long.
and u may use it on ur gmap.
this code also start gps functionality problematically. Hope this will help u.. All the best :)