添加在AsyncTask的android的折线折线、AsyncTask、android

2023-09-05 00:42:00 作者:皇族丶太子丿

我遇到增加折线的性能问题,并认为,也许这将是可能增加他们扩展AsyncTask的一个单独的类。然而,当我得知UI元素不能以这样的方式添加(和折线的UI元素)。

为什么我遇到性能问题,同时绘制折线?好了,我的折线从POS机的拉伸不是POS乙但是从我的当前位置到目的地的(这是很难codeD为求应用ATM)。因此,当执行onLocationChange监听多段线绘制,因此我的应用程序需要大量等待处理的力量。

任何想法如何在这种场合使用的AsyncTask?

这是主类:

  mMap.setOnMyLocationChangeListener(新GoogleMap.OnMyLocationChangeListener(){

                @覆盖
                公共无效onMyLocationChange(位置为arg0){
                    //获取位置!
                    currentPOS =新经纬度(arg0.getLatitude(),arg0.getLongitude());
                    经纬度DST =新的经纬度(58.378249,26.714673);
                    CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(currentPOS,13);
                    mMap.animateCamera(yourLocation);
                    mMap.addMarker(新MarkerOptions()位置(DST).title伪(学校!));
                    / *
                        //删除评论添加标记Liivi 2!
                        mMap.addMaker(新MarkerOptions()位置(currentPOS).title伪(我的POS));
                     * /
                    如果(currentPOS!= NULL){
                        //这是为了显示方向
                        DirectionAPI directionAPI =新DirectionAPI(currentPOS,DST);
                        GoogleResponse googleResponse = NULL;
                        尝试 {
                            googleResponse =(GoogleResponse)directionAPI.execute()得到()。
                        }赶上(InterruptedException异常E){
                            Log.e(抓,INTERRUPDED);
                            e.printStackTrace();
                        }赶上(为ExecutionException E){
                            Log.e(抓,为ExecutionException);
                            e.printStackTrace();
                        }
                        如果(googleResponse.isOk()){
                            DrivingDirection drivingDirection =新DrivingDirection(googleResponse.getJsonObject());
                            折线= drivingDirection.getTotalPolyline();
                            新drawPath(MMAP,折线).execute();
                        }
                    }
                }
            });
 

这是异步的路径图(这将导致一个错误,由于UI冲突):

 进口android.graphics.Color;
进口android.os.AsyncTask;

进口com.google.android.gms.maps.GoogleMap;
进口com.google.android.gms.maps.model.LatLng;
进口com.google.android.gms.maps.model.Polyline;
进口com.google.android.gms.maps.model.PolylineOptions;

进口的java.util.ArrayList;

/ **
 *在2015年10月7日创建者凯文。
 * /
公共类drawPath扩展AsyncTask的{

    私有静态的ArrayList<经纬度>折线;
    私有静态GoogleMap的MMAP;

    公共drawPath(GoogleMap的地图,ArrayList的<经纬度>折线){
        this.mMap =图;
        this.polyline =折线;
    }

    @覆盖
    保护对象doInBackground(Object []对象PARAMS){
        的for(int i = 0; I< polyline.size() -  1;我++){
            经纬度的src = polyline.get(ⅰ);
            经纬度DEST = polyline.get第(i + 1);

            // MMAP是Map对象
            折线行= mMap.addPolyline(
                    新PolylineOptions()。增加(
                            新的经纬度(src.latitude,src.longitude)
                            新的经纬度(dest.latitude,dest.longitude)
                    ).WIDTH(2)。颜色(Color.BLUE).geodesic(真)
            );
        }

        返回null;
    }
}
 
7.2 Android AsyncTask

解决方案

您可以使用此code

  ublic类DrawrootTask扩展的AsyncTask<字符串,字符串,字符串> {
私人上下文的背景下;
公共静态布尔flagCompleted = FALSE;
私人GoogleMap的GoogleMap的;
私人双人source_lat = 0.0;
私人双人source_long = 0.0;
私人双人dest_lat = 0.0;
私人双人dest_long = 0.0;
用户数据用户数据;
字符串变量=DrawRootTask;
私人ProgressDialog progressDialog;
公共静态双DIST,时间;
私人折线线;
字符串distanceText =;
字符串durationText =;

公共DrawrootTask(上下文的背景下,经纬度源,经纬度目的地,
        GoogleMap的GoogleMap的){
    source_lat = source.latitude;
    source_long = source.longitude;
    dest_lat = destination.latitude;
    dest_long = destination.longitude;

    this.googleMap = GoogleMap的;
    this.context =背景;
    用户数据= Userdata.getinstance(上下文);

}

在preExecute保护无效(){
    // // TODO自动生成方法存根
    super.on preExecute();
    progressDialog =新ProgressDialog(上下文);
    progressDialog.setMessage(context.getResources()的getString(
            R.string.please_wait));
    progressDialog.setIndeterminate(真正的);
    progressDialog.show();

}

@覆盖
保护字符串doInBackground(字符串... PARAMS){

    JSON字符串=;

    //构造
    StringBuilder的urlString =新的StringBuilder();
    urlString.append(http://maps.googleapis.com/maps/api/directions/json);
    HashMap的<字符串,字符串>的keyValue =新的HashMap<字符串,字符串>();
    urlString.append(原产地=?); //从
    urlString.append(Double.toString(source_lat));
    urlString.append(,);
    urlString.append(Double.toString(source_long));
    urlString.append(&放大器;目标=); //给
    urlString.append(Double.toString(dest_lat));
    urlString.append(,);
    urlString.append(Double.toString(dest_long));
    urlString.append(&放大器,传感器=假放;模式=驱动和放大器;替代品=真正的);

    // defaultHttpClient
    字符串URL = urlString.toString();
    FetchUrl fetchurl =新FetchUrl();
    JSON = fetchurl.fetchUrl(URL,的keyValue);

    Log.e(缓冲区错误,JSON);
    返回JSON;

}

@覆盖
保护无效onPostExecute(字符串结果){
    // TODO自动生成方法存根
    super.onPostExecute(结果);
    尝试 {
        progressDialog.dismiss();
        最后的JSONObject JSON =新的JSONObject的(结果);
        JSONArray routeArray = json.getJSONArray(路);
        的JSONObject路由= routeArray.getJSONObject(0);
        JSONObject的overviewPolylines =路线
                .getJSONObject(overview_polyline);
        字符串连接codedString = overviewPolylines.getString(分);
        名单<经纬度>名单=去$ C $℃聚(EN codedString);

        对于(INT Z = 0; Z<则为list.size() -  1; Z ++){
            经纬度SRC = list.get(Z);
            经纬度DEST = list.get(Z + 1);
            行= googleMap.addPolyline(新PolylineOptions()
                    。新增(新的经纬度(src.latitude,src.longitude)
                            新的经纬度(dest.latitude,dest.longitude))
                    // .WIDTH(8)。颜色(Color.BLUE).geodesic(真));
                    .WIDTH(8)
                    。颜色(context.getResources()的getColor(
                            R.color.actionbar_color))测(真))。
            Log.i(画根,++ line.toString());
        }
        JSONArray腿= routes.getJSONArray(腿);
        JSONObject的步骤= legs.getJSONObject(0);
        JSONObject的持续时间= steps.getJSONObject(期限);
        的JSONObject距离= steps.getJSONObject(距离);
        distanceText = distance.getString(文字);
        durationText = duration.getString(文字);
        Log.i(画根,+ distance.toString());
        DIST = Double.parseDouble(distance.getString(文本)。的replaceAll(
                [^ \\ 0123456789],));
        时间= Double.parseDouble(duration.getString(文本)。的replaceAll(
                [^ \\ 0123456789],));
        userdata.setDistance(distanceText);
        userdata.setTime(durationText);
        Log.d(标签,distace是+地区+时间是+时间);
        flagCompleted = TRUE;
    }赶上(JSONException E){
        Log.d(画根,+ E);

    }
}

私人列表<经纬度>德$ C $℃聚(字符串连接codeD){

    名单<经纬度>聚=新的ArrayList<经纬度>();
    INT指数= 0,len个= EN coded.length();
    INT纬度= 0,LNG = 0;

    而(指数< LEN){
        INT B,移= 0,结果为0;
        做 {
            B = EN coded.charAt(指数++) -  63;
            结果| =(B和0x1F的)LT;<转移;
            Shift + = 5;
        }而(B> = 0x20的);
        INT DLAT =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
        纬度+ = DLAT;

        移= 0;
        结果= 0;
        做 {
            B = EN coded.charAt(指数++) -  63;
            结果| =(B和0x1F的)LT;<转移;
            Shift + = 5;
        }而(B> = 0x20的);
        INT dlng =((导致&安培; 1)= 0〜(结果>→1):!?(导致>→1));
        LNG + = dlng;

        经纬度P =新的经纬度((((双)纬度/ 1E5)),
                (((双)LNG / 1E5)));
        poly.add(对);
    }

    返回聚;
}
 

}

i'm having performance issues adding polylines and thought that maybe it'll be possible to add them in a separate class extending AsyncTask. However as i learned that UI elements can't be added in such way (and polylines are UI elements).

Why i'm having performance issues while drawing polylines? Well, my polylines are drawn not from pos A to pos B but from my current location to destination (which is hardcoded for the sake of application atm). So the polylines are drawn when onLocationChange listener is executed and thus my application requires lots of proccessing power.

Any ideas how to use AsyncTask on this occasion?

This is the main class:

 mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                @Override
                public void onMyLocationChange(Location arg0) {
                    // Get positions!
                    currentPOS = new LatLng(arg0.getLatitude(), arg0.getLongitude());
                    LatLng dst = new LatLng(58.378249, 26.714673);
                    CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(currentPOS, 13);
                    mMap.animateCamera(yourLocation);
                    mMap.addMarker(new MarkerOptions().position(dst).title("SCHOOL!"));
                    /*
                        // Remove comments to add marker to Liivi 2!
                        mMap.addMaker(new MarkerOptions().position(currentPOS).title("My POS"));
                     */
                    if (currentPOS != null) {
                        //This is supposed to show directions
                        DirectionAPI directionAPI = new DirectionAPI(currentPOS, dst);
                        GoogleResponse googleResponse = null;
                        try {
                            googleResponse = (GoogleResponse) directionAPI.execute().get();
                        } catch (InterruptedException e) {
                            Log.e("CATCH","INTERRUPDED");
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            Log.e("CATCH","EXECUTIONEXCEPTION");
                            e.printStackTrace();
                        }
                        if (googleResponse.isOk()){
                            DrivingDirection drivingDirection =  new DrivingDirection(googleResponse.getJsonObject());
                            polyline = drivingDirection.getTotalPolyline();
                            new drawPath(mMap,polyline).execute();
                        }
                    }
                }
            });

This is the Async for path drawing (which will result in an error due to UI conflict):

import android.graphics.Color;
import android.os.AsyncTask;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;

/**
 * Created by Kevin on 7.10.2015.
 */
public class drawPath extends AsyncTask{

    private static ArrayList<LatLng> polyline;
    private static GoogleMap mMap;

    public drawPath(GoogleMap map, ArrayList<LatLng> polyline){
        this.mMap = map;
        this.polyline = polyline;
    }

    @Override
    protected Object doInBackground(Object[] params) {
        for (int i = 0; i < polyline.size() - 1; i++) {
            LatLng src = polyline.get(i);
            LatLng dest = polyline.get(i + 1);

            // mMap is the Map Object
            Polyline line = mMap.addPolyline(
                    new PolylineOptions().add(
                            new LatLng(src.latitude, src.longitude),
                            new LatLng(dest.latitude,dest.longitude)
                    ).width(2).color(Color.BLUE).geodesic(true)
            );
        }

        return null;
    }
}

解决方案

you can use this code

ublic class DrawrootTask extends AsyncTask<String, String, String> {
private Context context;
public static boolean flagCompleted = false;
private GoogleMap googleMap;
private double source_lat = 0.0;
private double source_long = 0.0;
private double dest_lat = 0.0;
private double dest_long = 0.0;
Userdata userdata;
String tag = "DrawRootTask";
private ProgressDialog progressDialog;
public static double dist, time;
private Polyline line;
String distanceText = "";
String durationText = "";

public DrawrootTask(Context context, LatLng source, LatLng destination,
        GoogleMap googleMap) {
    source_lat = source.latitude;
    source_long = source.longitude;
    dest_lat = destination.latitude;
    dest_long = destination.longitude;

    this.googleMap = googleMap;
    this.context = context;
    userdata = Userdata.getinstance(context);

}

protected void onPreExecute() {
    // // TODO Auto-generated method stub
    super.onPreExecute();
    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage(context.getResources().getString(
            R.string.please_wait));
    progressDialog.setIndeterminate(true);
    progressDialog.show();

}

@Override
protected String doInBackground(String... params) {

    String json = "";

    // constructor
    StringBuilder urlString = new StringBuilder();
    urlString.append("http://maps.googleapis.com/maps/api/directions/json");
    HashMap<String, String> keyValue = new HashMap<String, String>();
    urlString.append("?origin=");// from
    urlString.append(Double.toString(source_lat));
    urlString.append(",");
    urlString.append(Double.toString(source_long));
    urlString.append("&destination=");// to
    urlString.append(Double.toString(dest_lat));
    urlString.append(",");
    urlString.append(Double.toString(dest_long));
    urlString.append("&sensor=false&mode=driving&alternatives=true");

    // defaultHttpClient
    String url = urlString.toString();
    FetchUrl fetchurl = new FetchUrl();
    json = fetchurl.fetchUrl(url, keyValue);

    Log.e("Buffer Error", json);
    return json;

}

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    try {
        progressDialog.dismiss();
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes
                .getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");
        List<LatLng> list = decodePoly(encodedString);

        for (int z = 0; z < list.size() - 1; z++) {
            LatLng src = list.get(z);
            LatLng dest = list.get(z + 1);
            line = googleMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude),
                            new LatLng(dest.latitude, dest.longitude))
                    // .width(8).color(Color.BLUE).geodesic(true));
                    .width(8)
                    .color(context.getResources().getColor(
                            R.color.actionbar_color)).geodesic(true));
            Log.i("draw root", "" + "" + line.toString());
        }
        JSONArray legs = routes.getJSONArray("legs");
        JSONObject steps = legs.getJSONObject(0);
        JSONObject duration = steps.getJSONObject("duration");
        JSONObject distance = steps.getJSONObject("distance");
        distanceText = distance.getString("text");
        durationText = duration.getString("text");
        Log.i("draw root", "" + distance.toString());
        dist = Double.parseDouble(distance.getString("text").replaceAll(
                "[^\\.0123456789]", ""));
        time = Double.parseDouble(duration.getString("text").replaceAll(
                "[^\\.0123456789]", ""));
        userdata.setDistance(distanceText);
        userdata.setTime(durationText);
        Log.d(tag, "distace is " + dist + " time is " + time);
        flagCompleted = true;
    } catch (JSONException e) {
        Log.d("draw root", "" + e);

    }
}

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}

}