Google Maps v2 my location with Google Play - java

I would like to ask about a strange situation, that happened during usage of Google Maps API v2.
There is an error in logcat that says:
The Google Play services resources were not found. Check your project
configuration to ensure that the resources are included.
The things that I have:
Google Map is displayed perfectly along with markers - I have acquired relevant code from Google.
google-play-services.jar library is included perfectly with Eclipse
(project->properties->android->add...).
The checkboxes in Eclipse (project->properties->java build path->order build path) are all checked properly.
The code
GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
returns true.
This code is running at a device, Nexus 4, not emulator.
I am trying to invoke event, that would allow me to get current position by this class:
public class FindMyLocationManager implements LocationListener, LocationSource
{
private OnLocationChangedListener mListener;
private LocationManager locationManager;
private GoogleMap map;
private Context ctx;
private int intervalTime;
private int intervalDistance;
public void setMap(GoogleMap map)
{
this.map = map;
}
public int getIntervalTime()
{
return intervalTime;
}
public void setIntervalTime(int intervalTime)
{
this.intervalTime = intervalTime;
}
public int getIntervalDistance()
{
return intervalDistance;
}
public void setIntervalDistance(int intervalDistance)
{
this.intervalDistance = intervalDistance;
}
public FindMyLocationManager(Context mContext)
{
this.ctx = mContext;
locationManager = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void activate(OnLocationChangedListener listener)
{
mListener = listener;
isGooglePlayOk(); //returns true
if(isGPSAvailable())
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, intervalTime, intervalDistance, this);
}
else if(isCompassAvailable())
{
Log.d("DEBUG", "No GPS here");
}
else
{
Log.d("DEBUG", "Nothing here");
}
}
private boolean isGPSAvailable()
{
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public boolean isGooglePlayOk()
{
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(ctx);
if(isAvailable == ConnectionResult.SUCCESS)
{
Toast.makeText(ctx, "Can connect to Goolge Play", Toast.LENGTH_SHORT).show();
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable))
{
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, (Activity)ctx, 9001);
dialog.show();
}
else
{
Toast.makeText(ctx, "Can't connect to Goolge Play", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean isCompassAvailable()
{
PackageManager pm =
ctx.getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS);
}
#Override
public void deactivate()
{
locationManager.removeUpdates((android.location.LocationListener)this);
mListener = null;
}
public void restart()
{
locationManager.removeUpdates((android.location.LocationListener)this);
if(isGPSAvailable())
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, intervalTime, intervalDistance, this);
}
else if(isCompassAvailable())
{
Log.d("DEBUG", "No GPS");
}
else
{
Log.d("DEBUG", "Nothing at all");
}
}
// the compiler never enters here
#Override
public void onLocationChanged(Location location)
{
Toast.makeText(this.ctx, location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_LONG).show();
if(mListener != null)
{
mListener.onLocationChanged(location);
}
map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
#Override
public void onProviderDisabled(String arg0)
{
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0)
{
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{
// TODO Auto-generated method stub
}
}
And here is the usage of above code:
// this method is called in many places in the program, like onCreate of my view with map or onResume
private void setUpMapIfNeeded()
{
if(map == null)
{
map = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
if(map != null)
{
map.setMyLocationEnabled(true);
locationManager.setMap(map);
locationManager.setIntervalDistance(0);
locationManager.setIntervalTime(0);
map.setLocationSource(locationManager); //Here I apply the object from above class
//if(currentModel != null)
//currentModel = getCurrentModel(); TODO
//moveCameraInstantly(map.);
focusCamera();
fillMapWithMarkers(FindMyApplication.MAP_MARKER_MODELS);
}
}
}
UPDATE
So it seems that the error itself is harmless, but I still don't get the onLocationChanged event.
UPDATE 2
This code is based on How to get My Location changed event with Google Maps android API v2? .

If i understand correctly you have defined the location update method, but have not started requesting the location updates.
To send the request for location updates, create a location client and a request in onCreate():
protected void onCreate(Bundle savedInstanceState) {
...
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
}
Then connect it in onStart():
protected void onStart() {
...
mLocationClient.connect();
}
Then make the update request in onConnected():
public void onConnected(Bundle dataBundle) {
...
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
Here is a complete guide on how to do this correctly:
http://developer.android.com/training/location/receive-location-updates.html#StartUpdates
The Google Play services resources were not found. error is a common bug in the library.

if the map shows like it should then you did everything correctly, there is something in the library that is causing the problem that google needs to fix. I get this error in my app even when I dont use google maps.
since you have google play service you should be using the new location API and not the old one.
http://developer.android.com/training/location/index.html

EDIT
Also this piece of code seems suspicious:
if(map == null) {
map = <something new>;
if(map != null) {
<do thing>
}
}
Is your map always null before entering this method?
EDIT2
map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
Log.d("DEBUG", "setOnMyLocationChangeListener");
setUpMapIfNeeded();
}
});
if it doesn't work, then try also:
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public onCameraChange(CameraPosition cameraPosition) {
Log.d("DEBUG", "setOnCameraChangeListener");
setUpMapIfNeeded();
}
});
I need log results on this.

Related

Android / Java: GoogleApiClient won't connect

I coded an Android Game in Java using Android Studio. Now I want to exchange the players highscore online, via the GoogleApi. So I initialize a GoogleApiClient in my onCreate function:
googleApi = new GoogleApiClient.Builder(FullscreenActivity.this)
.addApi(Games.API)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.build();
Where googleApiis a public GoogleApiClient variable.
Then there are:
#Override
protected void onStart() {
super.onStart();
Log.e("Connected?", String.valueOf(googleApi.isConnected()));
googleApi.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d("ConnectionFailed", String.valueOf(result));
if (result.hasResolution()) {
try {
// !!!
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (IntentSender.SendIntentException e) {
googleApi.connect();
}
}
}
#Override
public void onConnected(Bundle bundle) {
if(!started){
started = true;
setContentView(new Game(this));
}
}
#Override
public void onConnectionSuspended(int i) {
if(!started){
started = true;
this.setContentView(new Game(this));
}
}
The output of onConnectionFailed(...) says: D/ConnectionFailed: ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{2b5bddee: android.os.BinderProxy#7d0328f}, message=null}
On my mobile the Google Play Games Login window showed up, and I logged in. Then a rotating progress circle was showing, and it disappeared. The onConnected(...) function never got called.
What to add/remove/edit?
This is most likely not a duplicate, because I did not find a working solution for several other questions, that equal in content.
During the signin process, there can be multiple calls to onConnectionFailed. Have you looked at the samples in GitHub: https://github.com/playgameservices/android-basic-samples/tree/master/BasicSamples ?
In the samples onConnectionFailed is implemented as:
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed");
if (mIsResolving) {
// The application is attempting to resolve this connection failure already.
Log.d(TAG, "onConnectionFailed: already resolving");
return;
}
if (mSignInClicked || mAutoStartSignIn) {
mSignInClicked = false;
mAutoStartSignIn = false;
// Attempt to resolve the connection failure.
Log.d(TAG, "onConnectionFailed: begin resolution.");
mIsResolving = resolveConnectionFailure(this, mGoogleApiClient,
connectionResult, RC_SIGN_IN, getString(R.string.signin_other_error));
}
updateUI();
}
And resolveConnectionFailure is:
public static boolean resolveConnectionFailure(Activity activity,
GoogleApiClient client, ConnectionResult result, int requestCode,
String fallbackErrorMessage) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(activity, requestCode);
return true;
} catch (IntentSender.SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
client.connect();
return false;
}
} else {
// not resolvable... so show an error message
int errorCode = result.getErrorCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(errorCode,
activity, requestCode);
if (dialog != null) {
dialog.show();
} else {
// no built-in dialog: show the fallback error message
showAlert(activity, fallbackErrorMessage);
}
return false;
}
}

Google map object showing NPE on older devices

I am using this piece of code to initialize the google map object:
googleMap = ( (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
It works fine on newer devices , but shows NPE on older devices.Please help!!
This is how I solved the NPE of google maps.
public class WBMapFragment extends LogoBaseFragment implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
private GoogleMap map;
private MapView mapView;
#Inject
private MapManager mapManager;
/*
* Define a request code to send to Google Play services This code is
* returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationClient mLocationClient;
#Inject
private IUserLocationProvider userLocation;
private BitmapDescriptor mapPin;
private BitmapDescriptor mapPinUsed;
private SupportMapFragment supportMapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true); //< -- very important line
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//I needed this for when I return to the fragment that contained the map
getChildFragmentManager().putFragment(outState, "supportFragment", supportMapFragment);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map, null);
if (savedInstanceState == null) {
if (supportMapFragment == null) {
supportMapFragment = SupportMapFragment.newInstance();
getChildFragmentManager().beginTransaction().add(R.id.mapCont, supportMapFragment,SupportMapFragment.class.getSimpleName()).commit();
}
}
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState !=null){
supportMapFragment = (SupportMapFragment) getChildFragmentManager().getFragment(savedInstanceState, "supportFragment");
map = null; //<very important to nullify the map, because the new instance of the map will not be the same
}
mLocationClient = new LocationClient(getActivity(), this, this);
}
/*
* Called when the Activity becomes visible.
*/
#Override
public void onStart() {
super.onStart();
// Connect the client.
if (isGooglePlayServicesAvailable()) {
mLocationClient.connect();
initMap();
}
}
public void initMap() {
if (map == null) {
map = (GoogleMap) supportMapFragment.getMap();
if (map == null) {
//this call is made several times, and on first tried map can be null
return;
}
}
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setZoomControlsEnabled(false);
map.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
if (location != null) {
userLocation.saveLocation(location);
}
}
});
}
#Override
public void onResume() {
super.onResume();
initMap();
updateAnnotations();
}
/*
* Called when the Activity is no longer visible.
*/
#Override
public void onStop() {
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
super.onStop();
}
/*
* Handle results returned to the FragmentActivity by Google Play services
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST:
/*
* If the result code is Activity.RESULT_OK, try to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK:
mLocationClient.connect();
break;
}
}
}
private boolean isGooglePlayServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates", "Google Play services is available.");
MapsInitializer.initialize(getActivity().getApplicationContext());
mapPin = BitmapDescriptorFactory.fromResource(R.drawable.envelope);
mapPinUsed = BitmapDescriptorFactory.fromResource(R.drawable.envelope_open);
return true;
} else {
//here google suggests to display an error dialog, but i found that this only cause problems , better show a toast instead
// Get the error dialog from Google Play services
// Dialog errorDialog =
// GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
// CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
// if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
// ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// errorFragment.setDialog(errorDialog);
// errorFragment.show(getActivity().getSupportFragmentManager(),
// "Location Updates");
// }
return false;
}
}
/*
* Called by Location Services when the request to connect the client
* finishes successfully. At this point, you can request the current
* location or start periodic updates
*/
#Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Location location = mLocationClient.getLastLocation();
if (location != null) {
updateAnnotations();
} else {
// makeText( "Current location was null, enable GPS on emulator!",
// Toast.LENGTH_SHORT);
}
}
private Marker addMarker(GoogleMap map, double lat, double lon, String title, String snippet, boolean isWon) {
MarkerOptions options = new MarkerOptions().position(new LatLng(lat, lon)).title(title).snippet(snippet);
if (isWon) {
options.icon(mapPinUsed);
} else {
options.icon(mapPin);
}
Marker marker = map.addMarker(options);
return marker;
}
private void addMarkerToMap(GoogleMap map, WBMarker beacon) {
addMarker(map, beacon.location.Lat, beacon.location.Lng, beacon.name, beacon.address, beacon.isWon);
}
private void updateAnnotations() {
mapManager.getBeaconData(new IBeaconDataReceivedListener() {
#Override
public void onBeaconDataReceived(List<WBMarker> data) {
if (data.size() > 0) {
map.clear();
}
Location loc = userLocation.getLocation();
LatLng userTarget = new LatLng(loc.getLatitude(), loc.getLongitude());
LatLngBounds.Builder builder = new LatLngBounds.Builder();
List<WBMarker> ret = closeAnnotations(data);
for (WBMarker beacon : data) {
addMarkerToMap(map, beacon);
}
builder.include(userTarget);
CameraUpdate update;
if (ret.size() == 0) {
update = CameraUpdateFactory.newCameraPosition(new CameraPosition(userTarget, 17, 0, loc.getBearing()));
} else {
for (WBMarker beacon : ret) {
builder.include(new LatLng(beacon.location.Lat, beacon.location.Lng));
}
update = CameraUpdateFactory.newLatLngBounds(builder.build(), 50);
}
map.animateCamera(update);
}
});
}
private List<WBMarker> closeAnnotations(List<WBMarker> data) {
Location userLoc = userLocation.getLocation();
List<WBMarker> ret = new ArrayList<WBMarker>();
for (WBMarker beacon : data) {
Location loc = beacon.location.getLocation();
float dist = loc.distanceTo(userLoc);
if (dist < 50000.0f) {
ret.add(beacon);
}
}
return ret;
}
/*
* Called by Location Services if the connection to the location client
* drops because of an error.
*/
#Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(getActivity(),"Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects. If the error
* has a resolution, try sending an Intent to start a Google Play
* services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
}
}
}
Old answer:
I also ran into this problem. you should make this call in onResume only! as the map may not be ready before then
You should also call
MapsInitializer.initialize(getActivity().getApplicationContext());
and
GooglePlayUtils.isGooglePlayServicesAvailable(context)
before calling for the map

Showing my track with Google map api v2 in android

I am trying to make an app that will show my current location and will track me from there with a line.I have been using Google maps Api v2 for android so i was trying to work with polylines to help me show my tracks but its not showing.
Can anyone help me with that..Thankyou.
Total code is provided.
public class MainActivity extends FragmentActivity implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener,
OnMyLocationButtonClickListener, OnClickListener, android.location.LocationListener {
private GoogleMap mMap;
private LocationClient mLocationClient;
private TextView mMessageView;
private boolean setIt;
// These settings are the same as the settings for the map. They will in fact give you updates
// at the maximal rates currently possible.
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_demo);
mMessageView = (TextView) findViewById(R.id.message_text);
Button b1=(Button)findViewById(R.id.start);
Button b2=(Button)findViewById(R.id.stop);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
getApplicationContext(),
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
/**
* Button to get current Location. This demonstrates how to get the current Location as required
* without needing to register a LocationListener.
*/
public void showMyLocation(View view) {
if (mLocationClient != null && mLocationClient.isConnected()) {
String msg = "Location = " + mLocationClient.getLastLocation();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (v.getId() == R.id.start) {
setIt = true;
};
if (v.getId() == R.id.stop) {
mMap.clear();
};
}
PolylineOptions rectOptions = new PolylineOptions().width(3).color(
Color.RED);
#Override
public void onLocationChanged(Location location) {
mMessageView.setText("Location = " + location);
rectOptions.add(new LatLng(location.getLatitude(), location.getLongitude()));
if (setIt == true){
mMap.addPolyline(rectOptions);
}
}
#Override
public void onConnected(Bundle connectionHint) {
mLocationClient.requestLocationUpdates(
REQUEST,
this); // LocationListener
}
/**
* Callback called when disconnected from GCore. Implementation of {#link ConnectionCallbacks}.
*/
#Override
public void onDisconnected() {
// Do nothing
}
/**
* Implementation of {#link OnConnectionFailedListener}.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
// Do nothing
}
#Override
public boolean onMyLocationButtonClick() {
{
setIt = true;
};
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
This is very easy to in Google Map API V2 . If you would like to do this then you can follow this reference link:
Go this stackoverflow link
This man already give useful solution. I have done the same way as this site told.
For your facility I have written the main things:
1.create a list of LatLng points such as:
List<LatLng> routePoints;
2.Add the route points to the list (could/should be done in a loop):
routePoints.add(mapPoint);
3.Create a Polyline and feed it the list of LatLng points as such:
Polyline route = map.addPolyline(new PolylineOptions()
.width(_strokeWidth)
.color(_pathColor)
.geodesic(true)
.zIndex(z));
route.setPoints(routePoints);
Try this and give feedback!!!

App starts searching for GPS right on app start, not when needed

I have an Android app that has Google Maps V2 as part of functionality.
I have
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
in my manifest, and everything else needed for maps to work.
My app starts not on the screen with maps.
Now the question is why does my phone (Galaxy Nexus, just in case) starts showing GPS icon in status bar right when app starts, but not when I get to the screen with maps and start to work with it? I don't need to track my location and use battery power when I'm not on maps screen.
For example What's App messenger also uses GPS for its map but the icon is showed only when you open the map screen, not right on the first activity that is launched.
Googled for couple of hours but found nothing at all.
Any help will be appreciated!
Edited:
MapActivity class
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.map_activity);
startGPS();
initMap();
mMapView = (MapView) findViewById(R.id.map_google_map);
mMapView.onCreate(null);
mGoogleMap = mMapView.getMap();
if (mGoogleMap != null) {
customizeGoogleMap();
loadAndFillMap();
}
}
private void startGPS() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
}
private void initMap() {
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
private void customizeGoogleMap() {
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.setMyLocationEnabled(true);
}
private void loadAndFillMap() {
new LoadAndFillMapTask().execute();
}
private class LoadAndFillMapTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
String address = Session.appData().getSelectedAddress();
mMapLocation = Api.getMapApi().getMapLocation(address);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
fillMap();
}
}
private void fillMap() {
// filling Google Map with markers etc.
}
#Override
public void onDestroy() {
super.onDestroy();
if (mMapView != null) {
mMapView.onDestroy();
}
mLocationManager.removeUpdates(mLocationListener);
}
After a while we found out that the problem was in Flurry SDK we were using in our project...
By default Flurry starts to report location right from app start. To turn it off we used:
FlurryAgent.setReportLocation(false);
... /_-
You'll have to implement the successive method of location-fetching: Using GPS(only if it is on), then Wifi, and then the data-connection. Also, apart from FINE_LOCATION, use the following too--
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
I'm not sure whether it is the best solution but I've used this approach.
In my starting activity I do like this:
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
if (GpsUtils.canToggleGps(this)) {
GpsUtils.turnGpsOff(this);
}
//...
}
And in my MapActivity:
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
if (GpsUtils.canToggleGps(this)) {
GpsUtils.turnGpsOn(this);
}
//...
}
#Override
public void onDestroy() {
super.onDestroy();
if (GpsUtils.canToggleGps(this)) {
GpsUtils.turnGpsOff(this);
}
//...
}
GPS icon in status bar doesn't bother me anymore.

Android onLocationChanged and MainActivity class

I have the following code:
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
// called when the listener is notified with a location update from the GPS
Log.d("Latitude", Double.toString(loc.getLatitude()));
Log.d("Longitude", Double.toString(loc.getLongitude()));
}
#Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
}
#Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
and in my MainActivity
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Now, all I want is to receive the current position of the device ONCE to the MainActivity class (get altitude and longitude variables to use later in the application).
A. how do I stop receiving the location after a single time? The function lm.removeUpdates(listener) can only be called in the MainActivity class.
B. basically the same. How do I connect between the MyLocationListener class and the MainActivity one?
Sorry, I'm a newbie to Android and Java development.
And thanks!
You may use the following sample code:
public class LocationGetter {
private final Context context;
private Location location = null;
private final Cordinate gotLocationLock = new Cordinate();
private final LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
synchronized (gotLocationLock) {
LocationGetter.this.location = location;
gotLocationLock.notifyAll();
Looper.myLooper().quit();
}
}
};
public LocationGetter(Context context) {
if (context == null)
throw new IllegalArgumentException("context == null");
this.context = context;
}
public void getLocation(int maxWaitingTime, int updateTimeout) {
try {
final int updateTimeoutPar = updateTimeout;
synchronized (gotLocationLock) {
new Thread() {
public void run() {
Looper.prepare();
LocationResolver locationResolver = new LocationResolver();
locationResolver.prepare();
locationResolver.getLocation(context, locationResult, updateTimeoutPar);
Looper.loop();
}
}.start();
gotLocationLock.wait(maxWaitingTime);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
gteAddress ();
}
public double getLatitude() {
return location.getLatitude();
}
public double getLongitude() {
return location.getLongitude();
}
In your activity use:
_locationGetter=new LocationGetter(context);
_locationGetter.getLocation(200000000, 10000000);
_locationGetter.getLongitude();
_locationGetter.getLatitude();
You can also use LocationManager.removeUpdates after obtining the coordinates (and possibly checking if the coordinates are sufficient for your needs):
#Override
public void onLocationChanged(Location loc) {
// called when the listener is notified with a location update from the GPS
Log.d("Latitude", Double.toString(loc.getLatitude()));
Log.d("Longitude", Double.toString(loc.getLongitude()));
lm.removeUpdates(this);
}

Categories