4 votes

How can I program thread in my android application?

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

 /* Use the LocationManager class to obtain GPS locations */
        LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        MyLocationListener mlocListener = new MyLocationListener();
        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);
            Log.i("Location", "Permisos necesarios OK!.");
            mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) mlocListener);
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) mlocListener);


    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) {

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

        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

            String Text = "Latitud: " + loc.getLatitude();
            String Text2 = "Longitud: " + loc.getLongitude();


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

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

        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



Elenasys Points 67941

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

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

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

 //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.


k3ym4n Points 1

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{

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



HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by: