ArcGis for Android学习笔记之AsyncTask和IdentifyTask的应用

最近做一个项目,是识别地图服务的高亮要素,并且获取到要素的信息,所以在网上找了些资料,现在整理下。

1.首先自定义了一个IdentifyTask类,将IdentifyParameters对象设置好传给自定义的IdentifyTask。

    Point pointClicked = mapView.toMapPoint(x, y);
            // 获取图层
            drawLayer = mMapLayerMap.get("drawLayer");

            IdentifyParameters inputParameters = new IdentifyParameters();
            inputParameters.setGeometry(pointClicked);
            int layout[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                    13, 14, 15, 16, 18, 19, 20, 21 };
            inputParameters.setLayers(layout);// 设置图层
            Envelope env = new Envelope();
            mapView.getExtent().queryEnvelope(env);
            inputParameters.setSpatialReference(mapView.getSpatialReference());
            inputParameters.setMapExtent(env);
            inputParameters.setDPI(96);
            inputParameters.setMapHeight(mapView.getHeight());
            inputParameters.setMapWidth(mapView.getWidth());
            inputParameters.setTolerance(tolerance);// 设置容差

2.自定义IdentifyTask继承AsyncTask类

AsyncTask类简单介绍:

AsyncTask类是一个处理简单的异步操作,相当于Handler。

AsyncTask定义了三种泛型类型 Params,Progress和Result。如果没有可以直接用void。

1>Params 启动任务执行的输入参数,比如HTTP请求的URL。

2>Progress 后台任务执行的百分比。

3>Result 后台执行任务最终返回的结果,比如String。

使用过AsyncTask 的同学都知道一个异步加载数据最少要重写以下这两个方法:

  • doInBackground(Params…) 后台执行,比较耗时的操作都可以放在这里。注意这里不能直接操作UI。此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以 调用publicProgress(Progress…)来更新任务的进度。
  • onPostExecute(Result)  相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI。 此方法在主线程执行,任务执行的结果作为此方法的参数返回

有必要的话你还得重写以下这三个方法,但不是必须的:

  • onProgressUpdate(Progress…)   可以使用进度条增加用户体验度。 此方法在主线程执行,用于显示任务执行的进度。
  • onPreExecute()        这里是最终用户调用Excute时的接口,当任务执行之前开始调用此方法,可以在这里显示进度对话框。
  • onCancelled()             用户调用取消时,要做的操作

使用AsyncTask类,以下是几条必须遵守的准则:

1>Task的实例必须在UI thread中创建;

2>execute方法必须在UI thread中调用;

3>不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法;

4>该task只能被执行一次,否则多次调用时将会出现异常;

public class BLMyIdentifyTask extends
        AsyncTask<IdentifyParameters, Void, IdentifyResult[]> {
    private IdentifyTask mIdentifyTask;
    private Graphic[] highlightGraphics;
    private Context mContext;
    private GraphicsLayer mGraphicsLayer;
    private Map<String, Object> map;
    private Dialog aDialog;
    private static final String TBL_SYS_CONFIG = "SystemConfig"; // 系统配置表
    private ProgressDialog dialog;// 等待图标

    public BLMyIdentifyTask(Context context, GraphicsLayer graphicsLayer) {
        this.mContext = context;
        this.mGraphicsLayer = graphicsLayer;
        this.aDialog = new Dialog(mContext);

    }

    /**
     * 异步任务执行的过程,所有费时的操作
     */
    @Override
    protected IdentifyResult[] doInBackground(IdentifyParameters... params) {
        // TODO Auto-generated method stub
        IdentifyResult[] mResult = null;
        if (params != null && params.length > 0) {
            IdentifyParameters mParams = params[0];
            try {
                mResult = mIdentifyTask.execute(mParams);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return mResult;
    }

    /**
     * 接收doInBackground返回的值,更新UI
     */
    @Override
    protected void onPostExecute(IdentifyResult[] result) {
        // TODO Auto-generated method stub
        dialog.dismiss();
        if (result != null && result.length > 0) {
            IdentifyResult tempResult = result[0];
            String LayerName = tempResult.getLayerName();
            highlightGraphics = new Graphic[result.length];
            Geometry geom = result[0].getGeometry();
            String typeName = geom.getType().name();
            map = result[0].getAttributes();
            try {
                dialog(map, LayerName);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

            // 随机颜色
            Random r = new Random();
            int color = Color.rgb(r.nextInt(255), r.nextInt(255),
                    r.nextInt(255));

            /*
             * Create appropriate symbol, based on geometry type
             */
            // 绘制点线面的要素
            if (typeName.equalsIgnoreCase("point")) {
                SimpleMarkerSymbol sms = new SimpleMarkerSymbol(color, 20,
                        STYLE.SQUARE);
                highlightGraphics[0] = new Graphic(geom, sms);
            } else if (typeName.equalsIgnoreCase("polyline")) {
                SimpleLineSymbol sls = new SimpleLineSymbol(color, 5);
                highlightGraphics[0] = new Graphic(geom, sls);
            } else if (typeName.equalsIgnoreCase("polygon")) {
                SimpleFillSymbol sfs = new SimpleFillSymbol(color);
                sfs.setAlpha(75);
                highlightGraphics[0] = new Graphic(geom, sfs);
            }

            /**
             * set the Graphic's geometry, add it to GraphicLayer and refresh
             * the Graphic Layer
             */
            mGraphicsLayer.addGraphic(highlightGraphics[0]);

        } else {
            Toast toast = Toast.makeText(mContext, "没有寻找到对象!",
                    Toast.LENGTH_SHORT);
            toast.show();
        }

    }

    /**
     * 这是调用任务的接口,在任务之前调用,这可以显示进度条或者等待图片来增加用户体验
     */
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        DBHelper data = new DBHelper(mContext);
        Cursor cursor = data.getLast(TBL_SYS_CONFIG);
        String mapUrl = cursor.getString(cursor.getColumnIndex("MapService"));
        mIdentifyTask = new IdentifyTask(mapUrl);

        // 显示等待对话框
        this.dialog = new ProgressDialog(mContext);
        this.dialog.setMessage("正在获取闭关阀门信息,请稍后...");
        this.dialog.setCanceledOnTouchOutside(false);
        this.dialog.setCancelable(false);
        this.dialog.show();

    }

    /**
     * 显示数据的对话框
     * 
     * @param map
     * @param LayerName
     */
    private void dialog(Map<String, Object> map, String LayerName) {
        // 初始化设置对话框
        AlertDialog.Builder builder = new Builder(mContext);
        LinearLayout layout = (LinearLayout) LayoutInflater.from(mContext)
                .inflate(R.layout.dialog_content, null);
        ExpandableListView listView = (ExpandableListView) layout
                .findViewById(R.id.delog_listview_content);
        // 初始化适配器
        UPropertyAdapter adapter2 = new UPropertyAdapter(mContext, map);
        listView.setAdapter(adapter2);
        // 展开基本属性
        listView.expandGroup(0);
        builder.setTitle("对象属性_" + LayerName);
        builder.setView(layout);
        aDialog = builder.create();
        aDialog.show();

    }

请多多指教。。。。

原文地址:https://www.cnblogs.com/wjdawx/p/3371518.html