I was updating a map with an Asynctask. Now i want to do the same with Handler. I looked around but couldn't understand what exactly should i do. AsyncTask is kinda slow and i would want it to be a bit fast.
Here is what i am doing in the Asynctask:
class DrawRouteTask extends AsyncTask<GeoPoint, Void, Polyline> {
private Exception exception;
private Polyline roadOverLay;
@Override
protected void onPostExecute(Polyline polyline) {
super.onPostExecute(polyline);
Log.i("AsyncTAsk ", " in post execute " + roadOverLay);
roadOverlay = roadOverLay;
// mOsmv.invalidate();
mOsmv.getOverlays().add(roadOverLay);
mOsmv.invalidate();
}
@Override
protected Polyline doInBackground(GeoPoint... geoPoints) {
try {
Log.i("AsyncTask", "Start Point >> " + geoPoints[0]);
Log.i("AsyncTask", "End Point >> " + geoPoints[1]);
RoadManager roadManager = new OSRMRoadManager(getContext());
ArrayList<GeoPoint> waypoints = new ArrayList<>();
waypoints.add(geoPoints[0]);
waypoints.add(geoPoints[1]);
Marker marker = new Marker(mOsmv);
marker.setPosition(geoPoints[0]);
marker.setPosition(geoPoints[1]);
marker.setTitle("Your Location ");
Log.i("AsyncTask ", "Drawable >> "+ ContextCompat.getDrawable(getContext(), R.drawable.pin));
marker.setIcon(ContextCompat.getDrawable(getContext(), R.drawable.pin));
mOsmv.getOverlays().add(marker);
road = roadManager.getRoad(waypoints);
roadOverLay = RoadManager.buildRoadOverlay(road);
roadOverLay.setColor(Color.RED);
return roadOverLay;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Any help would be appreciated.
You mean by a thread and handler?
Do whatever is inside your doInBackground() function inside a thread and send it via handler to the main thread.
Your code should look roughly like this.
new Thread(new Runnable(){
public void run(){
// your doInBackground() codes..
Message msg = handler.obtainMessage(what);//what refers to a field what inside Message;
msg.obj = anything you want to put;
msg.sendToTarget(); //dispatches msg to the certain handler.
}
}).start();
private Handler handler = new Handler(){
public void handleMessage(Message msg){
//handles message dispatched from the above code.
int what = msg.what; //You can use the 'what' as a switch-case case.
SomeObject data = (SomeObject) msg.obj; //
}
}
Note that the thread's run() or asyncTask's doInBackground is not the UI thread, which means that changing ui inside these methods will cause crashes. But, the handlerMessage() or onPostExecute() methods are performed inside the main thread, which you can use to update your view.