当返回片段时,OnConnected没有调用

时间:2016-12-13 20:15:30

标签: google-maps android-fragments

我正在尝试从Android应用中获取用户位置。在应用程序中,选项卡上有三个片段。当我启动应用程序时,GoogleApiClient运行良好,地图会显示位置标记。但是当我更改选项卡并返回相关片段时,onResume被调用但是,onConnected永远不会再被调用。标记不出现。相关片段如下。为什么会这样?

public class MapListFragment extends RootFragment implements SearchView.OnQueryTextListener, AbsListView.OnScrollListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mainActivity = (MainActivity) getActivity();
    super.onCreate(savedInstanceState);


    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)
            .setFastestInterval(1 * 1000);


}



@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // inflat and return the layout
    View v = inflater.inflate(R.layout.fragment_location_list, container,
            false);

    /**********************mappart**********************/
   // final Location userLocation = getBestLocation();
    mMapView = (MapView) v.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);
    mMapView.onResume();// needed to get the map to display immediately

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }


    mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    LinearLayoutManager llm = new LinearLayoutManager(getActivity().getApplicationContext());
    mRecyclerView.setLayoutManager(llm);
    restaurants = new ArrayList<>();
    adapter = new RestaurantCardViewAdapter(getActivity(), restaurants, MapListFragment.this);
    mRecyclerView.setAdapter(adapter);
    viewCard = inflater.inflate(R.layout.card_view, null);

    return v;
}


    index.searchASync(query, new SearchListener() {
        @Override
        public void searchResult(Index index, Query query, JSONObject results) {
            List<Restaurant> resultss = null;
            try {
                resultss = resultsParser.parseResults(results);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (adapter != null && adapter.restaurants != null) {
                adapter.restaurants.clear();
                adapter.restaurants.addAll(resultss);
                adapter.notifyDataSetChanged();
                for (Restaurant r : resultss) {
                    LatLng location = new LatLng(r.get_geoloc().getLat(), r.get_geoloc().getLng());
                    final Marker marker = mGoogleMap.addMarker(new MarkerOptions().position(location).title(r.getName()).snippet("description"));
                    marker.setTag(r.getObjectID());
                    //marker.showInfoWindow();
                    mapmap.put(marker.getId(), r.getObjectID());
                    mGoogleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                        // Use default InfoWindow frame
                        @Override
                        public View getInfoWindow(Marker arg0) {
                            return null;
                        }

                        // Defines the contents of the InfoWindow
                        @Override
                        public View getInfoContents(Marker arg0) {

                            if (arg0.getTitle().equals("Current")) {
                                return null;
                            }

                            // Getting view from the layout file info_window_layout
                            //View v = inflater.inflate(R.layout.card_view, null);
                            TextView res_name = (TextView) viewCard.findViewById(R.id.restaurant_name);
                            TextView res_desc = (TextView) viewCard.findViewById(R.id.restaurant_desc);
                            res_name.setText(arg0.getTitle());
                            res_desc.setText(arg0.getSnippet());

                            // Returning the view containing InfoWindow contents
                            return viewCard;

                        }
                    });

                    mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
                        @Override
                        public void onInfoWindowClick(Marker marker) {
                            mainActivity.clickedRestaurantName = marker.getTitle();
                            //   String map_path = mapmap.get(marker.getId());
                            String map_path = marker.getTag().toString();
                            Log.i("firebase_db", map_path);
                            mainActivity.setLastResIdFirebaseKey(map_path);
                            Log.i("Resturant : ", mainActivity.clickedRestaurantName);
                            mainActivity.getBasketItemsMap().clear();
                            enterNextFragment();
                        }
                    });

                }
            }
        }

        @Override
        public void searchError(Index index, Query query, AlgoliaException e) {

        }
    });

@Override
public void onResume() {
    super.onResume();
    mGoogleApiClient.connect();
    mMapView.onResume();
    setUpMap();
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}


@Override
public void onConnected(Bundle bundle) {
    Boolean a = !hasPermission(Manifest.permission.ACCESS_FINE_LOCATION);
    if (!hasPermission(Manifest.permission.ACCESS_FINE_LOCATION))
    {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            //showExplanation("Permission Needed", "Rationale", Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_PERMISSION_FINE_LOCATION);
            requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_PERMISSION_FINE_LOCATION);
        } else {
            requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_PERMISSION_FINE_LOCATION);
        }
    }
        //return;

    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null)
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    else {
        handleNewLocation(location);
    }


    Log.d(TAG, "onConnected");
}


private void setUpMap() {
    if (mGoogleMap == null)
        mMapView.getMapAsync(new OnMapReadyCallback() {

            @Override
            public void onMapReady(GoogleMap googleMap) {
                mGoogleMap = googleMap;
            }
        });
}



private void handleNewLocation(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
    mGoogleMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title("Current")
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location)));
    setUpAlgolia(location);
    fillWithAlgoliaQuery();

}

@Override
public void onConnectionSuspended(int i) {
    Log.d(TAG, "onConnectionSuspended");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.d(TAG, "onConnectionFailed");
}

@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);

    Log.d(TAG, "onLocationChanged");
}

}

0 个答案:

没有答案