帮助将转换方法转换为异步方法

时间:2011-09-11 15:22:59

标签: java android eclipse asynchronous methods

我正在尝试将我的应用中的方法转换为异步方法。这是一种在Google Map视图上加载大量自定义标记的方法。我需要使这个异步,以便在标记加载时立即显示视图。

任何人都可以帮我提一下如何将以下方法转换为异步方法吗?我正在努力理解这个概念。谢谢。

private void showpins() throws IOException {

    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    Cursor mCursor = db.query(TABLE_NAME, null, null, null, null, null, null);

    startManagingCursor(mCursor);

    while (mCursor.moveToNext()) {

    Address = mCursor.getString(4);
    Name = mCursor.getString(0);


    String noSpaces = Address.replaceAll(" ", "+");

    JSONObject geocoded = getLocationInfo(noSpaces);
    GeoPoint point = getGeoPoint(geocoded);


    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
    CustomizedItemOverlay itemizedOverlay = 
    new CustomizedItemOverlay(drawable, this);

    OverlayItem overlayitem = 
    new OverlayItem(point, Name, Address);

    itemizedOverlay.addOverlay(overlayitem);
    mapOverlays.add(itemizedOverlay);

    }
}

2 个答案:

答案 0 :(得分:0)

我做了类似的事情。但是它有为每个图像创建一个新线程的问题,因此最终崩溃。这对我来说是必要的(有点),但如果你没有从互联网上获取图像,你应该能够做到这一点。这是代码 -

/**
*
* @author Kyle
*/
public class HelloItemizedOverlay extends ItemizedOverlay {

private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;

public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
    super(boundCenterBottom(defaultMarker));
    populate();
    mContext = context;
}

@Override
public boolean onTouchEvent(MotionEvent event, final MapView mapView) {
    //---when user lifts his finger---
    if (event.getAction() == MotionEvent.ACTION_UP) {
        new Thread(new Runnable() {

            public void run() {
                ArrayList db = MainActivity.getDB(mContext);

                int i=0;

                for (Object o : db) {
                    if(i>40)break;

                    final ArrayList list = ((ArrayList) o);
                    final int lon = (int) ((Double.parseDouble("" + list.get(1)) * 1000000.0) + .5);
                    final int lat = (int) ((Double.parseDouble("" + list.get(2)) * 1000000.0) + .5);
                    final GeoPoint point = new GeoPoint(lat, lon);
                    if (isCurrentLocationVisible(mapView, point)) {
                        Log.i("***", "POINT IS VISIBLE");
                        if (mOverlays.size() > 40) {
                            i++;
                            Log.i("***", i+"");
                            removeOverlay(0);
                        }

                        if (lat != 0) {

                            Thread t=new Thread(new Runnable() {

                                public void run() {
                                    final OverlayItem overlayitem = new OverlayItem(point, "" + lat + " " + lon, list.get(0).toString().replace("jpg", "mjpg").replace("image", "video"));

                                    final String url = list.get(0).toString().replace("mjpg", "jpg").replace("video", "image");

                                    Drawable d = MainActivity.getImage(url);

                                    if (d != null) {
                                        d.setBounds(0, 0, 48, 32);
                                        overlayitem.setMarker(d);
                                        addOverlay(overlayitem);
                                        mapView.postInvalidate();
                                    }
                                }
                            });

                            t.setPriority(Thread.MIN_PRIORITY);
                            t.start();
                        }
                    } else {
                        Log.i("***", "POINT IS OUTSIDE VISIBLE RECT");
                    }
                }
            }
        }).start();

    }
    return false;
}


public void addOverlay(OverlayItem overlay) {
    mOverlays.add(overlay);
    populate();
}

public void removeOverlay(int index) {
    try {
        mOverlays.remove(index);
    } catch (Exception e) {
        Log.e("***", e.toString());
    }
    populate();
}

@Override
protected OverlayItem createItem(int i) {
    return mOverlays.get(i);
}

@Override
public int size() {
    return mOverlays.size();
}

@Override
protected boolean onTap(int index) {
    OverlayItem item = mOverlays.get(index);
    return true;
}
}

和主要活动 -

public class MainActivity extends MapActivity {

public static final String mapsApi = "xxxxxxxxxxxxxxxxxx";
public static final String PREFS_NAME = "CamWorldPrefsFile";
ListView myListView = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    final MapView mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapView.setSatellite(false);

    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.cam);
    //   d.setBounds(0, 0, d.getIntrinsicWidth()-50, d.getIntrinsicHeight());

    final HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);

    final DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());

    try {
        myDbHelper.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    new Thread(new Runnable() {

        public void run() {
            try {
                //myDbHelper.close();
                myDbHelper.openDataBase();
                String query = "SELECT * from database;";

                ArrayList stringList = myDbHelper.selectRecordsFromDBList(query, null);
                myDbHelper.close();

                for (int i = 0; i < stringList.size() - 1; i++) {
                    final ArrayList list = (ArrayList) stringList.get(i);
                    try {
                        if (Double.parseDouble("" + list.get(1)) != 0) {
                            Log.i("***", list.get(0).toString().replace("mjpg", "jpg").replace("video", "image"));
                            //                    Log.i("***", list.get(2) + " : ");
                            //                    Log.i("***", list.get(3) + " : ");

                            final int lon = (int) ((Double.parseDouble("" + list.get(1)) * 1000000.0) + .5);
                            final int lat = (int) ((Double.parseDouble("" + list.get(2)) * 1000000.0) + .5);

                            final GeoPoint point = new GeoPoint(lat, lon);

                            if (lat != 0) {

                                Thread t = new Thread(new Runnable() {

                                    public void run() {
                                        final OverlayItem overlayitem = new OverlayItem(point, "" + lat + " " + lon, list.get(0).toString().replace("jpg", "mjpg").replace("image", "video"));

                                        final String url = list.get(0).toString().replace("mjpg", "jpg").replace("video", "image");

                                        Drawable d = MainActivity.getImage(url);

                                        if (d != null) {
                                            d.setBounds(0, 0, 48, 32);
                                            overlayitem.setMarker(d);
                                            itemizedoverlay.addOverlay(overlayitem);
                                        }
                                    }
                                });
                                t.setPriority(Thread.MIN_PRIORITY);
                                t.start();
                            }

                            // ("http://151cam.uoregon.edu/axis-cgi/jpg/image.cgi?resolution=160x120")

                        }
                    } catch (Exception e) {
                        Log.i("***", e.getMessage());
                    }
                }
                //    mapView.invalidate();
            } catch (SQLException sqle) {
                throw sqle;
            }
        }
    }).start();


    mapOverlays.add(itemizedoverlay);

答案 1 :(得分:0)

我不确定你发布的方法所调用的所有方法是什么,但是我假设只有对mapOverlays的调用会影响UI,而其他所有方法都会在后台发生。你可以把它变成像这样的AsyncTask(我认为这最适合作为内部类):

class OverlayLoader extends AsyncTask<Void, CustomizedItemOverlay, Void> {
    List<Overlay> mapOverlays;

    @Override
    protected onPreExecute() {
        mapOverlays = mapView.getOverlays();
    }

    @Override
    protected Void doInBackground(Void... params) {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();

        Cursor mCursor = db.query(TABLE_NAME, null, null, null, null, null, null);

        startManagingCursor(mCursor);

        while (mCursor.moveToNext()) {

            Address = mCursor.getString(4);
            Name = mCursor.getString(0);

            String noSpaces = Address.replaceAll(" ", "+");

            JSONObject geocoded = getLocationInfo(noSpaces);
            GeoPoint point = getGeoPoint(geocoded);

            Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
            CustomizedItemOverlay itemizedOverlay = 
                new CustomizedItemOverlay(drawable, this);

            CustomizedItemOverlay overlayitem = new OverlayItem(point, Name, Address);

            itemizedOverlay.addOverlay(overlayItem);
            publishProgress(overlayitem);
        }
    }

    @Override
    protected void onPublishProgress(CustomizedItemOverlay... overlayItem) {
        mapOverlays.add(itemizedOverlay);
    }
}