mapActivity以almos 1.5分钟加载所有内容

时间:2014-10-28 13:28:24

标签: android google-maps-markers google-maps-android-api-2

所以,这是我的代码,它转到外部数据库并在半径范围内检索前25个标记(我不记得它是100或200公里)。

问题是,地图大约需要1.5分钟才能完全加载。

有什么办法可以减少这个加载时间吗?在我看来,这是不可接受的。

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapasActivity extends ActionBarActivity {

    GoogleMap googleMap;
    SharedPreferences pref;
    String sLatitude;
    String sLongitude;
    String sLinguagem;
    LocationManager locationManager;
    Location location;
    ProgressDialog pDialog;
    String sLat;
    String sLng;
    String sTipo;
    String id;
    TextView tvNome;
    TextView tvNext;
    RelativeLayout layoutClickable;
    LatLng markerLatLng;
    Typeface tf;
    Typeface tf2;
    Marker marker;
    MarkerOptions markerOptions;
    Drawable d;
    String sTransition;

    Double dLatitude;
    Double dLongitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mapa);

        sTransition = "b"; // até contrário ao clickar em algo faz o efeito b

        tf = Typeface.createFromAsset(this.getAssets(), "fonts/Lobster.ttf");
        tf2 = Typeface.createFromAsset(this.getAssets(),
                "fonts/Cabin-Italic.otf");

        // TESTEEEEE

        d = getResources().getDrawable(R.drawable.ab_background);
        getActionBar().setBackgroundDrawable(d);
        getActionBar().setLogo(
                getResources().getDrawable(R.drawable.logo_degradee));

        int actionBarTitle = Resources.getSystem().getIdentifier(
                "action_bar_title", "id", "android");
        TextView actionBarTitleView = (TextView) getWindow().findViewById(
                actionBarTitle);
        actionBarTitleView.setTypeface(tf);
        getActionBar().setTitle("Mapactivity");

        /*********************************************************************************
         * INTENTS E PREFS
         *********************************************************************************/

        pref = getApplicationContext().getSharedPreferences("MyPref",
                MODE_PRIVATE);

        sLinguagem = pref.getString("LINGUAGEM", null);
        sLatitude = pref.getString("LATITUDE", "0");
        sLongitude = pref.getString("LONGITUDE", "0");
        sTipo = getIntent().getExtras().getString("TIPO");

        dLatitude = Double.parseDouble(sLatitude);
        dLongitude = Double.parseDouble(sLongitude);

        // ******************************************************************************
        // TESTES
        // ******************************************************************************

        id = " Finder";

        layoutClickable = (RelativeLayout) findViewById(R.id.layout_mapa_botton);
        tvNome = (TextView) findViewById(R.id.tvNomeDoEstabelecimento);
        tvNext = (TextView) findViewById(R.id.tvNext);
        tvNome.setText(id);
        tvNome.setTypeface(tf);
        tvNext.setTypeface(tf2);
        tvNext.setVisibility(View.INVISIBLE);
        /*********************************************************************************
         * GOOGLE PLAY
         ********************************************************************************/

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if (status != ConnectionResult.SUCCESS) {

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                    requestCode);
            dialog.show();

        } else {
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            /*********************************************************************************************************************
             * PORMENORES PARA O MAPA
             ***************************************************************************************************************/
            googleMap = fm.getMap();
            googleMap.setMyLocationEnabled(true);
            googleMap.setBuildingsEnabled(true);
            googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            googleMap.getUiSettings().setZoomControlsEnabled(true);
            // cOISAS PARA TESTES
            // ********************************************************
            LatLng latLng = new LatLng(dLatitude, dLongitude);
            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 12);
            googleMap.animateCamera(cameraUpdate);




            googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {




                @Override
                public View getInfoWindow(Marker arg0) {
                    // TODO Auto-generated method stub
                    return null;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    View v = getLayoutInflater().inflate(
                            R.layout.marker_custom_marker_info, null);
                    TextView tvNomeInfo = (TextView) v
                            .findViewById(R.id.tvMarkerNome);
                    TextView tvIdInfo = (TextView) v
                            .findViewById(R.id.tvMarkerId);

                //  LatLng llMarker = marker.getPosition();

                    tvNomeInfo.setText(marker.getTitle());
                    tvNomeInfo.setTypeface(tf);
                    tvIdInfo.setText(marker.getSnippet());
                    tvIdInfo.setVisibility(View.INVISIBLE);

                    return v;
                }
            });
            // ***************************************************************************

            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            /******************************************************************************
             * EVENTO DO LAYOUT
             *****************************************************************************/

            layoutClickable.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    if (id != "Finder") {
                        sTransition = "a";
                        Intent intent = new Intent(MapasActivity.this,
                                SingleItemView.class);
                        intent.putExtra("KEY_ID", id);
                        startActivity(intent);
                    }

                }
            });
        }

        new getAllCustomerstask().execute(new ApiConnectorMapas());

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.map_actions, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
        case R.id.action_search:
            sTransition = "c";
            Intent i1 = new Intent(this, ServicosListActivity.class);
            startActivity(i1);
            return true;
        case R.id.action_listView:
            sTransition = "b";
            Intent i2 = new Intent(this, LOJASListActivity.class);
            i2.putExtra("TIPO", sTipo);
            startActivity(i2);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    private class getAllCustomerstask extends
            AsyncTask<ApiConnectorMapas, Long, JSONArray> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MapasActivity.this);
            pDialog.setTitle(R.string.app_name);
            pDialog.setMessage("A localizar lojas ao pé de si...");
            pDialog.setCancelable(false);
            pDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                    "Esconder esta mensagem",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            pDialog.show();
        }

        protected JSONArray doInBackground(ApiConnectorMapas... params) {
            return params[0].GetAllCustomers(sLatitude, sLongitude, sTipo/*
                                                                         * ,
                                                                         * sLinguagem
                                                                         */);
        }

    //  @SuppressWarnings("null")
        @Override
        protected void onPostExecute(JSONArray jsonArray) {
            /*
             * Códigos Para lista::
             * 
             * id name address promotype distance lat lng tipo foto
             */
            pDialog.dismiss();
            /*
             * if (jsonArray!= null){
             */
            /**********************************************************************************************************************************
             * LAYOUT MARKER
             */
            View icon = ((LayoutInflater) getSystemService(MapasActivity.LAYOUT_INFLATER_SERVICE))
                    .inflate(R.layout.mapa_custom_marker_layout, null);

            View iconPromo = ((LayoutInflater) getSystemService(MapasActivity.LAYOUT_INFLATER_SERVICE))
                    .inflate(R.layout.mapa_custom_promoted_marker_layout, null);


            TextView numTxt = (TextView) icon.findViewById(R.id.tvInfoNome);
            numTxt.setTypeface(tf2);

            List<Marker> markers = new ArrayList<Marker>();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject json = null;
                try {
                    json = jsonArray.getJSONObject(i);
                    Double promotype = json.getDouble("promotype");

                    numTxt.setText(json.getString("distance") + " km");
                    if (promotype < 1) {

                        //numTxt.setText(json.getString("distance") + " km");
                        Marker marker;
                        marker = googleMap.addMarker(new MarkerOptions()
                                .title(json.getString("name"))
                                .snippet(json.getString("id"))
                                .position(
                                        new LatLng(json.getDouble("lat"), json
                                                .getDouble("lng")))
                                // .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
                                .icon(BitmapDescriptorFactory
                                        .fromBitmap(createDrawableFromView(
                                                MapasActivity.this, iconPromo)))

                        );

                        googleMap
                                .setOnMarkerClickListener(new OnMarkerClickListener() {
                                    public boolean onMarkerClick(Marker marker) {
                                        marker.showInfoWindow();
                                        id = marker.getSnippet();
                                        tvNome.setText(marker.getTitle());
                                        tvNext.setVisibility(View.VISIBLE);

                                        return true;
                                    }
                                });
                        markers.add(marker);
                    } else {
                        //numTxt.setText(json.getString("distance") + " km");
                        //String sAlpha = "0.45";
                        //Float fAlpha = Float.parseFloat(sAlpha);
                        marker = googleMap.addMarker(new MarkerOptions()
                                .title(json.getString("name"))
                                .position(
                                        new LatLng(json.getDouble("lat"), json
                                                .getDouble("lng")))
                                /*
                                 * .icon(BitmapDescriptorFactory.defaultMarker(
                                 * BitmapDescriptorFactory.HUE_ROSE))
                                 * /*.icon(BitmapDescriptorFactory
                                 * .fromResource(R.drawable.pin))
                                 */
                                .icon(BitmapDescriptorFactory
                                        .fromBitmap(createDrawableFromView(
                                                MapasActivity.this, icon)))
                                /*.snippet(json.getString("id")).alpha(fAlpha)*/);

                        googleMap
                                .setOnMarkerClickListener(new OnMarkerClickListener() {
                                    public boolean onMarkerClick(Marker marker) {
                                        id = marker.getSnippet();
                                        marker.showInfoWindow();
                                        tvNome.setText(marker.getTitle());
                                        tvNext.setVisibility(View.VISIBLE);
                                        return true;
                                    }
                                });

                        markers.add(marker);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                /*
                 * } json = jsonArray.getJSONObject(i);
                 * 
                 * listId.add(json.getString("id"));
                 * listName.add(json.getString("name"));
                 * listAddress.add(json.getString("address"));
                 * listPromo.add(json.getString("promotype"));
                 * listDistance.add(json.getString("distance"));
                 * listLat.add(json.getString("lat"));
                 * listLng.add(json.getString("lng"));
                 * listTipo.add(json.getString("tipo"));
                 * listFoto.add(json.getString("foto"));
                 * listRank.add(json.getString("ranking"));
                 * listIdd.add(json.getString("id"));
                 */
            }
        }
    }

    /**********************************************************************************
     * CLASS QUE VAI TRANSFORMAR O LAYOUT NUM BITMAP
     */

    public static Bitmap createDrawableFromView(Context context, View view) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(displayMetrics);
        view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
        view.layout(0, 0, displayMetrics.widthPixels,
                displayMetrics.heightPixels);
        view.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(),
                view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

        return bitmap;
    }

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

        /*
         * sTransition = a - single item- check sTransition = b - back ou
         * listview - check sTransition = c - searchview - check
         */

        if (sTransition.equals("a")) {
            overridePendingTransition(R.anim.para_esq_baixo,
                    R.anim.para_esq_baixo);
        }
        if (sTransition.equals("b")) {
            overridePendingTransition(R.anim.para_dir_cima,
                    R.anim.para_dir_baixo);
        }// bottom to top
        if (sTransition.equals("c")) {
            overridePendingTransition(R.anim.from_bottom, R.anim.to_top);
        }

    }

1 个答案:

答案 0 :(得分:0)

有些事情会浮现在脑海中:

您是在模拟器还是真实设备上运行应用程序? (我希望在模拟器上这很慢)

您正在运行的查询是否正在撤回过多的数据,查询效率低下,或者只是在整个网络中显得很慢?

您可以在每种方法中添加Log语句,以查看您的应用花费最多的时间 - 这将指出您的瓶颈。