Forum Xamarin.Android

I want to get the location changes, but I get JNI DETECTED ERROR IN APPLICATION in GoogleApiClient

I want to get the location changes by the method of OnLocationChanged, I used the OnMyLocationChanged before but I see that this method is already in disuse, but with the new meotodo it marks me error when assigning the mGoogleApiClient variable

namespace FuncionesAndroid.Droid
{
[Activity(Label = "MainMapa")]
public class MainMapa : Activity, IOnMapReadyCallback, IOnMyLocationClickListener, IOnMyLocationButtonClickListener, Android.Gms.Location.ILocationListener, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener
{
private string _tag = "MainMapa";
GoogleMap mapa = null;
DataBase db = new DataBase();
private LocationRequest locationRequest;
static GoogleApiClient mGoogleApiClient;
public static int MILISEGUNDOS_POR_SECUNDOS = 1000;
public static int MINUTO = 60 * MILISEGUNDOS_POR_SECUNDOS;
//private IFusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
public async void OnMapReady(GoogleMap googleMap)
{
mapa = googleMap;
googleMap.MyLocationEnabled = true;
googleMap.SetOnMyLocationButtonClickListener(this);
googleMap.SetOnMyLocationClickListener(this);
googleMap.SetMinZoomPreference(6.0F);

        //Opcional
        googleMap.SetLatLngBoundsForCameraTarget(new LatLngBounds(new LatLng(14.399838, -119.346947),new LatLng(30.706694, -83.355215)));
        googleMap.UiSettings.ZoomControlsEnabled = true;
        googleMap.UiSettings.CompassEnabled = true;
        locationRequest = new LocationRequest();
        locationRequest.SetInterval(MINUTO);
        locationRequest.SetFastestInterval(15 * MILISEGUNDOS_POR_SECUNDOS);
        locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);

        try
        {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
            .AddConnectionCallbacks(this)
            .AddOnConnectionFailedListener(this)
            .AddApi(LocationServices.API)
            .Build();
        }
        catch (Exception e)
        {
            Log.Debug(_tag, e.Message);
        }


        googleMap.MoveCamera(CameraUpdateFactory.ZoomIn());
        CargarMarcadores();
        CentrarMyUbicacion();

    }

    private void GuardarRutas(ArrayList rutas, int idInicio, int idFin)
    {
        foreach (ArrayList path in rutas)
        {
            foreach (Dictionary<String, Double> punto in path)
            {
                Model.Polyline polyline = new Model.Polyline()
                {
                    id_inicio = idInicio,
                    id_fin = idFin,
                    lat = punto["lat"],
                    lon = punto["lon"]
                };
                db.InsertarDatoPolyline(polyline, this);
            }
        }
    }

    public void CargarMarcadores()
    {
        BitmapDrawable bitmapClienteDraw = (BitmapDrawable)GetDrawable(Resource.Mipmap.marker_map_us);
        Bitmap bitmapCliente = bitmapClienteDraw.Bitmap;
        Bitmap smallMarkerCliente = Bitmap.CreateScaledBitmap(bitmapCliente, 60, 90, false);

        List<ClientesGps> clientesGps;
        clientesGps = db.selectTablaClientesGps(this);
        Location miUbicacion = ObtenerUbicacionActual();
        foreach (ClientesGps cliente in clientesGps)
        {
            MarkerOptions clienteMarcador = new MarkerOptions()
            .SetPosition(new LatLng(cliente.lat, cliente.lon))
            .SetIcon(BitmapDescriptorFactory.FromBitmap(smallMarkerCliente))
            .SetTitle(cliente.nombre);
            mapa.AddMarker(clienteMarcador);
        }
    }

    public void CentrarMyUbicacion()
    {
        LocationManager locationManager = (LocationManager)
            GetSystemService(Context.LocationService);
        Criteria criteria = new Criteria();
        criteria.Accuracy = Accuracy.Fine;
        Location Ubicación = locationManager.GetLastKnownLocation(locationManager.GetBestProvider(criteria, false));
        if (Ubicación != null)
        {
            LatLng myUbicación = new LatLng(Ubicación.Latitude, Ubicación.Longitude);
            mapa.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(myUbicación,15.4F));
        }
    }

    public Location ObtenerUbicacionActual()
    {
        LocationManager locationManager = (LocationManager)
            GetSystemService(Context.LocationService);
        Criteria criteria = new Criteria();
        criteria.Accuracy = Accuracy.Fine;
        Location Ubicación = locationManager.GetLastKnownLocation(locationManager.GetBestProvider(criteria, false));
        return Ubicación;
    }


    public void DibujarRutas(ArrayList rutas, GoogleMap googleMap)
    {
        PolylineOptions polylineOptions = null;

        foreach(ArrayList path in rutas)
        {
            polylineOptions = new PolylineOptions();

            foreach(Dictionary<String, Double> punto in path)
            {
                double lat, lon;
                lat = punto["lat"];
                lon = punto["lon"];
                polylineOptions.Add(new LatLng(lat, lon));
            }
            polylineOptions.InvokeWidth(15);
            polylineOptions.InvokeColor(Color.Blue);
            polylineOptions.Geodesic(true);
        }

        if(polylineOptions!=null)
        {
            googleMap.AddPolyline(polylineOptions);
        }
        else
        {
            Toast.MakeText(this, "Direcciones no encontradas", ToastLength.Short).Show();
        }
    }

    private async Task<ArrayList> GetUrlAsync(LatLng origin,LatLng dest, String directionMode)
    {
        String str_origin = "origin=" + origin.Latitude + "," + origin.Longitude;
        String str_dest = "destination=" + dest.Latitude + "," + dest.Longitude;
        String mode = "mode=" + directionMode;
        String parameters = str_origin + "&" + str_dest + "&" + mode;
        String output = "json";
        JObject json = await Servicios.Servicio.ObtenerRutaGoogleMaps(output, parameters, GetString(Resource.String.GoogleKey));


        ArrayList routes = new ArrayList();
        JArray jRoutes = null;
        JArray jLegs = null;
        JArray jSteps = null;
        try
        {
            jRoutes = (JArray)json["routes"];
            for (int i = 0; i < jRoutes.Count; i++)
            {
                jLegs = (JArray)jRoutes[i]["legs"];
                ArrayList path = new ArrayList();
                for (int j = 0; j < jLegs.Count; j++)
                {
                    jSteps = (JArray)jLegs[j]["steps"];
                    for (int k = 0; k < jSteps.Count; k++)
                    {
                        String polyline = "";
                        polyline = (String)jSteps[k]["polyline"]["points"];
                        ArrayList list = decodePolyline(polyline);
                        for(int l = 0; l < list.Count; l++)
                        {
                            Dictionary<String, Double> hm = new Dictionary<string, Double>();
                            hm.Add("lat", ((LatLng)list[l]).Latitude);
                            hm.Add("lon", ((LatLng)list[l]).Longitude);
                            path.Add(hm);
                        }
                    }
                    routes.Add(path);
                }
            }
            return routes;
        }
        catch (JsonReaderException e)
        {
            routes = null;
            return routes;
        }
    }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.MainMapa);
        MapFragment mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map);
        mapFragment.GetMapAsync(this);
    }

    protected override void OnResume()
    {
        base.OnResume();
        if(mGoogleApiClient.IsConnected)
        {
            RequestLocationUpdates();
        }
    }

    protected override void OnStart()
    {
        base.OnStart();
        mGoogleApiClient.Connect();
    }

    protected override void OnStop()
    {
        base.OnStop();
        mGoogleApiClient.Disconnect();
    }

    private void RequestLocationUpdates()
    {
        LocationServices.FusedLocationApi.RequestLocationUpdates(mGoogleApiClient, locationRequest, this);
    }

    protected override void OnPause()
    {
        base.OnPause();
        LocationServices.FusedLocationApi.RemoveLocationUpdates(mGoogleApiClient, this);
    }

    public void OnMyLocationClick(Location location)
    {
        Toast.MakeText(this, "My Ubicación actual", ToastLength.Short).Show();
    }

    public bool OnMyLocationButtonClick()
    {
        Toast.MakeText(this, "Centrando en ubicación actual", ToastLength.Short).Show();
        return false;
    }

    public async void OnLocationChanged(Location location)
    {
        Toast.MakeText(this, location.ToString(),ToastLength.Short).Show();
    }

    public void OnConnectionFailed(ConnectionResult result)
    {
        //throw new NotImplementedException();
    }

    public void OnConnected(Bundle connectionHint)
    {
        RequestLocationUpdates();
    }

    public void OnConnectionSuspended(int cause)
    {
        //throw new NotImplementedException();
    }
}
}

Likewise, I have seen some codes that are not in disuse, that do not use the Google AppClient, but do not explain the use or are not very well documented, if they have some better code I would appreciate it very much

Answers

Sign In or Register to comment.