Can't Create ClusterManager For Android Google Maps - java

I'm trying to use Google Maps clustering in my Android project.
Currently for a start I actually copied the code from the demo
https://github.com/googlemaps/android-maps-utils
(which runs fine for me)
On my project, however, on
mClusterManager = new ClusterManager<MyItem>(this, getMap());
it throws:
java.lang.ClassCastException: android.widget.ImageView cannot be cast to com.google.maps.android.ui.RotationLayout
I can't even figure out what why is any there casting?
Basically took the activity (and all needed related classes) from
https://github.com/googlemaps/android-maps-utils/blob/master/demo/src/com/google/maps/android/utils/demo/BigClusteringDemoActivity.java
public class ClusteringDemoActivity extends BaseDemoActivity {
private ClusterManager<MyItem> mClusterManager;
#Override
protected void startDemo() {
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.503186, -0.126446), 10));
mClusterManager = new ClusterManager<MyItem>(this, getMap());
getMap().setOnCameraChangeListener(mClusterManager);
try {
readItems();
} catch (JSONException e) {
Toast.makeText(this, "Problem reading list of markers.", Toast.LENGTH_LONG).show();
}
}
private void readItems() throws JSONException {
InputStream inputStream = getResources().openRawResource(R.raw.radar_search);
List<MyItem> items = new MyItemReader().read(inputStream);
mClusterManager.addItems(items);
}
public static void launch(Context context) {
context.startActivity(new Intent(context, ClusteringDemoActivity.class));
}
}
public abstract class BaseDemoActivity extends FragmentActivity {
private GoogleMap mMap;
protected int getLayoutId() {
return R.layout.map;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap != null) {
return;
}
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap != null) {
startDemo();
}
}
/**
* Run the demo-specific code.
*/
protected abstract void startDemo();
protected GoogleMap getMap() {
setUpMapIfNeeded();
return mMap;
}
}
public class MyItem implements ClusterItem {
private final LatLng mPosition;
public MyItem(double lat, double lng) {
mPosition = new LatLng(lat, lng);
}
#Override
public LatLng getPosition() {
return mPosition;
}
}
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
and have on my build.gradle
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.google.maps.android:android-maps-utils:0.3+'
Does anyone have any idea, please?

Incase this can help anyone -
I had in my own project a layout named text_bubble.xml
This clashed with a layout of the library, by the same name, and it caused the exception.
Simply renaming my layout resolved this.

Related

Cannot remove marker on Google Map (Java)

I have an application that will update the google map marker with the latest latitude and longitude from the real time Firebase. I have a problem with removing a markers on google maps, The problem is when there is a new marker appear on the map, the previous marker couldn't be removed. I tried to use GoogleMap.clear() but it seem like not working. Does anyone know what caused this issue ?Thanks !
My code
public class PoliceMapActivity extends FragmentActivity implements OnMapReadyCallback {
//initialize all variables
DatabaseReference reff;
GoogleMap map;
String RecordId;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_police_map);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.police_map);
supportMapFragment.getMapAsync(PoliceMapActivity.this);
//get record Id
RecordId = getIntent().getStringExtra("recordId");
reff = FirebaseDatabase.getInstance().getReference().child("Records");
Thread thread = new Thread() {
#Override
public void run() {
try {
while (isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// update onmapready()
if (supportMapFragment != null) {
supportMapFragment.getMapAsync(PoliceMapActivity.this);
if (marker != null) {
map.clear();
}
}
}
});
}
} catch (InterruptedException e) {
}
}
};
thread.start();
}
#Override
public void onMapReady(GoogleMap googleMap) {
map.clear();
final DatabaseReference finalreff = reff.child(RecordId);
finalreff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Double lat = (Double) snapshot.child("latitude").getValue();
Double lon = (Double) snapshot.child("longitude").getValue();
String name = snapshot.child("Fullname").getValue().toString();
LatLng latLng = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(latLng).title(getIntent().getStringExtra(name)));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
you may have invoked map.clear() on a different object and not on the googleMap instance you are showing in the code.
try to invoke googleMap.clear() in the method onDataChange

getMap to getMapAsync covert error

I never try Google Map. This is a client project where they use
compile project(':google-play-services_lib')
I have to improve their design to support the latest version of android that's way
compile 'com.android.support:appcompat-v7:25.1.1'
it shows me an error so I try this link.
It say It can be fixed by updating the Google Play Services dependency to 6.1.+. .
Then I use
compile 'com.google.android.gms:play-services:10.2.0'
to support latest version of android.
Then it shows me error getMap() so I convert it to getMapAsync() but what are duing is private static GoogleMap googlemap; then assign it like this:
googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
When i convert it to
googlemap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
It show me error. What to do
public class Frnt_mapActivity extends AppCompatActivity implements OnMapReadyCallback {//implements OnMapClickListener, OnMarkerDragListener {
public static double Shop_lat;
public static double Shop_lng;
public String Shop_title;
public String Shop_address;
public String Shop_icons;
ProgressDialog mDialog;
JSONObject jsonobject3;
JSONArray jsonarray3;
// Google Map
//private static GoogleMap googlemap;
public static EditText edit_search;
public static Button btn_search;
ArrayList<SearchBeams> getAllimgs;
// Location
ArrayList<String> world_locationlist;
ArrayList<LocationBeams> worldlocation;
// Looking for
ArrayList<String> looking_forlist;
ArrayList<LookingForBeams> world_looking_for;
public static ArrayList<SearchBeams> searchdata_list;
public static ArrayList<NormalSearchBeams> normlSearchList;
public static String mid;
public static String mpost_title;
public static String mimage;
public static List<String> imglist;
ArrayList<All_products_lat_long> venueList;
Spinner mySpinner2;
public static ArrayList<SearchBeams> GetIMG;
public static TextView txtlocation;
public static TextView txtlookingfor;
public static ArrayList<All_products_lat_long> mpItm;
String vals;
private int i;
private Intent intent;
HashMap<Marker, Integer> hashMap = new HashMap<Marker, Integer>();
public static LatLng latlong;
#Override
public void onMapReady(GoogleMap map) {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frnt_map_activity);
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mySpinner2 = (Spinner) findViewById(R.id.spin_looking_for);
// Spinner adapter
txtlookingfor = (TextView) findViewById(R.id.country);
txtlocation = (TextView) findViewById(R.id.rank);
SupportMapFragment mapFragment=getSupportFragmentManager().findFragmentById(R.id.places_map).getMapAsync(this);
googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
googlemap.setMyLocationEnabled(true);
googlemap.getUiSettings().setZoomControlsEnabled(true);
googlemap.getUiSettings().setMyLocationButtonEnabled(true);
googlemap.getUiSettings().setCompassEnabled(true);
googlemap.getUiSettings().setRotateGesturesEnabled(true);
googlemap.getUiSettings().setZoomGesturesEnabled(true);
googlemap.setMyLocationEnabled(true);
intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
i=hashMap.get(arg0);
intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
startActivity(intent);
//overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
}
});
new Frnt_mIcons_Activity().execute();
new LocationList().execute();
new LookingForList().execute();
edit_search = (EditText)findViewById(R.id.txt_search);
btn_search = (Button)findViewById(R.id.btn_search);
btn_search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text;
text=edit_search.getText().toString();
// text!=null &&
if(text.equals("") && text.startsWith(" ")==false){
new GetSearch_data().execute();
/*new Get_normal_search().execute();
edit_search.setText("");*/
}else
new Get_normal_search().execute();
edit_search.setText("");
//new GetSearch_data().execute();
}
});
}
They are calling googlemap and also adding marks. how i can implement it
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try{
if(bd!=null){
Marker marker=googlemap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
.title(venue.getPost_title())
.icon(bd));
hashMap.put(marker, k);
}
}catch (Exception e){
e.printStackTrace();
}
}
switch (Integer.parseInt(venueList.get(k).getId()))
{
case 5689 :
Marker marker=googlemap.addMarker(new MarkerOptions()
.position(new LatLng(la, ln))
.title(venueList.get(k).getPost_title())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.fruitandveg)));
hashMap.put(marker, k);
break;
case 5779 :
Marker marker1=googlemap.addMarker(new MarkerOptions()
.position(new LatLng(la, ln))
.title(venueList.get(k).getPost_title())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.coffee)));
hashMap.put(marker1, k);
break;
.....}
This is a client project where they use compile project(':google-play-services_lib')
So, you replace that with this (notice the -maps)
compile 'com.google.android.gms:play-services-maps:10.2.0'
Then it shows me error getMap() so I convert it to getMapAsync()
Which is correct, but
You really should not have a static map variable. If there are static variables all over the app, something is wrong in the design.
When i convert it to googlemap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this); It show me error
Well, yes that'll error
1) getActivity() is not necessary. You already are in an Activity class
2) getSupportFragmentManager() will only be available if you extends AppCompatActivity (or FragmentActivity) in the class definition
3) getMapAsync(this) will not work unless you implements OnMapReadyCallback on the class definition.
If you do all that, then you will have something like
import com.google.android.gms.maps.OnMapReadyCallback;
public class YourActivity extends AppCompatActivity
implements OnMapReadyCallback {
private void SupportMapFragment mMapFragment;
// private GoogleMap mMap; // Commented so you don't use in onCreate
#Override
public void onMapReady(GoogleMap map) {
// this.mMap = map;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// TODO: call other map setup methods
}
// Inside onCreate
mMapFragment = getSupportFragmentManager().findFragmentById(R.id.map);
mMapFragment.getMapAsync(this);
// Don't do this in onCreate
// googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}

Google Maps How to - MY LOCATION Android - Crashing/NotWorking

Using Default Google Maps Activity from Android Studio and want to use MY Location displayed on a marker on a map plus the my location blue google button which is usually located bottom right.
Have looked over hundreds of examples and code and nothing is working.
package com.example.br.nightlyfegooglemap;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,OnInfoWindowClickListener,
OnMyLocationChangeListener, GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
private static final String STATE_IN_PERMISSION="inPermission";
private static final int REQUEST_PERMS=1337;
private boolean needsInit=false;
private boolean isInPermission=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (savedInstanceState==null) {
needsInit=true;
}
else {
isInPermission=
savedInstanceState.getBoolean(STATE_IN_PERMISSION, false);
}
onCreateForRealz(canGetLocation());
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_IN_PERMISSION, isInPermission);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults) {
isInPermission=false;
if (requestCode==REQUEST_PERMS) {
if (canGetLocation()) {
onCreateForRealz(true);
}
else {
finish(); // denied permission, so we're done
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
if (needsInit) {
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,-73.98180484771729));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
mMap.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
mMap.setOnInfoWindowClickListener(this);
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}
#Override
public void onMyLocationChange(Location lastKnownLocation) {
Log.d(getClass().getSimpleName(),
String.format("%f:%f", lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()));
}
private void onCreateForRealz(boolean canGetLocation) {
if (canGetLocation) {
if (readyToGo()) {
setContentView(R.layout.activity_maps);
MapFragment mapFrag=
(MapFragment)getFragmentManager().findFragmentById(
R.id.map);
mapFrag.getMapAsync(this);
}
}
else if (!isInPermission) {
isInPermission=true;
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMS);
}
}
private void addMarker(GoogleMap map, double lat, double lon,
int title, int snippet) {
map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
.title(getString(title))
.snippet(getString(snippet)));
}
private boolean canGetLocation() {
return(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)==
PackageManager.PERMISSION_GRANTED);
}
}
ERRORS
//CANNOT RESOLVE SYMBOLS FOR THESE
OnInfoWindowClickListener,
OnMyLocationChangeListener
new PopupAdapter
readyToGo
//REQUIRES PERMISSION
mMap.setMyLocationEnabled(true);
//DEPRECATED
mMap.setOnMyLocationChangeListener(this);

Changing map location from a thread in android

I am making an android app about locating friends on map. So far I have the map up and running, and the fused location also running but from a different class which extends thread so the app will keep listening to location changed throughout its life cycle.
I have a problem when I initialize the map, the problem is either the locationListener will keep working but the map won't load, or the map will load but the locationListener will take a long time to get a new location.
I also have a problem when sending the current location from the Thread activity to the map activity so i animate the camera to a new loaction.
Here is the error i get :
12-22 23:22:38.847 17339-17339/com.example.swampsoftware.blbmonitor
W/dalvikvm: threadid=1: thread exiting with uncaught exception
(group=0x41ee6300) 12-22 23:22:38.852
17339-17339/com.example.swampsoftware.blbmonitor E/AndroidRuntime:
FATAL EXCEPTION: main
java.lang.NullPointerException
at
com.example.swampsoftware.blbmonitor.Maps.gotoLocation(Maps.java:232)
at
com.example.swampsoftware.blbmonitor.GetLocation.onLocationChanged(GetLocation.java:81)
at
com.google.android.gms.location.internal.zzk$zzb.handleMessage(Unknown
Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
So the problem happens once the method "onLocationChanged" is called.
I believe that this is a thread caused problem, but I don't understand what is the problem nor how to fix it, here is the code i made :
Maps.class :
public class Maps extends FragmentActivity implements OnMapReadyCallback{
private GoogleMap mMap;
private Double locationLat;
private Double locationLng;
private Context context;
private static boolean isVisible;
// Defining parse object
ParseObject locationObject;
//Declaring Tabhost
TabHost tabHost;
public Maps() {
}
public Maps(Context context) {
this.context = context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isVisible = true;
setContentView(R.layout.activity_gpslocation);
// Initialize google map
initMap();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
// Initialize GoogleMap -> mMap
public void initMap() {
if (mMap == null) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} else {
Toast.makeText(getApplicationContext(), "Can't start map", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
// Method that saves current location
private void setCurrentLocation(Double lat, Double lng) {
locationLat = lat;
locationLng = lng;
}
// Get method for lng
public Double getLocationLat() {
return locationLat;
}
public Double getLocationLng() {
return locationLng;
}
// Method that animates the camera to a new location
public void gotoLocation(Location location) {
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 15);
mMap.animateCamera(update);
}
#Override
protected void onResume() {
super.onResume();
initMap();
isVisible = true;
}
#Override
protected void onPause() {
super.onPause();
isVisible = false;
}
protected void onDestroy() {
super.onDestroy();
isVisible = false;
}
public boolean getIsVisible() {
return isVisible;
}
// Method that is called when map is connected, initializes the locationRequest.
public void onConnected(Bundle bundle) {
}
And this is the Thread class that will keep listening to the new location using fused location :
GetLocation :
public class GetLocation extends Thread implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient googleApiClient; // Object that is used to connect to google maps API, must be built to use fused location
private LocationRequest locationRequest; //Object that requests a quality of service for location updates from fused location
public Context context;
public volatile boolean isRunning = true; // boolean to stop the thread loop
// Declaring location variables
private Double locationLat;
private Double locationLng;
// Declaring objects
private ParseData parseData;
private Maps maps = new Maps();
/***
* run method for thread
***/
public void run() {
//Initializing objects
parseData = new ParseData();
googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
googleApiClient.connect();
}
public void terminate() {
isRunning = false;
}
// Getters
public Double getLocationLat() {
return locationLat;
}
public Double getLocationLng() {
return locationLng;
}
/***
* Auto-generated methods
***/
#Override
public void onLocationChanged(Location location) {
if (!isRunning) {
googleApiClient.disconnect();
return;
} else if (location != null) {
locationLat = location.getLatitude();
locationLng = location.getLongitude();
parseData.GetLocationParse(locationLat, locationLng);
System.out.println(locationLat + " " + locationLng);
// Check is map is active
if(maps.getIsVisible()) {
System.out.println("Maps is in foreground");
maps.gotoLocation(location);
} else {
System.out.println("Maps isn't running");
}
}
}
#Override
public void onConnected(Bundle bundle) {
locationRequest = locationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(7000);
locationRequest.setFastestInterval(5000);
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
Thank you.

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.

Categories