Null longitude and latitude when wanting to obtain them

2

I have a class where it is assumed that you get the longitude and latitude but when you want to get it from my service, I send it in 0.0 I searched for the answers they give me, the code does not work here.

GPSTracker.java

package com.android.controlmovil.funciones;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.location.LocationServices;

import static android.content.ContentValues.TAG;

/**
 * Create this Class from tutorial :
 * http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
 *
 * For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
 *
 */

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // Flag for GPS status
    boolean isGPSEnabled = false;

    // Flag for network status
    boolean isNetworkEnabled = false;

    // Flag for GPS status
    boolean canGetLocation = false;

    Location location; // Location
    double latitude; // Latitude
    double longitude; // Longitude
    LocationServices locationserice;
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // Getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // Getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // No network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    checkLocationPermission();
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                };
                // If GPS enabled, get latitude/longitude using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }


    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app.
     * */


    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }


    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch Settings Options.
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing the Settings button.
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // On pressing the cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }


    @Override
    public void onLocationChanged(Location location) {

    }


    @Override
    public void onProviderDisabled(String provider) {
    }


    @Override
    public void onProviderEnabled(String provider) {
    }


    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
        } else {
            return true;
        }
    }

My service where I want to get them

public void comenzarLocalizacion(Context mcontext) {


        GPSTracker gps = new GPSTracker(mcontext);

        if (gps.canGetLocation()) {
            latitud = gps.getLatitude();
            longitud = gps.getLongitude();

            Log.e("Latitud",">>"+latitud);
            Log.e("Latitud",">>"+latitud);

            try{
                Toast.makeText(enviar_coord_background.this,"Coordenadas Enviadas",Toast.LENGTH_LONG).show();
            }catch (Exception e){

            }
        } else {
            latitud = 0.0;
            longitud = 0.0;
        }
    }

I get values of 0.0 and I have added the following permissions to my Manifest.xml

  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BIND_DEVICE_ADMIN" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    
asked by Carlos Hernández 27.09.2016 в 21:14
source

1 answer

1

Because this code mostly causes error to many people, I found a way to get the longitude, latitude and adapt it according to my needs in link

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

     <TextView
            android:id="@+id/textView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:text="Do you want a fine accuracy or not?" />

     <TextView
            android:id="@+id/choice"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="coarse accuracy selected (default)" />

     <CheckBox
         android:id="@+id/fineAccuracy"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="fine accuracy" />

     <Button
         android:id="@+id/chooseRadio"
         style="?android:attr/buttonStyleSmall"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="OK" />

      <TextView
            android:id="@+id/prov"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="No provider selected yet"
            android:layout_marginTop="10dp"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/lat"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="Latitude: -"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/lon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Longitude: -"
            android:textSize="20dp" />

</LinearLayout> 

MainActivity.java :

package com.javacodegeeks.android.locationservicetest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
      private TextView latitude;
      private TextView longitude;
      private TextView choice;
      private CheckBox fineAcc;
      private Button choose;
      private TextView provText;
      private LocationManager locationManager;
      private String provider;
      private MyLocationListener mylistener;
      private Criteria criteria;

    /** Called when the activity is first created. */

      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          latitude = (TextView) findViewById(R.id.lat);
          longitude = (TextView) findViewById(R.id.lon);
          provText = (TextView) findViewById(R.id.prov);
          choice = (TextView) findViewById(R.id.choice);
          fineAcc = (CheckBox) findViewById(R.id.fineAccuracy);
          choose = (Button) findViewById(R.id.chooseRadio);

          // Get the location manager
          locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
          // Define the criteria how to select the location provider
          criteria = new Criteria();
          criteria.setAccuracy(Criteria.ACCURACY_COARSE);   //default

          // user defines the criteria
          choose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 if(fineAcc.isChecked()){
                      criteria.setAccuracy(Criteria.ACCURACY_FINE);
                      choice.setText("fine accuracy selected");
                 }else {
                     criteria.setAccuracy(Criteria.ACCURACY_COARSE);
                     choice.setText("coarse accuracy selected");
                 }  
            }
          });
          criteria.setCostAllowed(false); 
          // get the best provider depending on the criteria
          provider = locationManager.getBestProvider(criteria, false);

          // the last known location of this provider
          Location location = locationManager.getLastKnownLocation(provider);

          mylistener = new MyLocationListener();

          if (location != null) {
              mylistener.onLocationChanged(location);
          } else {
              // leads to the settings because there is no last known location
              Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
              startActivity(intent);
          }
          // location updates: at least 1 meter and 200millsecs change
          locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
      }

      private class MyLocationListener implements LocationListener {

          @Override
          public void onLocationChanged(Location location) {
            // Initialize the location fields
              latitude.setText("Latitude: "+String.valueOf(location.getLatitude()));
              longitude.setText("Longitude: "+String.valueOf(location.getLongitude()));
              provText.setText(provider + " provider has been selected.");

              Toast.makeText(MainActivity.this,  "Location changed!",
                        Toast.LENGTH_SHORT).show();
          }

          @Override
          public void onStatusChanged(String provider, int status, Bundle extras) {
              Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
                        Toast.LENGTH_SHORT).show();
          }

          @Override
          public void onProviderEnabled(String provider) {
              Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",
                Toast.LENGTH_SHORT).show();

          }

          @Override
          public void onProviderDisabled(String provider) {
              Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!",
                Toast.LENGTH_SHORT).show();
          }
      }
}

AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javacodegeeks.android.locationservicetest"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.javacodegeeks.android.locationservicetest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
    
answered by 28.09.2016 в 03:31