Modify the settings of Android device - android

I am using Location Service in my app as follows:
LocationManager locM = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
criteria.setSpeedRequired(false);
String currentProvider = locM.getBestProvider(criteria, true);
Log.d("Location", "currentProvider: " + currentProvider);
Location currentLocation = locM.getLastKnownLocation(currentProvider);
if(currentLocation == null){
locM.requestLocationUpdates(currentProvider, 0, 0, locationListener);
}
And I add permissions of network and locations in Manifest.xml.
When I test this code in my Android phone earlier today, this line String currentProvider = locM.getBestProvider(criteria, true); always returned null. After some googling, I find out that this is caused by the settings of my phone. I should turn settings->location->use wireless networks on.
I am curious that why other app(e.g. google maps) can work well even when I turn this off. Because I never modify the settings of location before, and all other apps using location service in my phone works well. Is there some way to modify settings in code?

Just find out that there are lots of third-party libraries that works much better than the built-in location classes. Like baidu in china. Plz refer to this page:Wiki of baidu Location sdk

Related

Android LocationManager locationManager.requestLocationUpdates() not working

hi guys i am trying to get current location with location manager, i am using this below code
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider =locationManager.getBestProvider(criteria,true);
Location location =
locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0,this);
But i am not getting any response for this line
locationManager.requestLocationUpdates(bestProvider, 20000, 0,this);
and also getting lastknown location as null, i have added all permissions in manifest as well as dynamic, but this above line is not giving any response, i searched for it but dint get and relevant answer , please help.
For the getLastKnownLocation method, it is said in the documentation :
If the provider is currently disabled, null is returned.
Which means your GPS is disabled.
For the requestLocationUpdates, you are requesting a location every 20 seconds, try to decrease this number so you know at least if your program is working.
You can try this :
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Also I really advise you to use the new API to request location updates : https://developer.android.com/training/location/receive-location-updates.html
It is very fast and accurate, but you need to create a google developer account (for free) and create an api key. All needed information should be in the link.
String bestProvider =locationManager.getBestProvider(criteria,true);
In the above line, the second boolean parameter is true. That means it will fetch the provider which is enabled. And you the GPS_PROVIDER is disabled which is validated by the fact that locationManager.getLastKnownLocation returns null.
Moreover, since your Criteria for requesting BestProvier is empty so you must be getting "passive" as your BestProvider. Which means you will receive location updates only when other applications request and receives updates.
To get real location updates in onLocationChangedMethod() of your class. You must ensure these things:
Make sure that you have either one of ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION and then request it in runtime too, which you say you have already done.
If you want to request location through GPS_PROVIDER then you need to make sure that GPS_PROVIDER is enabled you can do that using below code:
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // OR some other PRIORITY depending upon your requirement
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient,
builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can
// Request for location updates now
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
status.startResolutionForResult(YourActivity.this, 100); // First parameter is your activity instance
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way
// to fix the settings so we won't show the dialog.
Log.e("TAG", "Error: Can't enable location updates SETTINGS_CHANGE_UNAVAILABLE");
break;
}
}
});
LocationManager.NETWORK_PROVIDER need network, but it is real, not precise.
if you want to use LocationManager.GPS_PROVIDER, the situation must be outdoor instead of indoor, because GPS location need satellite, if you are in any building, the satellite cannot find you!
pleasle go outdoor and check with GPS_PROVIDER again!
*best approach is getting location from both of GPS and NETWORK and check any of then that was not null and more accurate useing it.

Simplest way to get rough user location in Android [duplicate]

Is it possible to get the current location of user without using GPS or the internet? I mean with the help of mobile network provider.
What you are looking to do is get the position using the LocationManager.NETWORK_PROVIDER instead of LocationManager.GPS_PROVIDER. The NETWORK_PROVIDER will resolve on the GSM or wifi, which ever available. Obviously with wifi off, GSM will be used. Keep in mind that using the cell network is accurate to basically 500m.
http://developer.android.com/guide/topics/location/obtaining-user-location.html has some really great information and sample code.
After you get done with most of the code in OnCreate(), add this:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You could also have your activity implement the LocationListener class and thus implement onLocationChanged() in your activity.
By getting the getLastKnownLocation you do not actually initiate a fix yourself.
Be aware that this could start the provider, but if the user has ever gotten a location before, I don't think it will. The docs aren't really too clear on this.
According to the docs getLastKnownLocation:
Returns a Location indicating the data from the last known location
fix obtained from the given provider. This can be done without
starting the provider.
Here is a quick snippet:
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;
public class UtilLocation {
public static Location getLastKnownLoaction(boolean enabledProvidersOnly, Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location utilLocation = null;
List<String> providers = manager.getProviders(enabledProvidersOnly);
for(String provider : providers){
utilLocation = manager.getLastKnownLocation(provider);
if(utilLocation != null) return utilLocation;
}
return null;
}
}
You also have to add new permission to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
No, you cannot currently get location without using GPS or internet.
Location techniques based on WiFi, Cellular, or Bluetooth work with the help of a large database that is constantly being updated. A device scans for transmitter IDs and then sends these in a query through the internet to a service such as Google, Apple, or Skyhook. That service responds with a location based on previous wireless surveys from known locations. Without internet access, you have to have a local copy of such a database and keep this up to date. For global usage, this is very impractical.
Theoretically, a mobile provider could provide local data service only but no access to the internet, and then answer location queries from mobile devices. Mobile providers don't do this; no one wants to pay for this kind of restricted data access. If you have data service through your mobile provider, then you have internet access.
In short, using LocationManager.NETWORK_PROVIDER or android.hardware.location.network to get location requires use of the internet.
Using the last known position requires you to have had GPS or internet access very recently. If you just had internet, presumably you can adjust your position or settings to get internet again. If your device has not had GPS or internet access, the last known position feature will not help you.
Without GPS or internet, you could:
Take pictures of the night sky and use the current time to estimate your location based on a star chart. This would probably require additional equipment to ensure that the angles for your pictures are correctly measured.
Use an accelerometer to track location starting from a known position. The accumulation of error in this kind of approach makes it impractical for most situations.
boolean gps_enabled = false;
boolean network_enabled = false;
LocationManager lm = (LocationManager) mCtx
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location net_loc = null, gps_loc = null, finalLoc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy())
finalLoc = net_loc;
else
finalLoc = gps_loc;
// I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
Here possible to get the User current location Without the use of GPS and Network Provider.
1 . Convert cellLocation to real location (Latitude and Longitude), using "http://www.google.com/glm/mmap"
2.Click Here For Your Reference
Have you take a look Google Maps Geolocation Api? Google Map Geolocation
This is simple RestApi, you just need POST a request, the the service will return a location with accuracy in meters.
It appears that it is possible to track a smart phone without using GPS.
Sources:
Primary: "PinMe: Tracking a Smartphone User around the World"
Secondary: "How to Track a Cellphone Without GPS—or Consent"
I have not yet found a link to the team's final code. When I do I will post, if another has not done so.
You can use TelephonyManager to do that .

Android using LocationManager Get Provider is "Passive" in My Moto G Android Phone

I need a little help with some information about LocationManager in Android. I'm using this code to get user's specific information depending on his location,but in My Device Motorola G I get provider="Passive" and also Location return Null My Motorola G is running on Latest Android Kit Kat(4.4) Android Os.
I also try this code in Other Devices so Provider is either Network Or GPS also find Location properly.
locationManager = (LocationManager) getSherlockActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 1000, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getSherlockActivity(), "Location not available", Toast.LENGTH_SHORT).show();
}
I know that this is somehow an old question. But hope my answer will help others as well.
The issue is not related to the used device, actually the issue is how we use the provided API.
In the following code snippet, you pass true for the enabledOnly flag while you just need to pass it as false and it will work correctly at this time.
Instead of :
provider = locationManager.getBestProvider(criteria, true);
To be:
provider = locationManager.getBestProvider(criteria, false);
To clear this point:
If we set this flag "enabledOnly flag" to true, this means to return the requested best provider based on our criteria from the enabled only providers which will return the Passive provider.
While, if we set it to false, this will mean to return the requested best provider based on our criteria even if it is not enabled, which will return gps.
Btw, I am using Moto G too -but it's 2nd Gen- , and it worked with me this way :)
Hope this helps :)
READ THIS IF YOUR APP SUPPORTS kITKAT(4.4) VERSION OF ANDROID
I was having the same issue and my code was working perfectly in other devices not running kitkat,after a little bit of snooping around i found out that you have to explicitly turn on GPS to get location through wifi/gps. you can read about it here.
https://support.google.com/nexus/answer/3467281

getLastKnownLocations always returns null

I am unable to getLastKnownLocations on my Android device (Samsung Galaxy Note N7000) as it is always null, towers is detected as network so it is fine, anybody got any idea how to get my location?
d = getResources().getDrawable(R.drawable.songs_gray);
//Placing pinpoint at location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Toast.makeText(LocationActivity.this, "Towers: " + towers, Toast.LENGTH_SHORT).show();
Location location = lm.getLastKnownLocation(towers);
Toast.makeText(LocationActivity.this, "Location: " + location, Toast.LENGTH_SHORT).show();
if(location !=null){
lat = (int) (location.getLatitude()*1E6);
longi = (int) (location.getLongitude()*1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
CustomPinpoint custom = new CustomPinpoint(d, LocationActivity.this);
custom.insertPinPoint(overlayItem);
overlayList.add(custom);
}else{
Toast.makeText(LocationActivity.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
}
Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
With getLastKnownLocation() you can only get a Location object when the specified location provider is active.
The documentation says:
Returns a Location indicating the data from the last known location
fix obtained from the given provider. This can be done without
starting the provider. Note that this location could be out-of-date,
for example if the device was turned off and moved to another
location.
If the provider is currently disabled, null is returned.
To detect the current position and not the last detected one you need to enable the location provider(s). This tutorial should help you to understand how to work with location providers as GPS and network.
the last known location is only available if the location has been determined by another app prior to your call. start maps or some other app and let it get a location lock. then run your app.
if you really need location in your app, you need to fall back to some other method, because you cannot depend on there being a last known location.
as a side note, ACCESS_MOCK_LOCATION isn't required here. from the docs,
Allows an application to create mock location providers for testing
Nevermind found out my problem! Just needed to on Google's Location Services on my phone

Fails to get the location on Android mobile

Actually my problem is sometimes i can get the location and sometimes i can't get the location on Android real device. I used following code for getting the location,
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
I need to get the location when my application starts up. I don't know why sometimes it fails. How to resolve this issue?
#jsmith commented on my quesion,
Increase your power requirements and make sure you test where you can
get a network or gps signal. If that helps, then it's simply a case of
the sensors not getting enough reception to know the location.
This is the right answer for my question. Now its working fine.
You forgot to request for 'Location Updates', use this function after declaring the LocationManager:
locationManager.requestLocationUpdates(provider, 0, 0, this);
and you have to let the class implements LocationListener then add this function:
public void onLocationChanged(Location location) {
//get the location here
}
If you don't want to get the location repeatedly, after you get the location you have to stop the 'Location Updates' this way:
locationManager.removeUpdates(this);
in case you want the application always listen for the 'Location Updates', you better request for updates in onResume() and remove the updates in onPause() & onDestroy()
Good Luck

Categories

Resources