Apk delay with Location Manager up to one minute.in Android Studio

1

I wanted to ask you why can the webview load so much delay me? since it brings me a map taking as reference the latitude and longitude of the location manager and there it seems that it was stuck for several seconds (in the first consultation it takes up to 1 minute, that is, there is no person in the world who has that patience to an app) This is my fragment where I have the problem

public class YavieneFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    LocationManager locationManager;
    double longitud, latitud;

    boolean Primeraubicacion = true;
    private ProgressDialog progressDialog;
    WebView webView;

    private OnFragmentInteractionListener mListener;

    private int duracion_splash = 2300;
    private Timer timer;
    private ProgressBar progressBar;
    private int i = 0;
    Toast toast;

    @SuppressLint("SetJavaScriptEnabled")
    public YavieneFragment() {
        // Required empty public constructor

    }
    // TODO: Rename and change types and number of parameters
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }
        WifiManager myWifiManager = (WifiManager)getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if(!myWifiManager.isWifiEnabled()){
            Toast toast = Toast.makeText(getContext().getApplicationContext(),
                    "Habilitando WIFI!", Toast.LENGTH_LONG);
            toast.show();
            myWifiManager.setWifiEnabled(true);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {

            }
        }

        progressDialog = new ProgressDialog(requireContext());
        progressDialog.show();
        progressDialog.setContentView(R.layout.progressbar);
        progressDialog.setCancelable(false);
        Objects.requireNonNull(progressDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        Log.e("ya viene","ingresa a LocationStart");
        locationStart();


    }

    private void locationStart() {
        LocationManager mlocManager = (LocationManager) requireContext().getSystemService(Context.LOCATION_SERVICE);
        Localizacion Local = new Localizacion();
        Local.setMainActivity(this);




        assert mlocManager != null;
        final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!gpsEnabled) {
            Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(settingsIntent);
            Log.e("ya viene","ingresa a !gpsEnabled");
        }



        if ((PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(requireContext(), permission.ACCESS_FINE_LOCATION)) &&
                (ActivityCompat.checkSelfPermission(requireContext(), permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions((Activity) requireContext(), new String[]{permission.ACCESS_FINE_LOCATION,}, 1000);
            Log.e("ya viene","ingresa al otro if ");
            mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);
            mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) Local);
           //return;

        }else{
            mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);
            mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) Local);
            Log.e("ya viene","ingresa a locatonManager");
        }

       // mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);
        //mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) Local);


        toast = Toast.makeText(Objects.requireNonNull(getContext()).getApplicationContext(),
                "Por favor aguarde, ésto puede demorar unos segundos...", Toast.LENGTH_LONG);
        toast.show();
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1000) {
            if (PackageManager.PERMISSION_GRANTED == grantResults[0]) {
                locationStart();
            }
        }
    }



    //LLAMA AL SERVIDOR PARA CARGAR EL WEB VIEW
    @SuppressLint("SetJavaScriptEnabled")
    private void Cargarwebview(double latitud,double longitud) throws MalformedURLException {

        final WebView webView = Objects.requireNonNull(getView()).findViewById(R.id.yaviene_webview);
        webView.getSettings().setJavaScriptEnabled(true);;
        webView.getSettings().setAppCacheEnabled(false);
        webView.clearCache(true);
        webView.reload();
        toast = Toast.makeText(Objects.requireNonNull(getContext()).getApplicationContext(),
                "Su consulta está terminado de ser procesada", Toast.LENGTH_LONG);
        toast.show();
        webView.loadUrl("http://www.yaviene.com/usuario/index.php?a="+getString(R.string.EMPRESA)+"&v=1&lat="+latitud+"&Lng="+longitud);


        webView.setWebViewClient(new WebViewClient() {
            @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/erroryaviene.html");
            } });

        Log.e("ya viene","http://www.yaviene.com/usuario/index.php?a="+getString(R.string.EMPRESA)+"&v=1&lat="+latitud+"&Lng="+longitud);

        progressDialog.dismiss();

    }

    /* Aqui empieza la Clase Localizacion */
    public class Localizacion implements LocationListener {
        //  public Context ctx;
        YavieneFragment mainActivity;
        public YavieneFragment getMainActivity() {
            return mainActivity;
        }
        void setMainActivity(YavieneFragment mainActivity) {
            this.mainActivity = mainActivity;
        }


        @SuppressLint("SetJavaScriptEnabled")

        @Override
        public void onLocationChanged(Location loc) {
            // Este metodo se ejecuta cada vez que el GPS recibe nuevas coordenadas
            // debido a la deteccion de un cambio de ubicacion
            latitud= loc.getLatitude();
            Log.e("ya viene","Esto trae latitud ->"+latitud);
            longitud = loc.getLongitude();
            Log.e("ya viene","Esto trae longitud ->"+latitud);

            //CONSULTA SI ES LA PRIMERA UBICACION QUE TOMA EL GPS AL PRESIONAL EL BOTON YA VIENE Y LA ENVÍA, CASO CONTRARIO NO INGRESA
            if (Primeraubicacion){

                try {

                    //CargarMapaGPS(latitud,longitud);
                    Cargarwebview(latitud,longitud);

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                // enviarcoordenadasGET(Latitud,Longitud);
                Primeraubicacion = false;
            }


        }
        @Override
        public void onProviderDisabled(String provider) {
            // Este metodo se ejecuta cuando el GPS es desactivado
            //       mensaje1.setText("GPS Desactivado");
            Log.e("ya viene","EL GPS ESTÁ DESACTIVADO");
        }
        @Override
        public void onProviderEnabled(String provider) {
            // Este metodo se ejecuta cuando el GPS es activado
            //         mensaje1.setText("GPS Activado");
            Log.e("ya viene","EL GPS ESTÁ ACTIVADO");
        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                case LocationProvider.AVAILABLE:
                    Log.d("debug", "LocationProvider.AVAILABLE");
                    break;
                case LocationProvider.OUT_OF_SERVICE:
                    Log.d("debug", "LocationProvider.OUT_OF_SERVICE");
                    break;
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    Log.d("debug", "LocationProvider.TEMPORARILY_UNAVAILABLE");
                    break;
            }
        }
    }


    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //CONSULTO SI LA APLICACIÓN TIENE ACCESO A LA UBICACIÓN DEL DISPOSITIVO MÓVIL, EN CASO DE NO TENERLO PIDO PERMISO PARA OBTENERLA


        View v = inflater.inflate(R.layout.fragment_yaviene, container, false);

        return v;


    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

  /*  @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }*/

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    
asked by Luis 18.09.2018 в 19:50
source

1 answer

0

You actually have several details that cause what you say:

First you are defining minimum distance between location updates of 0 meters and minimum time interval between location updates of 0 seconds, this is not good practice and will cause your device to consume your battery quickly, check the documentation about requestLocationUpdates () .

 mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);
 mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) Local);

I suggest you review this information:

Explanation requestlocationupdates - locationManager Parameters

this may cause you to actually find yourself repeatedly calling the same method and therefore the WebView load:

  @Override
        public void onLocationChanged(Location loc) {
            // Este metodo se ejecuta cada vez que el GPS recibe nuevas coordenadas
            // debido a la deteccion de un cambio de ubicacion
            latitud= loc.getLatitude();
            Log.e("ya viene","Esto trae latitud ->"+latitud);
            longitud = loc.getLongitude();
            Log.e("ya viene","Esto trae longitud ->"+latitud);

            //CONSULTA SI ES LA PRIMERA UBICACION QUE TOMA EL GPS AL PRESIONAL EL BOTON YA VIENE Y LA ENVÍA, CASO CONTRARIO NO INGRESA
            if (Primeraubicacion){

                try {

                    //CargarMapaGPS(latitud,longitud);
                    Cargarwebview(latitud,longitud);

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                // enviarcoordenadasGET(Latitud,Longitud);
                Primeraubicacion = false;
            }


        }

To avoid the problem you mentioned, I suggest you make this change:

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

...
...


mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,  MIN_TIEMPO_ENTRE_UPDATES, MIN_CAMBIO_DISTANCIA_PARA_UPDATES, (LocationListener) Local);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,  MIN_TIEMPO_ENTRE_UPDATES, MIN_CAMBIO_DISTANCIA_PARA_UPDATES, (LocationListener) Local);
    
answered by 18.09.2018 в 20:40