How to resume Location access programmatically when app open - java

I developed a GPS app but it works correctly when location service turns off and again turn on. When getting GPS without location service turn off and again turn on GPS ,latitude and longitude are not correct. How can I fix it?
public void onLocationChanged(Location location) {
try {
latitute = location.getLatitude();
longitude = location.getLongitude();
accuracy = location.getAccuracy();
Provider = location.getProvider();
Toast.makeText(getContext(), "onLocationChanged: " + "Lat: " + latitute + "Lon: " + longitude, Toast.LENGTH_SHORT).show();
latituteField.setText(String.valueOf((double) latitute));
longitudeField.setText(String.valueOf((double) longitude));
txtaccuracy.setText(String.valueOf((double) accuracy));
txtprovider.setText(String.valueOf(Provider));
} catch (Exception e) {
}

Check in your onResume() method of your activity that Gps is enabled or not.
if Gps is not enabled then ask user to enable GPS/network in settings.
after Gps enable start your GPSTracker service to get location.
#Override
protected void onResume() {
super.onResume();
// Check if GPS is not enabled
if (!canGetLocation) {
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
}
}

Related

Getting the user's location in Android when the phone is locked

I am looking for a solution to get the user's location in a specific time-interval in Android API 17 (Android 4.2) and when the phone is locked.
I've already tried some different code, checked a lot tutorials and searched almost everywhere on the web. The solution might be there, but I think it's a combination of lack of experience with Android developing and interpreting the different right solutions and approaches.
At first I had some pretty basic code, which worked very well when the screen was turned on. Even in the background, the location got updated (as I could check via a Toast message with the longitude and latitude).
I used a Handler to do so:
public void locationRunnable() {
final Handler locationHandler = new Handler();
final int distanceDelay = 5000; // milliseconds
locationHandler.postDelayed(new Runnable(){
public void run() {
// code
mMap.clear();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
myLocation = locationManager.getLastKnownLocation(provider);
if (myLocation != null) {
latitudeCurrentPosition = myLocation.getLatitude();
longitudeCurrentPosition = myLocation.getLongitude();
}
currentPattern = shortTest;
Notification.Builder notificationBuilderChecking = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle("Test app")
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setContentText("Getting location!")
.setPriority(Notification.PRIORITY_MAX)
.setLights(0xffffffff, 200, 200)
.setVibrate(currentPattern);
Notification notification2 = notificationBuilderChecking.build();
NotificationManager notificationMngr2 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationMngr2.notify(NOTIFICATION_ID, notification2);
locationHandler.postDelayed(this, distanceDelay);
}
}, distanceDelay);
}
It's just a snippet and the purpose is that in the background, when the screen is locked, this will loop every 10 seconds. And it does. Even when the phone is locked, but only for about 3 times. After 3 times the timer goes up and the phone vibrates less frequent (Doze feature in the way?).
Also, the phone does vibrate, but the location isn't updated. When I unlock the phone with the app in the foreground, the location is still at the place when I locked the phone. After a while (10 seconds) it updates. I use a marker on the map to check.
Again: it works when the phone is unlocked.
Now I'm trying to use a Service, a Service (Intent Service), or a Broadcast Receiver, and start a new Thread, but I don't know how and nothing is working.
Some of the last code I have contains a not functioning Broadcast Receiver and the most recent code contains a AlarmManager:
public void getLocation(Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmIntent.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 30 seconds
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), 10000, pi);
context.getSystemService(Context.CONNECTIVITY_SERVICE);
mMap.clear();
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
myLocation = locationManager.getLastKnownLocation(provider);
latitudeCurrentPosition = myLocation.getLatitude();
longitudeCurrentPosition = myLocation.getLongitude();
LatLng latLngCurrent = new LatLng(latitudeCurrentPosition, longitudeCurrentPosition);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrent));
mMap.animateCamera(CameraUpdateFactory.zoomTo(distZoom));
currentPattern = shortTest;
showNotification(context);
mHereIAm = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitudeCurrentPosition, longitudeCurrentPosition))
.title(weAreHere)
.draggable(false)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker_iconv3)));
mHereIAm.setTag(0);
mHereIAm.showInfoWindow();
}
AndroidManifest permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
But at the long of 10000, Android Studio is telling me "Value will be forced up to 60000 as of Android 5.1; don't rely on this to be exact..." etc. So an AlarmManager isn't useful either.
With the last code, my app isn't even running anymore.
But still: vibrations and stuff still occur, but location updates don't.
In short:
I need some basic (at least, I think it just can't be so difficult, as the only problem is that it's not working when the screen is locked) code, that updates my location on a certain, variable interval.
Maybe I have to use a Handler/Runnable, start a new Thread, use a Service or a Broadcast Receiver. Maybe an AlarmManager may work as well, but I don't know how and which to use.
This is my first post. If anything misses or you guys need more information, please ask. I'm trying to be as precise as possible, without using to much overhead.
Edit 01
Can I use a Job Service to do so? - I've updated the API to 21, so I can make use of this service, but I don't know if that's the right solution I'm looking for? Got some great tutorials for the use of it.
Edit 02
Let me be more clear with less overhead: I am looking for a solution to get the user's current location when the device is locked: with an API, a Service, an IntentService, a BroadcastReceiver, ... - every tutorial tells me something different, even here at Stack Overflow I have troubles with finding the right solution.
I was able to use a Service as well as an Intent Service, but I cannot request any location updates, because of some errors, like:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.name.name/com.name.name.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(b‌​oolean)' on a null object reference - searching for a solution for this error, gives me another error later on, and on, and on... I got myself stuck in an error-loop and a lot of unnecessary code.
I hope there is a simple way to get the user's location and you guys could help me. Thanks again.
Edit 03
I've followed the instructions on this tutorial and the location is checking. See the following code:
public class LocationService extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// 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 LocationService(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 (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(LocationService.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
I've disabled Network location and only allowed GPS location for testing - tested both.
And my MapsActivity:
public void getLocation(){
gps = new LocationService(MapsActivity.this);
if(gps.canGetLocation()) { // gps enabled} // return boolean true/false
latitudeCurrentPosition = gps.getLatitude(); // returns latitude
longitudeCurrentPosition = gps.getLongitude(); // returns longitude
latLngCurrent = new LatLng(latitudeCurrentPosition, longitudeCurrentPosition);
Toast toastLatCur = makeText(getApplicationContext(), "Lat Current: " + latitudeCurrentPosition + "" ,Toast.LENGTH_SHORT);
toastLatCur.show();
Toast toastLongCur = makeText(getApplicationContext(), "Long Current: " + longitudeCurrentPosition + "" ,Toast.LENGTH_SHORT);
toastLongCur.show();
}
else {
gps.showSettingsAlert();
}
if(goToLocation){
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrent));
goToLocation = false;
if(firstStart){
mMap.animateCamera(CameraUpdateFactory.zoomTo(distZoom));
firstStart = false;
}
}
vibrateNotification();
}
When the screen is locked, the phone vibrates as I told in vibrateNotificatoin() - works perfectly every 10 seconds. But the location doesn't get updated! So a Service is not the right way to solve this. Help!
You should use the service to perform tasks which are needed to be done even when the application is not running. Give a try.

Android location distanceTo within proximity

I'm writing an app where a method is executed based on the users geo location. I'm using an Activity which implements LocationListener. Location latitude and longitude is stored in a database, and whenever the user gets within range of the current location, compared to the location stored, a method is executed.
My problem is that, the methods startTimer(), startTimer() is executed whenever the user moves around whithin the proximity. I want startTimer() to be executed once, whenever the user enters the area, and stopTimer() whenever the user exits the area.
So far i got this, but only seems to work when leaving the area:
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
Log.i("", "Latitude: " + latitude);
Log.i("", "Longitude: " + longitude);
if(activities != null) {
for (Activity activity : activities) {
Location newLocation = new Location(provider);
newLocation.setLongitude(activity.getLongitude());
newLocation.setLatitude(activity.getLatitude());
if(location.distanceTo(newLocation) > 15) {
activity.setInProximity(false);
stopTimer(activity.getId());
}
if (location.distanceTo(newLocation) <= 15 && !activity.isInProximity()) {
activity.setInProximity(true);
startTimer(activity.getId());
}
}
}
}
It looks like you are almost there/tried to implement this already - just missed the calls to your function in the first if statement (and also should be an if/else statement)
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
Log.i("", "Latitude: " + latitude);
Log.i("", "Longitude: " + longitude);
if(activities != null) {
for (Activity activity : activities) {
Location newLocation = new Location(provider);
newLocation.setLongitude(activity.getLongitude());
newLocation.setLatitude(activity.getLatitude());
if(location.distanceTo(newLocation) > 15 && activity.isInProximity()) {
activity.setInProximity(false);
stopTimer(activity.getId());
}
else if (location.distanceTo(newLocation) <= 15 && !activity.isInProximity()) {
activity.setInProximity(true);
startTimer(activity.getId());
}
}
}
}
where
void setInProximity(boolean status)
and
boolean isInProximity()
should be getters/setters to a private boolean data member of the Activity class you iterate through

Unable to get current GPS Location co-ordinates

I have been trying hard to get my current location's GPS co-ordinates but my app never locks on to a GPS satellite.
The GPS icon in the notification area just keeps on blinking.
Whereas I tried using Google Maps on Android (the pre-installed app) and that thing is able to lockon in approx 60 secs! In both of the cases my 3G data connection was switched on and working.
Update: I am using Android 2.3.3 (HTC Desire S (Factory installed OS; no updates applied)) Logcat output is here. Now this is without setting LocationUpdates()'s min time and min-distance between update to 0, 0.
Update #2: My earlier code is here(PasteBin Link).
Update #3: Now, I am getting a force close after displaying a Toast .."Available".. in on onStatusChanged().
Update #4: Finally..I got it to work.
--
So, is it like that the Google map's app uses some proprietary code for locking on to GPS signals? I have tried using various version of my code. Tried using criteria(s) but never got them to work with GPS. For me getting precise (~50ft accuracy) location co-ordinates through GPS is a must.
My Code:
public class LocationDemoActivity extends Activity implements LocationListener {
LocationManager locationManager;
StringBuilder builder;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000l, 50.0f, this);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(this);
locationManager = null;
Intent i = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
#Override
public void onLocationChanged(Location location) {
// builder = new StringBuilder();
double lati=location.getLatitude();
double longi=location.getLongitude();
double alti=location.getAltitude();
float acc=location.getAccuracy();
float speed=location.getSpeed();
long time=location.getTime();
System.out.println(lati);
System.out.println(longi);
System.out.println(alti);
System.out.println(acc);
System.out.println(speed);
System.out.println(time);
/*Toast.makeText(this, "Lati: " + lati,Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Long: " + longi,Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Alti: " + alti,Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Acc.: " + acc,Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Speed: " + speed,Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Time: " + time,Toast.LENGTH_SHORT).show();*/
builder.append("Longitide: " + location.getLongitude());
builder.append('\n');
builder.append("Latitude: " + location.getLatitude());
builder.append('\n');
builder.append("Altitude: " + location.getAltitude());
builder.append('\n');
builder.append("Accuracy: " + location.getAccuracy());
builder.append('\n');
builder.append("TimeStamp:" + location.getTime());
builder.append('\n');
System.out.println(builder.toString());
Toast.makeText(this, builder.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
System.out.println("Provider Disabled:");
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
#Override
public void onProviderEnabled(String provider) {
System.out.println("Provider Enabled:");
Toast.makeText(this, "GPS is now enabled...", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
System.out.println("Status Changed: Out of Service");
Toast.makeText(this, "Status Changed: Out of Service",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
System.out.println("Status Changed: Temporarily Unavailable");
Toast.makeText(this, "Status Changed: Temporarily Unavailable",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.AVAILABLE:
System.out.println("Status Changed: Available");
Toast.makeText(this, "Status Changed: Available",
Toast.LENGTH_SHORT).show();
break;
}
}
}
Please do answer as it's quite urgent on me and any help is greatly appreciable :)
Thanks..
It seams pretty obvious that you won't get any Location updates, because you have set the minDistance to 50 meters or 164.042 ft. It appears you have confused this with accuracy.
The minDistance parameter is the minimum distance between location updates. So you would have to move at least 50 meters to get a location update.
Also make sure you have a clear view of the sky in order to have GPS signal.
Read more in the documentation
http://developer.android.com/reference/android/location/LocationManager.html
I asked a related question here.
To me looks like your GPS on the phone is not able to see the sat's. You need to get our of your office/home onto open air. In my case, I moved to NetworkProvider since GPS was just too clumsy.
Also note, that the parameters you give for distance and time are not literal, its the best guess that the api makes. So dont count on response times/distances from the API callback.
Do you have all these manifest permissions?
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
ACCESS_LOCATION_EXTRA_COMMANDS
ACCESS_MOCK_LOCATION
CONTROL_LOCATION_UPDATES
INTERNET

Get user current location and determine it in Google maps

i wan to ask you: i am using google Maps in my application and when i open the activity that has the map i want the user current location to be determine, i am using this code to retrieve the current user location
public void locat ()
{
//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
{
#Override
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();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}// End of Class MyLocationListener */
but it is just give me the latitude and longitude and that is not what i want! i want to determine the user current location in google maps!how can i do it ? do you need my code to google MAps? Please please help me! THANK YOU
If I understand your question correctly you want to get the users current position and show it on a map. You have the latitude and longitude values, all you need to do is construct a GeoPoint and animate to that position on the map. You can also add a custom overlay to the map if desired. Something like the following should help.
double lat = location.getLatitude();
double longi = location.getLongitude();
long time = location.getTime();
GeoPoint currentGeo = new GeoPoint(toMicroDegrees(lat), toMicroDegrees(longi));
MapController controller = map.getController();
controller.animateTo(currentGeo);
You are never actually passing the information to a map in order to display the location.
What you need to do is get the MapView from the layout you displaying.
Then get the controller of the map view and set the users location as the centre/animate to their location.
Something similar to this:
mapView1 = (MapView) this.findViewById(R.id.map);
MapController mapControl = mapView1.getController();
GeoPoint geo = new GeoPoint((int)(lat)*1e6), (int(long*1e6));
mapControl.animateTo(geo);
This link should help http://mobiforge.com/developing/story/using-google-maps-android
You can open google maps with a geo uri like so:
String url = "geo:48.200927,16.369548,192";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Edit: It appears that you want reverse geocoding. Here is an example:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Here is the documentation for the android Geocoder class - http://developer.android.com/reference/android/location/Geocoder.html

Android - Unable to get the gps location on the emulator

i'm tring to use the gps on the android emulator, i've the following code:
public class NL extends Activity {
private LocationManager locmgr = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nl);
locmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locmgr.getBestProvider(crit, true);
Location loc = locmgr.getLastKnownLocation(provider);
Toast msg = Toast.makeText(this, "Lon: " + Double.toString(loc.getLongitude()) + " Lat: " + Double.toString(loc.getLatitude()), Toast.LENGTH_SHORT);
msg.show();
}
}
i've added the following line at the manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and i've set the gps location with the DDMS method and either with the geo fix method, but when i run the code, i get a NullPointerExeption at the Toast line, probably cause loc is null.
I don't understand where the error is... can you help me please?
UPDATE!
Thanks for your help, now i use the following code and i don't get any error, but it doesn't run the code inside onChangeLocation... it doesn't run the Toast and don't return any message in the log!
public class NL extends Activity {
private LocationManager locmgr = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nl);
locmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location loc) {
// Called when a new location is found by the network location provider.
Log.i("NOTIFICATION","onLocationChenged Triggered");
Toast msg = Toast.makeText(NetworkLocator.this, "Lon: " + Double.toString(loc.getLongitude()) + " Lat: " + Double.toString(loc.getLatitude()), Toast.LENGTH_SHORT);
msg.show();
}
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
locmgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
Thanks!
Emulator just doesn't have any location at the beginning. According to the doc, 'getLastKnownLocation' method can return null, so it is ok. In that case you should wait for location updates (you can user requestLocationUpdates method from LocationManager). You can trigger location update on emulator's gps module by following command:
adb -e emu geo fix 50 50
FOUND THE SOLUTION:
LocationManager.NETWORK_PROVIDER is WRONG.
correction: LocationManager.GPS_PROVIDER
if all you what you described is done than maybe you are not probably not ur gps is on in emulator.go to setting:->Location and Security:->and use gps satelites should be checked
edited:ithink you have to use location manager without criteria type.
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
loc=mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
------than try to get long. and lat.
Are you sure that your emulated device is actually supporting GPS?
I think there was an extra option for this...
This may help too:
Thanks! To all: You can change the Build Target for your project any time in Eclipse: Right-click the project in Package Explorer, select Properties > Android and then check 'Google API' for Project Target. -- Developers working with non-English culture settings might notice that pressing the Send button in Location Controls does not send a new location to the Android emulator. It's fixed with the upcoming release 7 of the SDK tools; for a quick fix you can change your locale to 'en'. (See code.google.com/p/android/issues/detail?id=915 for details.) – Patrick de Kleijn
source: GPS on emulator doesn't get the geo fix - Android

Categories