I have an app that finds the users location (loading in a progress dialog) using GPS or network signal , when it finds it's location, the coordinates are written in a text view . If the GPS doesn't find a location in 40 sec or the user clicks on the cancel button , then the dialog closes. The problem is that if I click to cancel the dialog , it doesn't dismiss. However, if I click again, it dismisses. Why do I have to click twice ?!? Below is the source code:
public class MainActivity extends Activity {
private LocationControl locationControlTask;
private boolean hasLocation = false;
LocationHelper locHelper;
protected Location currentLocation;
private TextView myText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.mytext);
locHelper = new LocationHelper();
locHelper.getLocation(MainActivity.this, locationResult);
locationControlTask = new LocationControl();
locationControlTask.execute(this);
}
protected void onStart()
{
super.onStart();
// ....
new LocationControl().execute(this);
}
private class LocationControl extends AsyncTask<Context, Void, Void>
{
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute()
{
this.dialog.setMessage("Tap to cancel");
this.dialog.setTitle("Searching");
this.dialog.setCancelable(true);
this.dialog.setButton(Dialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == Dialog.BUTTON_NEGATIVE) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "dialog canceled", Toast.LENGTH_SHORT).show();
}
}
});
this.dialog.show();
}
protected Void doInBackground(Context... params)
{
//Wait 40 seconds to see if we can get a location from either network or GPS, otherwise stop
Long t = Calendar.getInstance().getTimeInMillis();
while (!hasLocation && Calendar.getInstance().getTimeInMillis() - t < 40000) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
return null;
}
protected void onPostExecute(final Void unused)
{
if(this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (currentLocation != null)
{
//useLocation();
String text = "lat:"+currentLocation.getLatitude()+" long:"+currentLocation.getLongitude();
myText.setText(text);
}
else
{
Toast.makeText(MainActivity.this, "location could not be found", Toast.LENGTH_SHORT).show();
//Couldn't find location, do something like show an alert dialog
}
}
}
public LocationResult locationResult = new LocationResult()
{
#Override
public void gotLocation(final Location location)
{
currentLocation = new Location(location);
hasLocation = true;
}
};
#Override
protected void onStop() {
locHelper.stopLocationUpdates();
locationControlTask.cancel(true);
super.onStop();
}
}
The location helper:
public class LocationHelper
{
LocationManager locationManager;
private LocationResult locationResult;
boolean gpsEnabled = false;
boolean networkEnabled = false;
public boolean getLocation(Context context, LocationResult result)
{
locationResult = result;
if(locationManager == null)
{
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
//exceptions thrown if provider not enabled
try
{
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch (Exception ex) {}
try
{
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch (Exception ex) {}
//dont start listeners if no provider is enabled
if(!gpsEnabled && !networkEnabled)
{
return false;
}
if(gpsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
//GetLastLocation();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location)
{
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extra) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location)
{
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extra) {}
};
private void GetLastLocation()
{
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
Location gpsLocation = null;
Location networkLocation = null;
if(gpsEnabled)
{ //if()
gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(networkEnabled)
{
networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
//if there are both values use the latest one
if(gpsLocation != null && networkLocation != null)
{
if(gpsLocation.getTime() > networkLocation.getTime())
{
locationResult.gotLocation(gpsLocation);
}
else
{
locationResult.gotLocation(networkLocation);
}
return;
}
if(gpsLocation != null)
{
locationResult.gotLocation(gpsLocation);
return;
}
if(networkLocation != null)
{
locationResult.gotLocation(networkLocation);
return;
}
//locationResult.gotLocation(null);
}
public void stopLocationUpdates() {
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
}
public static abstract class LocationResult
{
public abstract void gotLocation(Location location);
}
}
the xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/mytext"
android:textSize="15dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Main activity"/>
</LinearLayout>
and these 2 permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I would appreciate it if anyone would take a look at the bug.
I didn't do an in-depth analysis of your code, but you are starting the aysnc task in both onCreate and onStart. Remove it from one of those, because I suspect you simply have one dialog on top of the other.
Related
In my application's splash screen, I'm starting to listen the location via gps or network until my second activity opens.
my network location listener:
private LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
newLocationReceived(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
my gps location listener:
private LocationListener locationListenerGPS = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
newLocationReceived(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
Inside onCreate I call getLocation method, for permissions I use rxPermission:
#SuppressLint("MissingPermission")
private void getLocation() {
rxPermissions
.request(Manifest.permission.ACCESS_FINE_LOCATION)
.subscribe(granted -> {
if (granted) {
boolean gpsEnabled, networkEnabled;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gpsEnabled && locationListenerGPS != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, locationListenerGPS);
}
if (networkEnabled && locationListenerNetwork != null) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListenerNetwork);
}
}
} else {
Timber.e("LOCATION PERMISSION DENIED");
}
});
}
When new location is received I call:
private void newLocationReceived(Location location) {
if (locationManager != null) {
locationManager.removeUpdates(locationListenerNetwork);
locationManager.removeUpdates(locationListenerGPS);
}
locationManager = null;
this.location = location;
}
And in order to avoid memory leaks I call this method in onPause, onStop and onDestroy:
private void stopLocationListener() {
if (locationManager != null) {
locationManager.removeUpdates(locationListenerNetwork);
locationManager.removeUpdates(locationListenerGPS);
locationManager = null;
}
if (locationListenerNetwork != null) locationListenerNetwork = null;
if (locationListenerGPS != null) locationListenerGPS = null;
}
However, In order to LeakCanary I still get memory leaks in location manager. How can I resolve this? Also sometimes My splash screen passes the progresses too fast and my runtime permission can stay at background too
Hello I have a question for a class project app I am working on. I have a Notes app that pretty simply records text input from edit texts into a SQLite database and then retrieves each of them to a list fragment for the user to view. They can also click on each list item and that opens another fragment that displays the "details" of the entry, i.e. Subject, body content, time, and date entered. I want to make an addition that records user's current GPS/Network location for that particular entry (geotagging). I have a floating action button in the note details fragment that should link to a Map fragment with a marker on it corresponding to the location recorded when that entry was made. I'm fairly new to Android so still learning about all this. Just a bit hung up on this. Does anyone have a good explanation on how to save location into that same database (lat, long) when the entry is submitted, and then when the user clicks the FAB in details fragment, it displays a map with location marker for each respective entry? Please let me know if anyone can help, or if any of my database classes are needed?
Also want to add that I have indeed looked in quite a few places on Google, but I'm not quite sure if maybe I am using the wrong terminology or what, but results seems to be off for what I am looking for.
Here you have a class for getting the location:
public class MyLocation {
private static final int REQUEST_PERMISSIONS = 1;
private Timer timer1;
private LocationManager lm;
private LocationResult locationResult;
private boolean gps_enabled = false;
private boolean network_enabled = false;
private String[] permissions = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
public boolean getLocation(final Context context, LocationResult result) {
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
//don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
try {
boolean allPermissionsGranted = true;
for(int i=0; i<permissions.length;i++) {
if(!Utils.PermissionGranted(permissions[i], context)) allPermissionsGranted = false;
}
if(!allPermissionsGranted) {
ActivityCompat.requestPermissions((Activity)context, permissions, REQUEST_PERMISSIONS);
return false;
}
if (gps_enabled) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
});
}
if (network_enabled) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
});
}
} catch (SecurityException e) {
Utils.Toast(context, e.getMessage());
}
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 5000);
return true;
}
private LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if(gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc != null && net_loc != null){
if(gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc != null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc != null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
When you are about to add a new note just do:
MyLocation.LocationResult locationResult = new MyLocation.LocationResult(){
#Override
public void gotLocation(Location location){
mCurrentLocation = location;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Any UI related code
}
});
}
};
Then for the map:
Go to https://developer.android.com/training/maps/index.html. You have to add a marker for every location in your database.
I have an app that updating user location is the main feature of it.
So far I have a class that get users location through both GPS and NETWORK providers . It works just fine :
public class UserLocation {
private String TAG = "UserLocation";
Timer timer;
LocationManager locationManager;
OnLocationResultListener listener;
boolean gps_enabled = false;
boolean network_enabled = false;
public UserLocation setListener(OnLocationResultListener listener) {
this.listener = listener;
return this;
}
public boolean getLocation() {
if (locationManager == null) {
locationManager = (LocationManager) G.context.getSystemService(Context.LOCATION_SERVICE);
}
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Location GPS_PROVIDER is off");
ex.printStackTrace();
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Location NETWORK_PROVIDER is off");
ex.printStackTrace();
}
timer = new Timer();
timer.schedule(new GetLastLocation(), 0, GlobalConsts.LOCATION_RECHECK_TIME);
return true;
}
LocationListener gpslocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.e(TAG, "Calling gpslocationListener==> onLocationChanged");
timer.cancel();
listener.onGotLocation(location);
locationManager.removeUpdates(gpslocationListener);
locationManager.removeUpdates(networklocationListener);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.e(TAG, "Calling networklocationListener==> onLocationChanged");
timer.cancel();
listener.onGotLocation(location);
locationManager.removeUpdates(networklocationListener);
locationManager.removeUpdates(gpslocationListener);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
Log.e(TAG, "Getting last location in TimeTask ");
locationManager.removeUpdates(gpslocationListener);
locationManager.removeUpdates(networklocationListener);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
listener.onGotLocation(gps_loc);
else
listener.onGotLocation(net_loc);
return;
}
if (gps_loc != null) {
listener.onGotLocation(gps_loc);
return;
}
if (net_loc != null) {
listener.onGotLocation(net_loc);
return;
}
if (gps_loc == null && net_loc == null) {
Log.e(TAG, "tried to get location in Timetask but both location was null");
} else if (gps_loc == null) {
Log.e(TAG, "gps_loc is null in time task");
} else {
Log.e(TAG, "net_loc is null in time task");
}
listener.onGotLocation(null);
}
}
public interface OnLocationResultListener {
void onGotLocation(Location location);
void onNoLocationProvider();
}
}
The thing that I want is to get user location even if he is not using the app ( I mean getting his location when it changes , even if the app is not up and running)
What is the best approach to achieve this ?
Should I make a service and run this ?
How about using Google Play Location Api ? Does this help me ?
Thanks in advance.
Create this service which will always running in background even if your application is not running.
public class MyLocationService extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public MyLocationService() {
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this)
.build();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mGoogleApiClient.connect();
Toast.makeText(this, "Location services started", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onLocationChanged(Location location) {
System.out.println("MyLocationService.onLocationChanged");
// do your work here with location
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onDestroy() {
Toast.makeText(this, "Location services stopped", Toast.LENGTH_LONG).show();
Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mGoogleApiClient.disconnect();
super.onDestroy();
}
}
i need to find current location, either with network or gps.
i searched over internet and in stackoverflow but i cann't find what's wrong with this code.
i also set this parameter in manifest:
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
so here is my code:
LocationManager locationManager;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
findCurrentLocation();
//some other stuff here
}
public void findCurrentLocation()
{
boolean networkEnabled = false;
boolean gpsEnabled = false;
currentLocation = getLastKnownLocation();
if(currentLocation == null)
{
currentLocation = new Location("sometext");
locationFindDialog = ProgressDialog.show(this, "Find Your Location", "Please Wait", false);
try
{
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch(Exception e)
{
}
try
{
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception e)
{
}
if((networkEnabled == false) && (gpsEnabled == false))
{
locationFindDialog.dismiss();
showMessage("we need gps or sim card(or network) to find your location");
//show message
//you need at least one provider
return;
}
if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
}
if(gpsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
}
}
private final LocationListener networkLocationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
currentLocation.set(location);
//unregister listener
locationManager.removeUpdates(this);
locationManager.removeUpdates(gpsLocationListener);
locationFindDialog.dismiss();
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
private final LocationListener gpsLocationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
currentLocation.set(location);
//unregister listener
locationManager.removeUpdates(this);
locationManager.removeUpdates(networkLocationListener);
locationFindDialog.dismiss();
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
private Location getLastKnownLocation()
{
Location location = null;
List<String> providers = locationManager.getAllProviders();
for(String provider : providers)
{
location = locationManager.getLastKnownLocation(provider);
if(location != null)
{
return location;
}
}
return null;
}
no mater how much i wait, the app don't give me the location.
what's wrong with this code and how i can fix it?
finally i found a solution for this problem, the idea is finding cellId and lac manually, then send them to google secret API, and find latitude and longitude of cell tower, it's not too accurate (because it's cell tower location not user location), but enough for me.
refer to this address for more info:
http://sunil-android.blogspot.com/2013/01/convert-celllocation-to-real-location.html
I have the following class to get the user location.
public class GetUserLocation extends Activity {
Timer timer1;
LocationManager locationManager = null;
LocationResult locationResult;
boolean gpsEnabled = false;
boolean networkEnabled = false;
public static Location userLocation = null;
public String checkProviders(Context context) {
if (locationManager == null) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
gpsEnabled = false;
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
networkEnabled = false;
}
if(!gpsEnabled && !networkEnabled)
return "No Location Service Found.\nPlease turn on your location service by\nenabling GPS or Data Service or WI-FI";
if(gpsEnabled && !networkEnabled)
return "No Internet Service Found.\nPlease turn on your inernet service by\nenabling Data Service or WI-FI";
return null;
}
public boolean getLocation(Context context, LocationResult result) {
locationResult = result;
if (locationManager == null) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
// exceptions will be thrown if provider is not permitted.
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
// don't start listeners if no provider is enabled
if (!gpsEnabled && !networkEnabled)
return false;
if (gpsEnabled) {
locationManager.removeUpdates(locationListenerGps);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListenerGps);
}
if (networkEnabled) {
locationManager.removeUpdates(locationListenerNetwork);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,locationListenerNetwork);
}
timer1 = new Timer();
//timer1.schedule(new GetLastLocation(), 30000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
// class GetLastLocation extends TimerTask {
// #Override
// public void run() {
//
// locationManager.removeUpdates(locationListenerGps);
// locationManager.removeUpdates(locationListenerNetwork);
//
// Location networkLocation = null, gpsLocation = null;
// if (gpsEnabled) {
// //t = Calendar.getInstance().getTimeInMillis();
// gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// }
//
// if (networkEnabled) {
// networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// }
//
// // if there are both values use the latest one
// if (gpsLocation != null && networkLocation != null) {
//
// if (gpsLocation.getTime() > networkLocation.getTime())
// locationResult.gotLocation(gpsLocation);
// else
// locationResult.gotLocation(networkLocation);
//
// return;
// }
//
// if (gpsLocation != null) {
// locationResult.gotLocation(gpsLocation);
// return;
// }
//
// if (networkLocation != null) {
// locationResult.gotLocation(networkLocation);
// return;
// }
//
// locationResult.gotLocation(null);
// }
// }
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
public void removeUpdates() {
if(timer1!=null) {
timer1.cancel();
}
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
userLocation = null;
locationResult.gotLocation(null);
}
public Timer getTimer() {
return this.timer1;
}
}
This code is working good for other devices, but not in galaxy s3. But in the test S3 device the google map is getting the user location fix.
Can anyone say why is this happening? Any Hints will be appreciated.
I solved a problem like this, installing the APP GPS Status, that reset the GPS.
Solution found at:
http://productforums.google.com/forum/#!topic/maps/q24Cq4sQAtc%5B1-25-false%5D
OR just, try clearing the App Data from "Maps".
You'll then need to re-grant access to location services when prompted.
Hugs