我正在使用Asynctask更新地图。现在我想对Handler做同样的事情。我环顾四周但却无法理解我到底应该做些什么。 AsyncTask有点慢,我希望它有点快。
以下是我在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;
}
}
任何帮助将不胜感激。
答案 0 :(得分:0)
你的意思是一个线程和处理程序?
在线程内的 doInBackground()函数中执行任何操作,并通过处理程序将其发送到主线程。
您的代码看起来应该大致如此。
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; //
}
}
请注意,线程的run()或asyncTask的doInBackground不是UI线程,这意味着在这些方法中更改ui将导致崩溃。但是,handlerMessage()或onPostExecute()方法在主线程内执行,您可以使用它来更新视图。