estoy intentando hacer que mi aplicación devuelva la ubicación del telefono. De hecho lo hace pero demora una eternidad y he visto aplicaciones que de la nada te la devuelven. Lo que queria consultarles es si ustedes pueden decirme donde estoy fallando para que demore tanto. Les comparto el codigo del fragment java y el manifest.
public class GPSFragment 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 GPSFragment() {
// 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("GPS","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("GPS","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("GPS","ingresa al otro if ");
return;
}
// mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) Local);
Log.e("GPS","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(""gps","http://www.esta.com/index.php?a="+getString(R.string.E)+"&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/error.html");
} });
Log.e("gps","http://www.esta.com/index.php?a="+getString(R.string.E)+"&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;
Log.e("GPS","ingresa a localizacion");
toast = Toast.makeText(Objects.requireNonNull(getContext()).getApplicationContext(),
"Procesando su ubicación actual", Toast.LENGTH_LONG);
toast.show();
}
@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 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("GPS","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("GPS","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 onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.NFC_TRANSACTION_EVENT"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/icono"
android:label="@string/app_name"
android:roundIcon="@drawable/icono"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"
android:screenOrientation="portrait"
/>
<activity android:name=".SplashActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
ACTUALIZADO 21/12/2018
La app se frena vario segundos (la mayoria del tiempo por mucho), cuando pasa por onCreateView tirandome los siguientes mensajes.
*E/libEGL: validate_display:255 error 3008 (EGL_BAD_DISPLAY)
*E/ConnectivityService: RemoteException caught trying to send a callback msg for NetworkRequest [ id=17908, legacyType=-1, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED] ]
E/NotificationService: Suppressing notification from package com.lookout by user request.
E/GraphResponse: {HttpStatus: 400, errorCode: -1, subErrorCode: -1, errorType: null, errorMessage: null}