我正在开发一个Android应用程序,其中包含从sqlite数据库,json请求,Google地图和recyclerView检索的大量数据。
问题是应用程序运行缓慢且滞后很多。 我已经在为json请求或适配器使用asynctask类了但是有没有办法从db和交换回收器视图的项目及时更快地获取数据?
我正在阅读有关自定义装载机的内容,但我不知道它是否对我有用。
/**
* 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);
}
}
}
在busUtility中我有一个由适配器调用的方法,它计算从currentLocation到bus stop的距离和时间,并在textViews中设置这些数据。所有公交车站都保存在本地sqlite3数据库中。
public String[] getArray(Fermata currentItem) throws JSONException, ExecutionException, InterruptedException {
return JsonUtility.getDistanceTime(new JSONParse().execute(currentItem).get());
}
总结:到我附近的公共汽车站(我使用半正式公式),用json计算从我到这个公交车站的距离,并在recyclerview上设置所有这些数据。
问题是recyclerview和谷歌地图非常慢并且滞后很多。(很多人请求google?)
答案 0 :(得分:-1)
我真的无法告诉你应用程序出了什么问题,但我可以给你一些工具来提高性能:
首先使用Android Lint查找代码漏洞: https://developer.android.com/studio/write/lint.html
修复所有这些内容后,或绝大多数使用Android内存监视器找出应用程序使用大多数内存的位置: 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