从异步任务获取LatLngs

时间:2015-09-08 17:37:12

标签: android google-maps android-asynctask google-roads-api

我已经成功实施了新的Google Maps Roads API,用于将我的位置捕捉​​到Long ..当我使用asyncTask.execute.get()但它冻结我的UI时工作正常。 我想知道如何从Async Task传递LatLng对象的结果,因为它必须每2秒运行一次以获得新的Lat Longs。

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);
    }
}

1 个答案:

答案 0 :(得分:0)

将此逻辑移至onPostExecute

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

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