从异步任务中获取 LatLngs

Getting LatLngs Back From Async Task

我已成功实施新的 Google 地图道路 API 以将我的位置捕捉​​到 Long.. 当我使用 asyncTask.execute.get() 时它工作正常但它冻结了我的 UI.. 我想知道如何从异步任务传递 LatLng 对象的结果,因为它必须每 2 秒 运行 才能获得新的经纬度。

MapsActivity.class

package com.example.akshay.roadsapi;

import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.concurrent.ExecutionException;

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    final String URL = "https://roads.googleapis.com/v1/snapToRoads?path=";
    final String KEY = "MYAPK KEY HERE";
    int i = 0;
    LatLng latLng1 = null;
    Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                BackgroundTask backgroundTask = new BackgroundTask(MapsActivity.this, latLng, URL, KEY, activity);
                try {
                    latLng1 = backgroundTask.execute().get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

                mMap.addMarker(new MarkerOptions().position(latLng1));
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        });
    }
}

BackgroundTask.class

package com.example.akshay.roadsapi;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.google.android.gms.maps.model.LatLng;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created by Akshay on 9/8/2015.
 */
public class BackgroundTask extends AsyncTask<Void, Void, LatLng> {
    Context CONTEXT;
    LatLng LATLNGS;
    String URL;
    String KEY;
    Double LAT = null;
    Double LONG = null;

    Activity ACTIVITY;
 myInt myInt = null;
    public BackgroundTask(Context context, LatLng LATLNGS, String URL, String KEY , Activity ACTIVITY) {
        this.CONTEXT = context;
        this.LATLNGS = LATLNGS;
        this.URL = URL;
        this.KEY = KEY;
        this.ACTIVITY = ACTIVITY; 
    }

    @Override
    protected LatLng doInBackground(Void... params) { 
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet();
        HttpResponse response = null;
        HttpEntity entity = null;
        InputStream inputStreamReader = null;
        BufferedReader bufferedReader = null;
        String line = null;
        StringBuilder strin = new StringBuilder();

        try {
            /*get.setURI(new URI(URL + l1.latitude + "," + l1.longitude + "|" + l2.latitude + "," + l2.longitude + "|" + l3.latitude + "," + l3.longitude + "|" + l4.latitude + "," + l4.longitude + "|" + l5.latitude + "," + l5.longitude + "|" + l6.latitude + "," + l6.longitude + "|" +
                    l7.latitude + "," + l7.longitude + "|" + l8.latitude + "," + l8.longitude + "|" + l9.latitude + "," + l9.longitude + "|" + l10.latitude + "," + l10.longitude + "|" + l11.latitude + "," + l11.longitude + "|" + l12.latitude + "," + l12.longitude + "|" + l13.latitude + "," + l13.longitude + "|" + l14.latitude + "," + l14.longitude + "|" + l15.latitude + "," + l15.longitude + "|" + l16.latitude + "," + l16.longitude + "|" + l17.latitude + "," + l17.longitude + "|" + l18.latitude + "," + l18.longitude + "|" + l19.latitude + "," + l19.longitude + "|" + l20.latitude + "," + l20.longitude + "|" + "&interpolate=false&key=" + KEY));
      */
            get.setURI(new URI(URL + LATLNGS.latitude+","+LATLNGS.longitude+"&interpolate=false&key=" + KEY));
            response = client.execute(get);
            entity = response.getEntity();
            inputStreamReader = entity.getContent();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStreamReader));
            while ((line = bufferedReader.readLine()) != null) {
                strin.append(line + "\n");
            }

            JSONObject ob = new JSONObject(strin.toString());
            JSONArray array = ob.getJSONArray("snappedPoints");
            for(int i =0 ; i<=array.length();i++)
            {
                JSONObject object = array.getJSONObject(i).getJSONObject("location");
                LAT = object.getDouble("latitude");
                LONG = object.getDouble("longitude");

            }
        }
        catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

LatLng latLng = new LatLng(LAT , LONG);
        return latLng;

    }

    @Override
    protected void onPostExecute(LatLng latLng) {
        super.onPostExecute(latLng);
    }
}

只需将此逻辑移动到 onPostExecute:

mMap.addMarker(new MarkerOptions().position(latLng1));

您可能还需要在 AsyncTask 构造函数中传递 GoogleMap 以实现此目的。