跳过 1492 帧!应用程序可能在其主要 thread.How 上做了太多工作以显示加载器,同时在应用程序中跳过帧?

Skipped 1492 frames! The application may be doing too much work on its main thread.How to show loader while skipping frames in app?

由于我是 android 的新手,我无法修复这个跳过的 1000 多帧 issue.Help 我来解决这个问题并帮助我在发生此跳过帧操作时添加加载进度条在打开地图之前。这是我的地图代码。

RouteMap.java

public class RouteMap extends android.support.v4.app.FragmentActivity
        implements OnClickListener, OnInfoWindowClickListener,
        DirecitonReceivedListener, OnMapReadyCallback {
    public List<String> destinations;
    ImageView img_home, img_menu;
    private GoogleMap mMap;
    ProgressDialog prgDialog;
    model modelData;
    private Button btnDirection;
    double latitude, longitude;
    LinearLayout linear_back;
    LatLng startPosition, start;
    String startPositionTitle;
    Vibrator vibrator;
    String startPositionSnippet;
    Double desc1_long, desc1_lat;
    LatLng destinationPosition1;
    String destinationPositionTitle;
    String destinationPositionSnippet;
    MarkerOptions mDestination1, mStart;
    ToggleButton tbMode;
    GPSTracker gps;
    Geocoder gCoder;
    ArrayList<Address> addresses = null;
    ArrayList<Address> adres2 = null;
    SupportMapFragment mapFragment;
    public final static double AVERAGE_RADIUS_OF_EARTH = 6371;
    TextView back_txt;
    openMap openMap;
    String mapStatus = "start";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route_map);
        back_txt = (TextView) findViewById(R.id.txt_back);

        try {
            back_txt = (TextView) findViewById(R.id.txt_back);
            modelData = model.getInstance();
            vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
            gps = new GPSTracker(RouteMap.this);
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            gCoder = new Geocoder(RouteMap.this);
            addresses = (ArrayList<Address>) gCoder.getFromLocation(latitude, longitude, 1);

            tbMode = (ToggleButton) findViewById(R.id.tbMode);
            mapFragment = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map));
            mapFragment.getMapAsync(this);
            btnDirection = (Button) findViewById(R.id.btnDirection);
            btnDirection.setOnClickListener(this);
            tbMode.setChecked(true);

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
        }

    }

    public int calculateDistance(double userLat, double userLng, double venueLat, double venueLng) {

        final int R = 6371;
        try {
            Double latDistance = deg2rad(venueLat - userLat);
            Double lonDistance = deg2rad(venueLng - userLng);
            Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                    + Math.cos(deg2rad(userLat)) * Math.cos(deg2rad(venueLat))
                    * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
            Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            double distance = R * c * 1000; // convert to meters

            double height = 0 - 0;
            distance = Math.pow(distance, 2) + Math.pow(height, 2);
            return (int) Math.sqrt(distance);
        } catch (Exception ex) {
            Toast.makeText(getApplicationContext(), "Please Check your Destination's GeoCode ", Toast.LENGTH_LONG).show();
        }
        return 0;
    }

    private double deg2rad(double deg) {return (deg * Math.PI / 180.0);}
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap=googleMap;
        //setUpMap();

        try {
            mMap.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;
            }
            mMap.setMyLocationEnabled(true);
            mMap.setIndoorEnabled(true);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
            mMap.getUiSettings().setCompassEnabled(true);
            mMap.getUiSettings().setAllGesturesEnabled(true);

            String[] arr = new String[modelData.outletList.size()];

            for(int i=0;i<modelData.outletList.size();i++)
            {
                String str1 = modelData.outletList.get(i)[2];
                String str2 = modelData.outletList.get(i)[3];
                String newString = str1+","+str2;
                arr[i] = newString;
            }
            String[] latTempArr = arr;
            String strKey = "";
            double curLatitude = latitude;
            double curLongtitude = longitude;
            double desLat;
            double desLng;

            Map<String, Integer> final_arr = new HashMap<String, Integer>();
            Map<String, Integer> final_arr2 = new HashMap<String, Integer>();
            List<Integer> intTempArr = new ArrayList<Integer>();
            List<Integer> intTempArr2 = new ArrayList<Integer>();

            for(int j=0;j<arr.length;j++)
            {
                intTempArr =  new ArrayList<Integer>();
                for (int k=0;k<latTempArr.length;k++)
                {
                    String[] arr_temp = latTempArr[k].split(",");
                    //System.out.println(arr_temp[0]);
                    desLat = Double.parseDouble(arr_temp[0]);
                    desLng = Double.parseDouble(arr_temp[1]);
                    int temp = calculateDistance(curLatitude,curLongtitude,desLat,desLng);
                    intTempArr.add(temp);

                    final_arr.put(latTempArr[k],temp);
                }

                Collections.sort(intTempArr);

                Integer[] array = new Integer[intTempArr.size()];
                intTempArr.toArray(array);

                for (Map.Entry<String, Integer> entry : final_arr.entrySet()) {

                    try{
                        if (entry.getValue().equals(array[0])) { //get next best path

                            List<String> list = new ArrayList<String>(Arrays.asList(latTempArr)); // remove the best path to find next one
                            list.remove(entry.getKey());
                            latTempArr = list.toArray(new String[0]);

                            String[] arr_temp2 = entry.getKey().split(",");
                            //System.out.println(arr_temp[0]);
                            curLatitude = Double.parseDouble(arr_temp2[0]);
                            curLongtitude = Double.parseDouble(arr_temp2[1]);
                            strKey = entry.getKey();
                            intTempArr2.add(entry.getValue());
                            final_arr2.put(strKey,entry.getValue());
                        }
                    }
                    catch(Exception e)
                    {

                    }

                }
                //System.out.println(intTempArr);
            }

            //int i = 0;
            destinations = new ArrayList<String>();
            for(int i =0;i<intTempArr2.size();i++) {
                for(String Key : final_arr2.keySet()) {
                    //System.out.println();
                    if(final_arr2.get(Key) == intTempArr2.get(i)) {
                        destinations.add(Key);
                        break;
                    }
                }
            }

            System.out.println(destinations);
            for(int i = 0;i < destinations.size();i++) {
                //Toast.makeText(getApplicationContext(), " ListItem : " + i, Toast.LENGTH_LONG).show();
                String desti1 = destinations.get(i);
                String[] des = desti1.split(",");
                desc1_lat = Double.parseDouble(des[0]);
                desc1_long = Double.parseDouble(des[1]);

                startPosition = new LatLng(latitude, longitude);
                startPositionTitle = addresses.get(0).getLocality();
                startPositionSnippet = addresses.get(0).getAddressLine(1)+"," +" "+ addresses.get(0).getAddressLine(2);

                try {
                    adres2 = (ArrayList<Address>) gCoder.getFromLocation(desc1_lat, desc1_long, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                destinationPosition1 = new LatLng(desc1_lat, desc1_long);
                destinationPositionTitle = adres2.get(0).getLocality();
                destinationPositionSnippet =adres2.get(0).getAddressLine(1)+"," +" "+adres2.get(0).getAddressLine(2);
                // mMap.setOnInfoWindowClickListener(this);

                mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                    @Override
                    public View getInfoWindow(Marker marker) {
                        return null;
                    }

                    @Override
                    public View getInfoContents(Marker marker) {
                        View v = getLayoutInflater().inflate(R.layout.marker, null);

                        TextView info= (TextView) v.findViewById(R.id.info);

                        info.setText(marker.getSnippet().toString());

                        return v;
                    }
                });

                mDestination1 = new MarkerOptions()
                        .position(destinationPosition1)
                        .title(destinationPositionTitle)
                        .snippet(destinationPositionSnippet)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));

                mStart = new MarkerOptions()
                        .position(startPosition)
                        .title(startPositionTitle)
                        .snippet(startPositionSnippet)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));

                mMap.addMarker(mDestination1);
                mMap.addMarker(mStart);

                latitude = desc1_lat;
                longitude = desc1_long;
                LatLng locations = new LatLng(latitude,longitude);
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locations, 5.5f));
            }
        }catch (Exception ex)
        {
            /*Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();*/
        }

    }

    public void clearMap() {
        mMap.clear();
    }

    @Override
    public void onClick(View v) {
        try
        {
            Locale mLocale = new Locale("en");
            Log.d("Display language = ", "" + mLocale.getDisplayLanguage());


            gCoder = new Geocoder(RouteMap.this,mLocale);
            gps = new GPSTracker(RouteMap.this);
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();


            for(int i = 0;i<destinations.size();i++) {
                String desti1 = destinations.get(i);
                String[] des = desti1.split(",");
                desc1_lat = Double.parseDouble(des[0]);
                desc1_long = Double.parseDouble(des[1]);

                startPosition = new LatLng(latitude, longitude);

                startPositionTitle = addresses.get(0).getLocality();
                startPositionSnippet = addresses.get(0).getAddressLine(1)+","+" "+addresses.get(0).getAddressLine(2);


                destinationPosition1 = new LatLng(desc1_lat, desc1_long);
                destinationPositionTitle = adres2.get(0).getLocality();
                destinationPositionSnippet =adres2.get(0).getAddressLine(1)+","+""+ adres2.get(0).getAddressLine(2);

                mMap.setOnInfoWindowClickListener(this);

                mStart = new MarkerOptions()
                        .position(startPosition)
                        .title(startPositionTitle)
                        .snippet(startPositionSnippet)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));

                mDestination1 = new MarkerOptions()
                        .position(destinationPosition1)
                        .title(destinationPositionTitle)
                        .snippet(destinationPositionSnippet)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));

                if (v == btnDirection) {
                    //  clearMap();

                    mMap.addMarker(mDestination1);
                    mMap.addMarker(mStart);

                    if (tbMode.isChecked()) {

                        new GetRotueListTask(RouteMap.this, startPosition,
                                destinationPosition1, GMapV2Direction.MODE_DRIVING, this)
                                .execute();

                    } else {
                        new GetRotueListTask(RouteMap.this, startPosition,
                                destinationPosition1, GMapV2Direction.MODE_WALKING, this)
                                .execute();
                    }
                }
                latitude = desc1_lat;
                longitude = desc1_long;



            }
        }catch (Exception ex)
        {
            Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public void OnDirectionListReceived(List<LatLng> mPointList) {
        try
        {
            if (mPointList != null) {
                PolylineOptions rectLine = new PolylineOptions().width(10).color(
                        Color.RED);
                for (int i = 0; i < mPointList.size(); i++) {
                    rectLine.add(mPointList.get(i));
                }
                mMap.addPolyline(rectLine);

                gps = new GPSTracker(RouteMap.this);
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();

                start = new LatLng(latitude, longitude);


                CameraPosition mCPFrom = new CameraPosition.Builder()
                        .target(start).zoom(15.5f).bearing(0).tilt(25)
                        .build();
                final CameraPosition mCPTo = new CameraPosition.Builder()
                        .target(destinationPosition1).zoom(15.5f).bearing(0)
                        .tilt(50).build();

                changeCamera(CameraUpdateFactory.newCameraPosition(mCPFrom),
                        new CancelableCallback() {
                            @Override
                            public void onFinish() {
                                changeCamera(CameraUpdateFactory
                                                .newCameraPosition(mCPTo),
                                        new CancelableCallback() {

                                            @Override
                                            public void onFinish() {

                                                LatLngBounds bounds = new LatLngBounds.Builder()
                                                        .include(start)
                                                        .include(
                                                                destinationPosition1)
                                                        .build();
                                                changeCamera(
                                                        CameraUpdateFactory
                                                                .newLatLngBounds(
                                                                        bounds, 50),
                                                        null, false);
                                            }

                                            @Override
                                            public void onCancel() {
                                            }
                                        }, false);
                            }

                            @Override
                            public void onCancel() {
                            }
                        }, true);
            }
        }catch (Exception ex)
        {
            Toast.makeText(getApplicationContext(), "Please Check your Data Connection", Toast.LENGTH_LONG).show();
        }

    }

    private void changeCamera(CameraUpdate update, CancelableCallback callback,
                              boolean instant) {

        if (instant) {
            mMap.animateCamera(update, 1, callback);
        } else {
            mMap.animateCamera(update, 4000, callback);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }


    private class openMap extends AsyncTask<String, Void, String>
    {
        ProgressDialog mProgressDialog;
        Context ctx;
        public openMap(Context ctx)
        {
            this.ctx=ctx;
            mProgressDialog = new ProgressDialog(RouteMap.this);
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.setMessage("Loading Map..Please wait....");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            // Toast.makeText(getApplicationContext(), "Syncing DB...", Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(String... urls)
        {
            return "Success";
        }

        @Override
        protected void onPostExecute(String result)
        {
            mProgressDialog.dismiss();

            try
            {
                if(result.equalsIgnoreCase("Success")) {

                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
                }

            }catch (Exception e){}


        }
    }
}

From this code above what changes should I make to fix the Skipped 1000+ frames issue and also help me add loader before opening the map...

您在 OnMapReady 函数中编写的代码太多,请从那里删除该代码 我可以看到 onMapReady 中有超过 4 个 "for" 循环,将该部分移至其他地方,例如 OnCreate () 创建您想要的所有地图和列表。

只需使用 OnMapReady 函数来放置标记

Geocoder.getFromLocation() 是对 Google 的服务器进行网络调用的昂贵调用,因此不要在 UI 线程上进行。

查看 android 开发人员文档中的 Processes and Threads,了解在后台发出请求的各种方式。