谷歌地图v2 MapFragment在从后堆栈返回时非常滞后

2022-09-03 02:20:21

我正在开发一个使用v2的应用程序,我遇到了非常奇怪的行为。我创建了一个子类来处理一些自定义行为(处理s,调整菜单选项等),并且在首次加载时,它都可以很好地工作。然后,我将一个新的片段嵌入到我的活动中,将自定义推送到回堆栈上。但是,当我从背包中返回地图时,事情变得很奇怪。平移地图变得非常滞后(我们谈论的是~1 FPS),无论是手动拖动/缩放还是单击图钉引起的动画。然后,如果我与溢出菜单的任何部分进行交互,即使只是打开它并再次关闭它,滞后也会立即清除。似乎没有其他东西可以解决它(除了关闭/重新打开应用程序);与非溢出菜单项和导航抽屉进行交互没有任何帮助。我从来没有见过这样的东西,也找不到任何以前描述过类似问题的人。欢迎任何想法,建议和/或修复。MapFragmentMapFragmentMarkerMapFragment

在被问到之前,要回答几个问题:

  • 是的,我调用了我覆盖的所有生命周期方法的版本(,[我还返回了该方法的超级返回值],以及)。superonCreate()onCreateView()onDestroyView()
  • 据我所知,我正在正确清理地图。每次我刷新图钉时,我都会调用它们中的每一个,然后在地图上调用它们本身,我也在做所有这些操作。remove()clean()onDestroyView()

最后,作为参考,这是添加新片段的代码:

getFragmentManager().beginTransaction().replace(R.id.main_content_container, new JoinGroupFragment()).addToBackStack(null).commit();

当我完成它时,我只需调用:

getFragmentManager().popBackStack();

编辑:我不确定它会有多大帮助,但这是习惯:MapFragment

public class CustomMapFragment extends MapFragment {

    private static final String DIALOG_TAG = "CUSTOM_MAP_FRAGMENT_DIALOG";
    private static final int DEFAULT_ZOOM = 14;
    private static final int MARKER_ZOOM = 15;
    private static final int DEFAULT_PADDING = 80;
    private static final int ORANGE_THRESHOLD_MINUTES = 7;
    private static final int BLUE_THRESHOLD_MINUTES = 20;

    public static final String KEY_GROUP_NAME = "GROUP_NAME";
    public static final String KEY_GROUP_ID = "GROUP_ID";

    private TextView mGroupNameOverlay;
    private GoogleMap mMap;
    private ArrayList<Marker> mMarkers;
    private Marker mSelectedMarker;
    private ArrayList<Group> mAllGroups;
    private Group mCurrentGroup;
    private ArrayList<Location> mAllLocations;
    private boolean mMapReady;
    private String mUsername;
    private boolean mCenterOnUser;

    public CustomMapFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        mMarkers = new ArrayList<>();
        mAllLocations = new ArrayList<>();

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mUsername = prefs.getString(PreferenceUtils.KEY_USERNAME, null);
        mCenterOnUser = prefs.getBoolean(PreferenceUtils.KEY_CENTER_ON_ME, false);
        mSelectedMarker = null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup view = (ViewGroup)super.onCreateView(inflater, container, savedInstanceState);

        if (view != null) {
            // View should never be null; MapFragments have a FrameLayout as their top level parent
            mGroupNameOverlay = (TextView)inflater.inflate(R.layout.group_name_overlay, view, false);
            view.addView(mGroupNameOverlay);
        }

        Bundle results = ((MainActivity)getActivity()).getFragmentResults();
        if (results != null) {
            String name = results.getString(KEY_GROUP_NAME);
            String id = results.getString(KEY_GROUP_ID);
            if (!StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(id)) {
                mCurrentGroup = new Group(name, id);
                mAllGroups.add(mCurrentGroup);
            }
        }

        if (mCurrentGroup != null) {
            updateGroupNameOverlay(mCurrentGroup.getGroupName());
        }

        getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                    @Override
                    public boolean onMarkerClick(Marker marker) {
                        mSelectedMarker = marker;
                        getActivity().invalidateOptionsMenu();
                        return false;
                    }
                });
                mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                    @Override
                    public void onMapClick(LatLng latLng) {
                        mSelectedMarker = null;
                        getActivity().invalidateOptionsMenu();
                    }
                });
                populateMap(true, false);
            }
        });

        GetGroupsRequest request = new GetGroupsRequest();
        request.setListener(new GetGroupsRequestListener());
        RequestProcessor.getInstance(getActivity()).queueRequest(request);

        return view;
    }

    @Override
    public void onDestroyView() {
        mSelectedMarker = null;
        for (Marker marker : mMarkers) {
            marker.remove();
        }
        mMarkers.clear();
        mMap.clear();
        mMap = null;
        mMapReady = false;
        super.onDestroyView();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (mSelectedMarker == null) {
            inflater.inflate(R.menu.menu_map, menu);
        }
        else {
            inflater.inflate(R.menu.menu_marker, menu);
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.map_menu_refresh_pins:
                performLocationsRequest(false);
                return true;
            case R.id.map_menu_recenter_zoom:
                populateMap(true, true);
                return true;
            case R.id.map_menu_select_group:
                DialogFragment selectDialog = new DialogFragment() {

                    @Override
                    public Dialog onCreateDialog(Bundle savedInstanceState) {
                        String[] groups = new String[mAllGroups.size()];
                        for (int i = 0; i < groups.length; i++) {
                            groups[i] = mAllGroups.get(i).getGroupName();
                        }
                        return new AlertDialog.Builder(getActivity())
                                .setItems(groups, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (!mAllGroups.get(which).equals(mCurrentGroup)) {
                                            mCurrentGroup = mAllGroups.get(which);
                                            updateGroupNameOverlay(mCurrentGroup.getGroupName());
                                            performLocationsRequest(true);
                                        }
                                    }
                                })
                                .create();
                    }
                };
                selectDialog.show(getFragmentManager(), DIALOG_TAG);
                return true;
            case R.id.map_menu_join_group:
                getFragmentManager().beginTransaction().replace(R.id.main_content_container, new JoinGroupFragment()).addToBackStack(null).commit();
                return true;
            case R.id.map_menu_create_group:
                CreateDialogFragment createDialog = new CreateDialogFragment();
                createDialog.show(getFragmentManager(), DIALOG_TAG);
                return true;
            case R.id.map_marker_zoom:
                if (mSelectedMarker != null) {
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mSelectedMarker.getPosition(), MARKER_ZOOM));
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void performLocationsRequest(boolean autoZoom) {
        GetLocationsRequest request = new GetLocationsRequest(mCurrentGroup.getGroupId());
        request.setListener(new GetLocationsRequestListener(autoZoom));
        RequestProcessor.getInstance(getActivity()).queueRequest(request);
    }

    private void updateGroupNameOverlay(final String groupName) {
        if (mGroupNameOverlay != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (groupName == null) {
                        mGroupNameOverlay.setText(R.string.map_group_overlay_no_group);
                    }
                    else {
                        mGroupNameOverlay.setText(getString(R.string.map_group_overlay_group, groupName));
                    }
                }
            });
        }
    }

    private void populateMap(boolean zoom, boolean animate) {
        if (!mMapReady) {
            mMapReady = true;
        }
        else {
            CameraUpdate update = null;
            mSelectedMarker = null;
            for (Marker marker : mMarkers) {
                marker.remove();
            }
            mMarkers.clear();
            mMap.clear();
            if (mAllLocations.size() == 1) {
                Location location = mAllLocations.get(0);
                mMarkers.add(addMarker(location));
                update = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), DEFAULT_ZOOM);
            }
            else if (mAllLocations.size() > 1) {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();
                for (Location location : mAllLocations) {
                    mMarkers.add(addMarker(location));
                    if (mCenterOnUser) {
                        if (location.getUsername().equals(mUsername)) {
                            update = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), DEFAULT_ZOOM);
                        }
                    }
                    else {
                        builder.include(new LatLng(location.getLatitude(), location.getLongitude()));
                    }
                }
                if (!mCenterOnUser) {
                    update = CameraUpdateFactory.newLatLngBounds(builder.build(), DEFAULT_PADDING);
                }
            }

            if (update != null && zoom) {
                if (animate) {
                    mMap.animateCamera(update);
                }
                else {
                    mMap.moveCamera(update);
                }
            }
        }
    }

    private Marker addMarker(Location location) {
        String timestamp;
        long minutesOld = (new Date().getTime() - location.getLastReported()) / 60000;
        float hue = BitmapDescriptorFactory.HUE_RED;
        if (minutesOld < 1) {
            timestamp = getString(R.string.map_timestamp_just_now);
        }
        else if (minutesOld < 2) {
            timestamp = getString(R.string.map_timestamp_one_minute);
        }
        else {
            timestamp = getString(R.string.map_timestamp_n_minutes, minutesOld);
            if (minutesOld >= ORANGE_THRESHOLD_MINUTES) {
                hue = BitmapDescriptorFactory.HUE_ORANGE;
            }
            if (minutesOld >= BLUE_THRESHOLD_MINUTES) {
                hue = BitmapDescriptorFactory.HUE_BLUE;
            }
        }
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        return mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .icon(BitmapDescriptorFactory.defaultMarker(hue))
                .title(location.getUsername())
                .snippet(timestamp));
    }

    private class GetGroupsRequestListener extends RequestListener<GetGroupsResponse> {

        public GetGroupsRequestListener() {
            super(getActivity());
        }

        @Override
        protected void onRequestComplete(GetGroupsResponse response) {
            mAllGroups = response.getGroups();
            if (mAllGroups.size() > 0) {
                if (mCurrentGroup == null) {
                    mCurrentGroup = mAllGroups.get(0);
                    updateGroupNameOverlay(mCurrentGroup.getGroupName());
                }
                performLocationsRequest(true);
            }
        }
    }

    private class GetLocationsRequestListener extends RequestListener<GetLocationsResponse> {

        private boolean mmAutoZoom;

        public GetLocationsRequestListener(boolean autoZoom) {
            super(getActivity());
            mmAutoZoom = autoZoom;
        }

        @Override
        protected void onRequestComplete(GetLocationsResponse response) {
            mAllLocations = response.getLocations();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    populateMap(mmAutoZoom, false);
                }
            });
        }
    }
}

附言:我意识到劫持视图创建并以这种方式注入我自己的叠加可能不是最佳实践,但是对于它的价值,我试图注释掉该部分,但它并没有解决问题,所以我怀疑它是否相关。


答案 1

我遇到过类似的问题。假设我有带有子支持MapFragment的FracmentA。通过导航抽屉菜单,我调用要显示的对话框。此时,FragmentA中的子映射进入某种“背景模式” - 它大约每秒更新两次(我在此映射上有动画标记,因此这种行为对我来说是众所周知的)。此“背景”模式通过显示任何具有覆盖层的元素(例如对话框或 AppBar 菜单)来打开,并且在隐藏该元素时处于关闭状态。

在对话框中,我有列表,其中的项目正在启动片段替换事务,当单击时。此时,FragmentA正在被SfracmentB取代。下面是 OnClickListener 的代码片段:

final SmartFragment fragment = new SmartFragment();
FragmentManager supportFragmentManager = getActivity().getSupportFragmentManager();
supportFragmentManager
        .beginTransaction()
        .replace(R.id.fragment_container, fragment, SmartFragment.FRAGMENT_TAG)
        .addToBackStack(null)
        .commit();
dismiss();

但是,在我从backstack返回到FragmentA之后,保留的map将保持在“后台模式”中,即使这样对话框也不再存在。在事务之前移动dissmiss()语句没有帮助,它接缝就像对话框在执行所有代码之前不会关闭一样。因此,唯一合理的解决方案(除了直接在地图片段上打开“后台模式”,我找不到如何做)是延迟片段交易,直到对话真正被解除。正如我之前假设的那样,只有当OnClick(这是对话框的一部分)中的所有代码都执行时,它才会发生,因此我们需要使事务不是在它声明的实例上完成的,而是稍晚一点,将其放在Runnable中:

dismiss();
final SmartFragment fragment = new SmartFragment();
Handler handler = new Handler();
final FragmentManager supportFragmentManager = getActivity().getSupportFragmentManager();
handler.post(new Runnable() {
    @Override
    public void run() {
        supportFragmentManager
                .beginTransaction()
                .replace(R.id.fragment_container, fragment, StopsSmartFragment.FRAGMENT_TAG)
                .addToBackStack(null)
                .commit();
    }
});

为此,我们需要使我们的片段和支持FragmentManager最终确定。现在一切正常,地图的“后台模式”被关闭,如果你从backstack返回到FragmentA,地图就会正常工作。

如果有人知道如何直接关闭地图片段中的“背景模式”,请告诉,我会很高兴听到。


答案 2

我遇到了同样的问题。我有一个自定义片段,在xml中指定:SupportMapFragment

<fragment
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

我设法通过用以下片段替换此片段来解决此问题:MapView

<com.google.android.gms.maps.MapView
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

值得注意的是,与(您需要根据官方Google文档将所有生命周期方法从您的片段/活动转发到您的片段/活动)相比,需要更多的设置。MapView(Support)MapFragmentMapView


推荐