how can I program thread in my android application?

4

As I can program with threads I am new in android studio and I do not know how to implement them because when using locates with gps my application becomes very slow, this is the code I use for the location

/* Use the LocationManager class to obtain GPS locations */
        LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        MyLocationListener mlocListener = new MyLocationListener();
        mlocListener.setMainActivity(this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //Requiere permisos para Android 6.0
            Log.e("Location", "No se tienen permisos necesarios!, se requieren.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 225);
            return;
        }else{
            Log.i("Location", "Permisos necesarios OK!.");
            mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) mlocListener);
        }
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) mlocListener);



    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_inicio, menu);
        return true;

    }


    public void setLocation(Location loc) {
        //Obtener la direccion de la calle,colonia, municipio,estado a partir de la latitud y la longitud
        if (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) {
            try {
                Geocoder geocoder = new Geocoder(this, Locale.getDefault());
                List<Address> list = geocoder.getFromLocation(
                        loc.getLatitude(), loc.getLongitude(), 1);
                if (!list.isEmpty()) {
                    Address address = list.get(0);
                    tvdireccion .setText(address.getLocality() + "," + address.getAddressLine(0) + "," + address.getSubLocality() + ", " + address.getAdminArea() + ", " + address.getCountryName());

                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        for (ValidationError error : errors)
        {
            View view = error.getView();
            String message = error.getCollatedErrorMessage(this);

            if (view instanceof EditText) {
                ((EditText) view).setError(message);
            }
            else
            {
                Toast.makeText(this, message, Toast.LENGTH_LONG).show();
            }
        }
    }

    /* Class My Location Listener */
    public class MyLocationListener implements LocationListener {
        Ubicacion mainActivity;

        public  Ubicacion getMainActivity() {
            return mainActivity;
        }

        public void setMainActivity(Ubicacion mainActivity) {
            this.mainActivity = mainActivity;
        }

        @Override
        public void onLocationChanged(Location loc) {
            // Este metodo se ejecuta cada vez que el GPS recibe nuevas coordenadas
            // debido a la deteccin de un cambio de ubicacion
            loc.getLatitude();
            loc.getLongitude();

            String Text = "Latitud: " + loc.getLatitude();
            String Text2 = "Longitud: " + loc.getLongitude();
            tvlatitud.setText(Text);
            tvlongitud.setText(Text2);
            this.mainActivity.setLocation(loc);



        }

        @Override
        public void onProviderDisabled(String provider) {
            //metodo se ejecuta cuando el GPS es desactivado
            notificacion.setText("GPS Desactivado");
        }

        @Override
        public void onProviderEnabled(String provider) {
            // metodo se ejecuta cuando el GPS es activado
            notificacion.setText("GPS Activado");
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // Este mtodo se ejecuta cada vez que se detecta un cambio en el
            // status del proveedor de localizacin (GPS)
            // Los diferentes Status son:
            // OUT_OF_SERVICE -> Si el proveedor esta fuera de servicio
            // TEMPORARILY_UNAVAILABLE -> Tempralmente no disponible pero se
            // espera que este disponible en breve
            // AVAILABLE -> Disponible
        }

    }
    
asked by osvaldo barcenas 08.10.2016 в 23:04
source

2 answers

3

In your code you are not specifically using a Thread, what we can observe is that you are doing geolocation readings continuously,

  mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) mlocListener);

you must configure to not continually perform this or your application will be very slow, this example is to configure readings every minute and when you move a minimum distance of 1.5 meters:

 //Minimo tiempo para updates en Milisegundos
    private static final long MIN_TIEMPO_ENTRE_UPDATES = 1000 * 60 * 1; // 1 minuto
 //Minima distancia para updates en metros.
    private static final long MIN_CAMBIO_DISTANCIA_PARA_UPDATES = 1.5; // 1.5 metros


locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIEMPO_ENTRE_UPDATES, MIN_CAMBIO_DISTANCIA_PARA_UPDATES, locListener, Looper.getMainLooper());

more information on this question .

    
answered by 08.10.2016 / 23:24
source
0

Create a new HiloGPS class or whatever you want to call it and extend it AsyncTask<Void,Void,Void> and implement the LocationListener . You execute it where you want.

public class HiloGPS extends AsyncTask<Void,Void,Void> implements LocationListener{

//Constructor 
//metodos implementados...
//Metodo con intent para recoger los datos ,asi luego los podaras recoger donde tu quieras

}
    
answered by 17.11.2017 в 11:59