2014-10-28 18 views
0

所以,這是我的代碼,它會轉到外部數據庫,並在半徑範圍內(我不記得它的100或200公里)的前25個標記。mapActivity almos 1.5分鐘加載一切

事情是,地圖大約需要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); 
     } 

    } 
+0

你應該剖析你的代碼並確定究竟需要這麼長時間。這是請求的延遲嗎?添加每個標記是否緩慢?只有很多標記嗎? – 2014-10-28 13:37:14

回答

0

有幾件事情浮現在腦海中:

你在模擬器或真實設備上運行應用程序? (我期望在仿真器上這會很慢)

難道說你正在運行的查詢是拉回了太多的數據,查詢效率低下,還是隻是在整個網絡中緩慢?

您可以在每種方法中添加Log語句,以查看您的應用花費的最多時間 - 這會將您指向瓶頸。

+0

好問題,查詢不應該花很長時間,因爲我使用與列表視圖(用兩個或三個secons加載)相同的查詢,我在真實設備上運行。 我可能會使用日誌語句!我肆意使用它們,所以我不記得它!好點子 !! – pihh 2014-10-28 14:42:21