Bonjour !

J'ai quelques soucis avec l'API V2 Google Map, mon GoogleMap.OnMyLocationClickListener n'est jamais appelé !
Il y a quelques jours, j'avais un code qui fonctionnait bien lorsqu'il était présent dans l'android.app.Activity contenant la map :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.googleMap = googleMap;
 
        //Enable the location button
        googleMap.setMyLocationEnabled(true);
 
        //Bind the location button to googleApiClient
        googleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {
            //TODO Si cest la deuxieme fois de suite, on place le marker d'ajout
            if(googleApiClient != null){
                googleApiClient.connect();
            }
            return false;
            }
        }); 
    [...]
J'ai par la suite restructuré mon code en foutant toute la gestion de ma google map dans une classe à part. Tout fonctionne bien mis à part l'écoute du clique sur le bouton MyLocation.
Voici la même parti du code dans ma nouvelle classe "ActivitiesOnMapHelper":
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
public ActivitiesOnMapHelper(Context context, GoogleMap googleMap) {
        this.context = context;
        map = googleMap;
 
        map.setMyLocationEnabled(true);
        map.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {
                //Double click ?
                if(lastCameraPosition == map.getCameraPosition()){
                    createAddActivityMarker(map.getCameraPosition().target);
                }
                else if(apiLocation != null){
                    //TODO Prefer a FusedLocationProviderApi.requestLocationUpdates(...)
                    apiLocation.connect();
                }
                return false;
            }
        }); 
    [...]
sachant que j'appel le constructeur dans mon android.app.Activity lorsque la map est prête :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
 
    @Override
    public void onMapReady(GoogleMap googleMap) {
        activitiesOnMapHelper = new ActivitiesOnMapHelper(getApplicationContext(), googleMap); 
    [...]
J'ai une classe de modèle nommée Activity, c'est pour ça que je vous parle d'android.app.Activity

Voici le code en entier des deux classes :

"public class NearActivities extends android.app.Activity implements OnMapReadyCallback"
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package fastandfurious.fr.mobileactivite.controllers;
 
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;
 
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
 
 
import fastandfurious.fr.mobileactivite.R;
import fastandfurious.fr.mobileactivite.helper.ActivitiesOnMapHelper;
import fastandfurious.fr.mobileactivite.helper.App;
 
/**
 * This class allow the user to see activities around a specific address or himself.
 * TODO For the moment, the class shows all the activities in the database. We'll add location capabilities later.
 */
public class NearActivities extends android.app.Activity implements OnMapReadyCallback {
 
    //Request key for android.app.Activity call
    private final int REQUEST_DETAIL_ACTIVITY = 1;
    private final int REQUEST_CREATE_ROOT_PROFILE = 2;
 
 
    private App application;
    private ActivitiesOnMapHelper activitiesOnMapHelper;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.near_acitivities);
 
        application = (App) getApplication();
 
        //If the root user doesn't exist, the user need to create his profile
        if(application.getRootUser() == null){
            Intent createRootProfile = new Intent(this, UserProfileEditorActivity.class);
            startActivityForResult(createRootProfile, REQUEST_CREATE_ROOT_PROFILE);
        }
 
        ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_DETAIL_ACTIVITY && resultCode == DetailActivity.ACTIVITY_DELETED){
            activitiesOnMapHelper.swapCursor(application.getDatabase().getActivities());
            Toast.makeText(this, getString(R.string.deletion_success), Toast.LENGTH_LONG).show();
        }
        else if(requestCode == REQUEST_CREATE_ROOT_PROFILE ) { //TODO resultCode
            //TODO Creation confirmation of root profile
        }else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_near_activities, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
 
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
 
        return super.onOptionsItemSelected(item);
    }
 
    @Override
    public void onMapReady(GoogleMap googleMap) {
        activitiesOnMapHelper = new ActivitiesOnMapHelper(getApplicationContext(), googleMap);
        activitiesOnMapHelper.setOnMarkerClickListener(new ActivitiesOnMapHelper.OnMarkerClickListener() {
            @Override
            public boolean onRegularMarkerClick(int activityID) {
                Intent detailActivity = new Intent(getApplicationContext(), DetailActivity.class);
                detailActivity.putExtra(DetailActivity.ACTIVITY_ID, activityID);
                startActivityForResult(detailActivity, REQUEST_DETAIL_ACTIVITY);
                return false;
            }
 
            @Override
            public boolean onAddActivityMarkerClick(LatLng position) {
                //TODO start EditActivity with some fields pre-filled
                return false;
            }
 
            @Override
            public void onLoadFromMarkerClick(LatLng position) {
                activitiesOnMapHelper.swapCursor(application.getDatabase().getActivities());
            }
        });
 
        SearchView address_sv = (SearchView) findViewById(R.id.address_sv);
        address_sv.setVisibility(View.VISIBLE);
        activitiesOnMapHelper.bindSearchView(address_sv);
    }
}
"public class ActivitiesOnMapHelper"
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package fastandfurious.fr.mobileactivite.helper;
 
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SearchView;
import android.widget.TextView;
 
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
 
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
 
import fastandfurious.fr.mobileactivite.R;
import fastandfurious.fr.mobileactivite.model.SimpleAddress;
 
/**
 * This class controls and organizes a map created for activities handling.
 * TODO : add https://developers.google.com/maps/documentation/android/utility/marker-clustering
 * TODO : Link onMyLocationClickListener
 */
public class ActivitiesOnMapHelper {
 
    //Size used for marker icons construction
    private final int MARKER_WIDTH = 70;
    private final int MARKER_HEIGHT = 80;
    private final Rect MARKER_CATEGORY_AREA = new Rect((97 * MARKER_WIDTH)/407, (82 * MARKER_HEIGHT)/477, ((97+240) * MARKER_WIDTH)/407, ((82+245) * MARKER_HEIGHT)/477);
 
    //Zoom for google map
    private final int ZOOM_LARGE_DISTRICT = 14;
 
    private Context context;
    private GoogleMap map;
    private GoogleApiClient apiLocation;
 
    //Cursor containing all the activities to show on the map
    private Cursor cursor;
 
    //Keep the link between a marker and his activity
    private HashMap<String, Integer> markerToActivityID = new HashMap<>();
 
    //The special marker to allow the user to create a new activity
    private Marker addActivityMarker;
 
    //The listener to invoke for actions on markers
    private OnMarkerClickListener onMarkerClickListener;
 
    //The last camera position (used for handling double click on MyLocation button
    private CameraPosition lastCameraPosition;
 
    public ActivitiesOnMapHelper(Context context, GoogleMap googleMap) {
        this.context = context;
        map = googleMap;
 
        map.setMyLocationEnabled(true);
        map.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {
                //Double click ?
                if(lastCameraPosition == map.getCameraPosition()){
                    createAddActivityMarker(map.getCameraPosition().target);
                }
                else if(apiLocation != null){
                    //TODO Prefer a FusedLocationProviderApi.requestLocationUpdates(...)
                    apiLocation.connect();
                }
                return false;
            }
        });
 
        map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }
 
            @Override
            public View getInfoContents(Marker marker) {
                return createInfoContentFor(marker);
            }
        });
 
        map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                if(onMarkerClickListener != null){
                    if(addActivityMarker != null && marker.getId().equals(addActivityMarker.getId())){
                        onMarkerClickListener.onAddActivityMarkerClick(marker.getPosition());
                    }
                    else {
                        onMarkerClickListener.onRegularMarkerClick(markerToActivityID.get(marker.getId()));
                    }
                }
            }
        });
 
        map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                createAddActivityMarker(latLng);
            }
        });
 
        map.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {
                return false;
            }
        });
 
        apiLocation = new GoogleApiClient.Builder(context)
                    .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {
                            Location location = LocationServices.FusedLocationApi.getLastLocation(apiLocation);
                            if(location != null){
                                map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), ZOOM_LARGE_DISTRICT));
                                lastCameraPosition = map.getCameraPosition();
                                if(onMarkerClickListener != null) {
                                    onMarkerClickListener.onLoadFromMarkerClick(new LatLng(location.getLatitude(), location.getLongitude()));
                                }
                            }
 
                            //TODO verify usage
                            //apiLocation.disconnect();
                        }
 
                        @Override
                        public void onConnectionSuspended(int i) {
 
                        }
                    })
                    .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult connectionResult) {
 
                        }
                    })
                    .addApi(LocationServices.API)
                    .build();
 
        if(apiLocation != null){
            apiLocation.connect();
        }
    }
 
    /**
     * Place an "addActivity" marker on the map
     * @param latLng The position where we want to place the marker
     */
    private void createAddActivityMarker(LatLng latLng){
        if(addActivityMarker != null) {
            addActivityMarker.remove();
        }
        addActivityMarker = getMap().addMarker(new MarkerOptions().position(latLng));
        addActivityMarker.showInfoWindow();
    }
 
    /**
     * Reload a new cursor containing activities for the map.
     * @param newCursor The cursor to load in the adapter.
     */
    public void swapCursor(Cursor newCursor){
        //We clear all
        map.clear();
        markerToActivityID.clear();
        cursor = newCursor;
        if(!cursor.moveToFirst()){
            return;
        }
 
        //Then we bind one by one all the activities with a marker.
        do{
            bindMarker();
        }while(cursor.moveToNext());
    }
 
    /**
     * Move the {@link #cursor} on the line containing activityID and return it
     * @param activityID The activityID that we need to target
     * @return The moved cursor
     */
    private Cursor getCursorAt(int activityID) {
        //Before searching with a loop, we verify that we aren't already on the good line.
        if(cursor.isAfterLast() || cursor.getInt(cursor.getColumnIndex(DatabaseContract.UserEntry.TABLE_NAME + "." + DatabaseContract.ActivityEntry._ID)) != activityID){
            boolean hasNext = cursor.moveToFirst();
            while(hasNext && cursor.getInt(cursor.getColumnIndex(DatabaseContract.UserEntry.TABLE_NAME + "." + DatabaseContract.ActivityEntry._ID)) != activityID){
                hasNext = cursor.moveToNext();
            }
        }
 
        return cursor;
    }
 
    /**
     * Create the info content view that correspond to this marker.
     * @param marker The marker used for create the content
     * @return The view created for the marker
     */
    private View createInfoContentFor(Marker marker){
 
        @SuppressLint("InflateParams")
        View view = LayoutInflater.from(getContext()).inflate(R.layout.map_item_activity, null);
 
        TextView title_tv = (TextView) view.findViewById(R.id.title_tv);
        TextView where_tv = (TextView) view.findViewById(R.id.where_tv);
        TextView information_tv = (TextView) view.findViewById(R.id.creator_tv);
 
        if(addActivityMarker != null && marker.getId().equals(addActivityMarker.getId())){
            title_tv.setText(R.string.create_activity_title);
            where_tv.setText(R.string.create_activity_information_l1);
            information_tv.setText(R.string.create_activity_information_l2);
        }
        else{
            Cursor cursor = getCursorAt(markerToActivityID.get(marker.getId()));
            title_tv.setText(cursor.getString(cursor.getColumnIndex(DatabaseContract.ActivityEntry.TABLE_NAME + "." + DatabaseContract.ActivityEntry.F_TITLE)));
 
            GregorianCalendar when = new GregorianCalendar();
            when.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(DatabaseContract.ActivityEntry.TABLE_NAME + "." + DatabaseContract.ActivityEntry.F_WHEN)));
            where_tv.setText(when.get(Calendar.DAY_OF_MONTH) + "/" + (when.get(Calendar.MONTH) + 1) + "/" + when.get(Calendar.YEAR));
 
            information_tv.setText(getContext().getString(R.string.proposed_by) + " " +
                    cursor.getString(cursor.getColumnIndex(DatabaseContract.UserEntry.TABLE_NAME + "." + DatabaseContract.UserEntry.F_FIRST_NAME)) + " " +
                    cursor.getString(cursor.getColumnIndex(DatabaseContract.UserEntry.TABLE_NAME + "." + DatabaseContract.UserEntry.F_LAST_NAME))
            );
        }
 
        return view;
    }
 
    //Bind an activity with a marker on map, processing marker for future needs
    private void bindMarker(){
        int activityID = cursor.getInt(cursor.getColumnIndex(DatabaseContract.UserEntry.TABLE_NAME + "." + DatabaseContract.ActivityEntry._ID));
 
        Bitmap markerIcon = constructBitmap(cursor.getInt(cursor.getColumnIndex(DatabaseContract.CategoryEntry.TABLE_NAME + "." + DatabaseContract.CategoryEntry.F_ICON_RESOURCE)));
 
        LatLng where = new LatLng(
                cursor.getDouble(cursor.getColumnIndex(DatabaseContract.ActivityEntry.TABLE_NAME + "." + DatabaseContract.ActivityEntry.F_LATITUDE)),
                cursor.getDouble(cursor.getColumnIndex(DatabaseContract.ActivityEntry.TABLE_NAME + "." + DatabaseContract.ActivityEntry.F_LONGITUDE))
        );
 
        Marker newMarker = map.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromBitmap(markerIcon))
                .position(where));
 
        markerToActivityID.put(newMarker.getId(), activityID);
    }
 
    /**
     * Allow to construct the marker icon containing a category icon
     * @param category_RESOURCE The category icon pointed by a resource to put in the output bitmap
     * @return The output bitmap containing the category icon
     */
    private Bitmap constructBitmap(int category_RESOURCE){
        Bitmap markerBM = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_marker);
        Bitmap categoryBM = BitmapFactory.decodeResource(context.getResources(), category_RESOURCE);
        Bitmap result = Bitmap.createBitmap(MARKER_WIDTH, MARKER_HEIGHT, Bitmap.Config.ARGB_8888);
 
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(
                markerBM,
                new Rect(0, 0, markerBM.getWidth(), markerBM.getHeight()),
                new Rect(0, 0, result.getWidth(), result.getHeight()),
                null);
        canvas.drawBitmap(
                categoryBM,
                new Rect(0, 0, categoryBM.getWidth(), categoryBM.getHeight()),
                MARKER_CATEGORY_AREA,
                null);
 
        return result;
    }
 
    public void bindSearchView(SearchView address_sv){
        new SearchAddressHelper(address_sv).setOnAddressSuggestedClickListener(new SearchAddressHelper.OnAddressSuggestedClickListener() {
            @Override
            public void onAddressSuggestedClick(SimpleAddress address) {
                createAddActivityMarker(new LatLng(address.getLatitude(), address.getLongitude()));
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(address.getLatitude(), address.getLongitude()), ZOOM_LARGE_DISTRICT));
            }
        });
    }
 
    private Context getContext(){
        return context;
    }
 
    private GoogleMap getMap(){
        return map;
    }
 
    public void setOnMarkerClickListener(OnMarkerClickListener onMarkerClickListener){
        this.onMarkerClickListener = onMarkerClickListener;
    }
 
    /**
     * Interface allowing this class to warn a listener when an action is made on an activity marker.
     */
    public interface OnMarkerClickListener {
        public boolean onRegularMarkerClick(int activityID);
        public boolean onAddActivityMarkerClick(LatLng position);
        public void onLoadFromMarkerClick(LatLng position);
    }
}
Si quelqu'un a une idée... J'ai l'impression de passer à coté de quelque chose d'évident !

Merci d'avance !