2016-08-22 2 views
-4

많은 데이터가 sqlite 데이터베이스, json 요청, Google지도 및 recyclerView에서 검색하는 Android 애플리케이션을 개발 중입니다.Android - 내 앱 속도를 높이려면 어떻게해야하나요?

문제는 응용 프로그램이 느리고 많은 지연이 있는지입니다. json 요청이나 어댑터에 이미 asynctask 클래스를 사용하고 있습니다. 그러나 db와 swap 리사이클 뷰의 아이템을 시간과 속도로 빠르게 가져올 수있는 방법이 있습니까?

나는 사용자 정의 로더에 대해 읽었지만, 그것이 나를 위해 유용 할 수 있는지 모르겠습니다. busUtility에서

/** 
* Fragment for Bus function 
*/ 
public class BusFragment extends Fragment { 
    private RecyclerView mRecyclerView; 
    private RecyclerView.Adapter mAdapter; 
    private RecyclerView.LayoutManager mLayoutManager; 
    private List<Fermata> myDataset; 
    public View view; 
    private static final String TAG_LOG = BusFragment.class.getName(); 
    private final String MAP = "BUS"; 
    Polyline line; 
    /** 
    * This is the request code we use for the onActivityResult management 
    */ 
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; 

    /** 
    * The GoogleApiClient we use to interact with Location Services 
    */ 
    public GoogleApiClient mGoogleApiClient; 

    /** 
    * The last location 
    */ 
    public static volatile Location mLastLocation; 

    /** 
    * The Fragment for the Map 
    */ 
    public SupportMapFragment mMapFragment; 


    /** 
    * The handle to manage Google Map 
    */ 
    public GoogleMap mGoogleMap; 

    /** 
    * The implementation of the interface to manage CallBacks from Google Play Services 
    */ 
    private final GoogleApiClient.ConnectionCallbacks mConnectionCallbacks = new GoogleApiClient.ConnectionCallbacks() { 

     @Override 
     public void onConnected(Bundle bundle) { 
      Log.d(TAG_LOG, "Connected"); 
      // We update the data into the View with the first location 
      try { 

       final Location firstLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
       mLastLocation = firstLocation; 
      } catch (SecurityException e) { 
       e.printStackTrace(); 
      } 


     } 

     @Override 
     public void onConnectionSuspended(int i) { 
      Log.d(TAG_LOG, "Disconnected. Please re-connect."); 
     } 
    }; 

    /** 
    * The implementation of the interface we use to manage errors from Google Play Services 
    */ 
    private final GoogleApiClient.OnConnectionFailedListener mOnConnectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() { 
     @Override 
     public void onConnectionFailed(ConnectionResult connectionResult) { 
      // This is invoked when we have an error in Google Play Services management. 
      // We have to check if there is a standard resolution for this 
      if (connectionResult.hasResolution()) { 
       // In this case we launch the Intent to manage the problem 
       try { 
        connectionResult.startResolutionForResult(getActivity(), 
          CONNECTION_FAILURE_RESOLUTION_REQUEST); 
       } catch (IntentSender.SendIntentException e) { 
        // In case Play Services cancels the Intent 
        e.printStackTrace(); 
       } 
      } else { 
       // In this case there's no standard resolution for the error so we can 
       // only show a Dialog with the error 
       DialogFragment dialogFragment = new DialogFragment(); 
       dialogFragment.show(getFragmentManager(), "Error:" + connectionResult.getErrorCode()); 
      } 
     } 
    }; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(mConnectionCallbacks) 
       .addOnConnectionFailedListener(mOnConnectionFailedListener) 
       .build(); 
    } 


    @Override 
    public void onStart() { 
     super.onStart(); 
     mGoogleApiClient.connect(); 
     Log.d(TAG_LOG, "Dentro onStart"); 

    } 

    @Override 
    public void onStop() { 
     super.onStop(); 
     mGoogleApiClient.disconnect(); 
    } 

    /** 
    * Method to require Location Updates 
    */ 
    protected void startLocationUpdates() { 
     LocationRequest mLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setSmallestDisplacement(10).setInterval(6000); 
     try { 
      LocationServices.FusedLocationApi.requestLocationUpdates(
        mGoogleApiClient, mLocationRequest, new LocationListener() { 
         @Override 
         public void onLocationChanged(Location location) { 
          mLastLocation = location; 
          new UpdateLocationRecycler().execute(); 
         } 
        }); 

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


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     view = inflater.inflate(R.layout.bus_fragment, 
       container, false); 

     mMapFragment.getMapAsync(new OnMapReadyCallback() { 
            @Override 
            public void onMapReady(final GoogleMap googleMap) { 

             googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() { 
              @Override 
              public void onMapLoaded() { 
               new getDistanceTask().execute(); 
               startLocationUpdates(); 


               googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { 
                @Override 
                public boolean onMarkerClick(Marker marker) { 
                 if (line != null) { 
                  line.remove(); 
                 } 

                 ArrayList<String> mark = new ArrayList<String>(); 
                 mark.add(JsonUtility.createJsonUrl(mLastLocation,LocationUtility.getLocationFromLatLng(marker.getPosition()),Const.MODE_WALKING)); 

                 new JSONParse().execute(mark); 

                 return false; 
                } 
               }); 


              } 
             }); 
            } 
           } 
     ); 
     mRecyclerView = (RecyclerView) view.findViewById(R.id.bus_stop_recycler_view); 
     mLayoutManager = new LinearLayoutManager(MyApplication.getAppContext()); 
     mRecyclerView.setLayoutManager(mLayoutManager); 

     final BusStopAdapter mAdapter = new BusStopAdapter(myDataset,mRecyclerView); 
     mRecyclerView.setAdapter(mAdapter); 

     return view; 
    } 







    /** 
    * AsyncTask class to manage json request 
    */ 
    public class JSONParse extends AsyncTask<ArrayList<String>, String, ArrayList<JSONObject>> { 

     @Override 
     protected ArrayList<JSONObject> doInBackground(ArrayList<String>... args) { 
      ArrayList<JSONObject> array = new ArrayList<>(); 
      for (int i = 0; i < args[0].size(); i++) { 
       array.add(JsonUtility.getJSONFromUrl(args[0].get(i))); 
      } 

      return array; 
     } 

     @Override 
     protected void onPostExecute(ArrayList<JSONObject> array) { 
      ArrayList<List<LatLng>> list = new ArrayList<>(); 
      for (int i = 0; i < array.size(); i++) { 
       JSONObject json = array.get(i); 
       list.add(PolylineUtility.listPolyline(json.toString())); 
      } 
      PolylineUtility.drawPath(list,mGoogleMap); 

     } 
    } 


    private class getDistanceTask extends AsyncTask<Void, String, BusStopAdapter> { 
     ProgressBar mProgressBar; 
     TextView mLoading; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      mRecyclerView = (RecyclerView) view.findViewById(R.id.bus_stop_recycler_view); 
      mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar); 
      mLoading = (TextView) view.findViewById(R.id.loading); 


     } 

     @Override 
     protected BusStopAdapter doInBackground(Void... params) { 
      publishProgress("Loading..."); 
      BusUtility busUtility = new BusUtility(); 
      myDataset = SplashScreenActivity.fermatas; 
      final BusStopAdapter mAdapter = new BusStopAdapter(myDataset,mRecyclerView); 

      return mAdapter; 
     } 

     @Override 
     protected void onPostExecute(BusStopAdapter mAdapter) { 
      super.onPostExecute(mAdapter); 
      mRecyclerView.setVisibility(View.VISIBLE); 
      mProgressBar.setVisibility(View.GONE); 
      mLoading.setVisibility(View.GONE); 

      View progress = view.findViewById(R.id.loading_layout); 
      ((ViewGroup) progress.getParent()).removeView(progress); 

      mRecyclerView.setAdapter(mAdapter); 
     } 

     @Override 
     protected void onProgressUpdate(String... values) { 
      super.onProgressUpdate(values); 
      mLoading.setText(values[0]); 
     } 
    } 

    private class UpdateLocationRecycler extends AsyncTask<Void, ProgressBar, List<Fermata>> { 
     private ProgressBar mProgressBar; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      mProgressBar = (ProgressBar) view.findViewById(R.id.progess_update); 
     } 

     @Override 
     protected List<Fermata> doInBackground(Void... params) { 
      publishProgress(mProgressBar); 
      BusUtility busUtility = new BusUtility(); 
      myDataset = busUtility.dist(mLastLocation); 
      return myDataset; 
     } 

     @Override 
     protected void onPostExecute(List<Fermata> newData) { 
      super.onPostExecute(newData); 
      final BusStopAdapter mAdapter = new BusStopAdapter(myDataset,mRecyclerView); 
      mRecyclerView.setAdapter(mAdapter); 
      mAdapter.swapItems(newData); 
      mProgressBar.setVisibility(View.GONE); 
     } 

     @Override 
     protected void onProgressUpdate(ProgressBar... values) { 
      super.onProgressUpdate(values); 
      values[0].setVisibility(View.VISIBLE); 
      mGoogleMap.clear(); 
      LocationUtility.addMarkerBusStop(mGoogleMap); 
     } 
    } 


} 

저는 버스 ​​정류장에 currentLocation의 거리 및 시간을 계산하고 textViews이 데이터 세트 어댑터라고 불리는 방법이있다. 모든 버스 정류장은 로컬 sqlite3 데이터베이스에 저장됩니다. 요약

public String[] getArray(Fermata currentItem) throws JSONException, ExecutionException, InterruptedException { 
    return JsonUtility.getDistanceTime(new JSONParse().execute(currentItem).get()); 
} 

: 나 근처의 버스 정류장 (나는 하버 사인 공식을 사용)를 얻을, JSON이 버스 정류장에 나까지의 거리를 계산하고 recyclerview에 모든 데이터를 설정합니다.

문제는 recyclerview 및 구글지도가 매우 느린이며 많이 지연 있다는 것입니다. (많은 요청이 Google에?)

정말 정말 당신의 앱 잘못 무엇을 말할 수 없다하지만 난 당신에게 줄 수
+0

. 가장 효율적인 방법으로 데이터를 가져 오는 것을 나는 모릅니다. 더 작은 조각 만 필요할 때 거대한 데이터 세트를 가져오고 있다는 것을 나는 모른다. 시도를 게시하지 않으면 도움을받을 수 없습니다. – DejaVuSansMono

+0

@DejaVuSansMono ok 죄송합니다. 유용 할 수있는 여행이 있는지를 알기 위해 일반적인 질문을했습니다. 예를 들어 db에 대한 연결은 모델 객체를 만들기 위해 커서가있는 정적 dbOpenHelper로 이루어집니다. 나는 가능한 빨리 코드를 게시 할 것이다. – Fidelis

+0

@DejaVuSansMono 내 편집을 확인하십시오. 고맙습니다. – Fidelis

답변

-1

몇 가지 도구는 약간에게 성능을 향상시키기 위해 :

코드 결함을 찾을 수

처음 사용 안드로이드 린트 : https://developer.android.com/studio/write/lint.html

을 사용하면 앱이 곳을 찾는 이들이나 대부분 사용 안드로이드 메모리 모니터의 모든 문제를 해결 한 후 대부분의 메모리 사용 : https://developer.android.com/studio/profile/am-memory.html

asyncTask를 사용해서는 안되며, 액티비티 라이프 시클을 인식하지 못하기 때문에 5 년 이상 감가 상실됩니다.

후에 만 ​​위의 작업이 로더 관리자를 구현하기 위해이 튜토리얼을 따라 완료 한 후

: 당신은 우리가 갈 수있는 뭔가가 귀하의 질문에 코드의 일종을 보여 주어야 http://www.recursiverobot.com/post/60331340133/very-simple-example-of-a-loader-and-loadermanager

+3

AsyncTasks는 더 이상 사용되지 않습니다. 항상 최상의 답변은 아니지만 용도가 있습니다. 또한, 당신의 대답은 정말로 그의 질문에 답하지 않습니다. –

+0

안녕하세요, 저는이 질문에 완전히 답할 수는 없지만 좋은 출발점이라고 생각합니다. AsyncTask가 가장 좋은 옵션이 될 수 있습니까? (그들에 대해 아는 것만으로) –

관련 문제