【问题标题】:Issue in getting Current Location with GPS_PROVIDER and NETWORK_PROVIDER使用 GPS_PROVIDER 和 NETWORK_PROVIDER 获取当前位置的问题
【发布时间】:2017-11-08 07:02:33
【问题描述】:

我试图在我的 android 应用程序中获取当前位置。但是,每次我将我的位置设为空时。我做了如下:

private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

我不知道解决方案,因为我正在检查 NETWORK_PROVIDER 和 GPS_PROVIDER。但是,每次都将 mLocation 设为 null。

我也在我的 Manifest 文件中授予了必要的权限。

可能是什么问题?

谢谢。

【问题讨论】:

  • LocationServices.FusedLocationApi 是否同时检查 NETWORK_PROVIDER 和 GPS_PROVIDER ?
  • 谢谢@JaydeepPatel fusedapi 太棒了..!!!

标签: android google-maps location android-permissions android-gps


【解决方案1】:

这是我的带有位置更新的 MapsActivity 类,您可以使用我的代码更新您的代码

package com.example.vishal.gpsloc;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.vision.barcode.Barcode;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, com.google.android.gms.location.LocationListener, GoogleMap.OnMapClickListener, ResultCallback<Status> {

    GoogleMap mMap;

    private MarkerOptions marker1, marker2;
    private final int GEOFENCE_REQ_CODE = 0;
    private GoogleApiClient googleApiClient;
    private double longitude;
    private double latitude;
    double lat,lon;

    List latt=new ArrayList();
    List longi=new ArrayList();

    Location lastLocation;
    String ip=null;

    SharedPreferences pref;
    SharedPreferences.Editor editor;
    int flag=1;String cityName,stateName,countryName,root;

    private ArrayList<LatLng> points; //added
    Polyline line; //added

    File log,myDir;


    private static MQTT mqtt;
    private static BlockingConnection connection;


    private final int UPDATE_INTERVAL = 60000 ;
    private final int FASTEST_INTERVAL = 60000 ;
    private static final float SMALLEST_DISPLACEMENT = 0.25F; //quarter of a meter


    String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date()), cord, devname, devid = android.os.Build.SERIAL;
    @Override
    public void onBackPressed() {
        super.onBackPressed();


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            CheckConnection();
            if (!isGooglePlayServicesAvailable()) {
                System.out.println(" My Google Play Not Available");
                finish();
            }
            points = new ArrayList<LatLng>(); //added
            setContentView(R.layout.route_mapper);
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

            InitializeDB();

            //Initializing googleApiClient
            googleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            googleApiClient.connect();

            findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    PunchStop();
                }
            });



            if (this.mMap != null) {

                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    mMap.setMyLocationEnabled(true);
                    return;
                }

            }

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

        mqtt=new MQTT();
        try{
            if(ip==null){
                System.out.println("Mqtt Initialized in Maps Activity");
                ip="demo.aiotm.in:1883";
            }
            //mqtt.setHost("tcp://"+ip);
            mqtt.setHost("tcp://10.30.60.242:1883");
            connection = mqtt.blockingConnection();
            connection.connect();
        }catch (Exception e){
            e.printStackTrace();

        }
    }

    private void InitializeDB() {
        pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        editor = pref.edit();
        if (isExternalStorageReadable() == true && isExternalStorageWritable() == true) {
            root = Environment.getExternalStorageDirectory().toString();
            myDir = new File(root + "/GpsTracking");
            myDir.mkdirs();
            log = new File (myDir, "GpsLog");
            if (myDir.exists()) {
                System.out.println("Directory Already Exsists............");
            } else {
                try {
                    myDir = new File(root + "/GpsTracking");
                    myDir.mkdirs();
                    log = new File (myDir, "GpsLog");

                } catch (Exception e) {
                    Toast.makeText(getBaseContext()
                            ,e.toString(),
                            Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }


            }
        }else {Toast.makeText(getBaseContext(),
                "Permissions Not Availiable'",
                Toast.LENGTH_SHORT).show();}
    }

    private void PunchStop() {
        System.out.println("stop Location is "+latitude+","+longitude+"\t"+cityName   );
try {
    String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
    PrintWriter out = new PrintWriter(new FileWriter(log, true));
   out.append(currentDateTimeString+"\t"+latitude+","+longitude+"\t"+cityName+"\n");
   out.close();
    Toast.makeText(getBaseContext(),
            "Done writing SD 'GpsLog.txt'",
            Toast.LENGTH_SHORT).show();

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

        }


    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

    private void CheckConnection() {
        String answer=null;
        ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                answer="You are connected to a WiFi Network";
            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                answer="You are connected to a Mobile Network";
        }
        else
            answer = "No internet Connectivity";
        Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG).show();
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        getCurrentLocation();
        mMap.setOnMapLongClickListener(this);
        mMap.setOnMapClickListener(this);


    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if( keyCode == KeyEvent.KEYCODE_POWER ) {
            //Handle what you want in long press.
            Toast.makeText(getApplicationContext(),"Power Key Pressed",Toast.LENGTH_LONG).show();
                flag=1;
            return true;
        }
        return super.onKeyLongPress(keyCode, event);
    }

    private void getCurrentLocation() {
       //mMap.clear();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();

            System.out.println("Parameters are ::" + latitude + ":" + longitude);
            //moving the map to location
            moveMap();

        }
    }

    private void moveMap() {
        /**
         * Creating the latlng object to store lat, long coordinates
         * adding marker to map
         * move the camera with animation
         */
        LatLng latLng = new LatLng(latitude, longitude);
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = null;
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
            cityName = addresses.get(0).getAddressLine(0);
            stateName = addresses.get(0).getAddressLine(1);
            countryName = addresses.get(0).getAddressLine(2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
                .draggable(true)
                .title(cityName))
                .showInfoWindow();
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        mMap.getUiSettings().setZoomControlsEnabled(true);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i("info", "Connection Failed");
        try {
          //  connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Toast.makeText(MapsActivity.this, "Connected", Toast.LENGTH_SHORT).show();
        getCurrentLocation();

        Log.i("info", "onConnected()");
        getLastKnownLocation();

    }

    private void getLastKnownLocation() {
        Log.d("INFO", "getLastKnownLocation()");
        System.out.println("info :: getLastKnownLocation");
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
       lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (lastLocation != null) {
            Log.i("INFO", "LasKnown location. " +
                    "Long: " + lastLocation.getLongitude() +
                    " | Lat: " + lastLocation.getLatitude());
            writeLastLocation();
            startLocationUpdates();
        } else {
            Log.w("INFO", "No location retrieved yet");
            startLocationUpdates();
        }


    }

    private LocationRequest locationRequest;


    // Start location Updatess
    private void startLocationUpdates() {
        Log.i("INFO", "startLocationUpdates()");

        pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        editor = pref.edit();

        locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setSmallestDisplacement(SMALLEST_DISPLACEMENT)
                .setFastestInterval(FASTEST_INTERVAL);


        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {

    }

    @Override
    public void onMapLongClick(LatLng latLng) {

        mMap.clear();
        marker1 = null;
        marker2 = null;
        getCurrentLocation();

    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d("INFO", "onLocationChanged ["+location+"]");
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = null;
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            cityName = addresses.get(0).getAddressLine(0);
            stateName = addresses.get(0).getAddressLine(1);
            countryName = addresses.get(0).getAddressLine(2);
        } catch (IOException e) {
            e.printStackTrace();
        }

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true)
                .title(cityName))
                .showInfoWindow();

        points.add(latLng);
        redrawline();
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        mMap.getUiSettings().setZoomControlsEnabled(true);

        lastLocation = location;
        writeActualLocation(location);

    }

    private void redrawline() {
        mMap.clear();  //clears all Markers and Polylines

        PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
        for (int i = 0; i < points.size(); i++) {
            LatLng point = points.get(i);
            options.add(point);
        }
       getCurrentLocation(); //add Marker in current position
        line = mMap.addPolyline(options); //add Polyline

    }

    // Write location coordinates on UI
    private void writeActualLocation(Location location) {
        Log.d( "Actual Lat: ", String.valueOf(location.getLatitude()));
        Log.d( "Actual Long: ", String.valueOf(location.getLongitude()));

        lat=location.getLatitude();
        lon=location.getLongitude();
        LatLng latLng=new LatLng(lat,lon);
        mMap.addMarker(new MarkerOptions()
        .position(latLng));


    }

    private void writeLastLocation() {
        writeActualLocation(lastLocation);
    }


    @Override
    public void onResult(@NonNull Status status) {
        Log.i("INFO", "onResult: " + status);
        if ( status.isSuccess() ) {
           System.out.println("Status Succes");
            Toast.makeText(getApplicationContext(),"Status Succes",Toast.LENGTH_LONG).show();
           // drawGeofence();
        } else {
            System.out.println("Status failed");
            Toast.makeText(getApplicationContext(),"Status Failed",Toast.LENGTH_LONG).show();
        }
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }





}

【讨论】:

    【解决方案2】:
    mLocationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                0,
                                0, this);   // 'this' is  onLocationChanged()
    
    @Override
    public void onLocationChanged(Location location) {
             mCurrentLatitude = location.getLatitude();
             mCurrentLongitude = location.getLongitude();
    }
    

    【讨论】:

      【解决方案3】:

      用户必须手动开启定位服务。这是代码。使用以下方法打开位置服务。还要放置清单权限

       public void checkLocationService() {
          LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
          boolean gps_enabled = false;
          boolean network_enabled = false;
      
          try {
              gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
          } catch (Exception ex) {
          }
      
          try {
              network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
          } catch (Exception ex) {
          }
      
          if (!gps_enabled && !network_enabled) {
              // notify user
              final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
              dialog.setMessage("GPS Not Enabled");
              dialog.setCancelable(false);
              dialog.setPositiveButton("Set", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                      // TODO Auto-generated method stub
                      Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                      startActivity(myIntent);
                      //get gps
                  }
              });
              dialog.setNegativeButton("Skip", new DialogInterface.OnClickListener() {
      
                  @Override
                  public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                      // TODO Auto-generated method stub
      
                  }
              });
              dialog.show();
          }
      }
      

      权限:

      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
       />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      

      【讨论】:

        【解决方案4】:

        正如 JayDeep Patel 引用我的答案,

        我使用了 fused google api,在我的 onConnected() 方法中获得准确的位置,如下所示:(成功:))

        请。看看:它真的有效:

        private void getLocation() {
            try {
                if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    Constant.displayLogE(">> PErmission >> ", ">> not granted");
                    return;
                } else {
                    mLocationManager = (LocationManager) mContext
                            .getSystemService(LOCATION_SERVICE);
                    // getting GPS status
                    boolean isGPSEnabled = mLocationManager
                            .isProviderEnabled(LocationManager.GPS_PROVIDER);
                    // getting network status
                    boolean isNetworkEnabled = mLocationManager
                            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                    if (!isGPSEnabled && !isNetworkEnabled) {
                        // no network provider is enabled
                    } else {
                        if (isNetworkEnabled) {
                            mLocationManager.requestLocationUpdates(
                                    LocationManager.NETWORK_PROVIDER,
                                    0,
                                    0, this);
                            if (mLocationManager != null) {
        
                                mLocation = mLocationManager
                                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                                if (mLocation != null) {
                                    mCurrentLatitude = mLocation.getLatitude();
                                    mCurrentLongitude = mLocation.getLongitude();
                                    loadFilterListData();
                                } else {
                                    mCurrentLatitude = mLastLocation.getLatitude();
                                    mCurrentLongitude = mLastLocation.getLongitude();
                                    loadFilterListData();
                                }
                            }
                        } else if (isGPSEnabled) {
                            if (mLocation == null) {
                                mLocationManager.requestLocationUpdates(
                                        LocationManager.GPS_PROVIDER,
                                        0,
                                        0, this);
                                if (mLocationManager != null) {
                                    mLocation = mLocationManager
                                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                    if (mLocation != null) {
                                        mCurrentLatitude = mLocation.getLatitude();
                                        mCurrentLongitude = mLocation.getLongitude();
                                        loadFilterListData();
                                    } else {
                                        mCurrentLatitude = mLastLocation.getLatitude();
                                        mCurrentLongitude = mLastLocation.getLongitude();
                                        loadFilterListData();
                                    }
                                }
                            }
                        }
                        if (mLastLocation == null) {
                            Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        
        }
        

        下面是我的 onConnected() 方法:

        @Override
        public void onConnected(@Nullable Bundle bundle) {
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mLastLocation != null) {
                // here we go you can see current lat long.
                Log.e(TAG, "onConnected: " + String.valueOf(mLastLocation.getLatitude()) + ":" + String.valueOf(mLastLocation.getLongitude()));
            }
        }
        

        【讨论】:

          【解决方案5】:

          试试这个代码

          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.app.ActivityCompat;
          import android.util.Log;
          import android.widget.Toast;
          
          
          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
          
              // The minimum distance to change Updates in meters
              private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
              // The minimum time between updates in milliseconds
              private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 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);
                      //Toast.makeText(mContext, "isGPSEnabled = "+isGPSEnabled, Toast.LENGTH_SHORT).show();
                      // getting network status
                      isNetworkEnabled = locationManager
                              .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
          //            Toast.makeText(mContext, "isNetworkEnabled = "+isNetworkEnabled, Toast.LENGTH_SHORT).show();
          
                      if (!isGPSEnabled && !isNetworkEnabled) {
                          // no network provider is enabled
                          showSettingsAlert();
                          Toast.makeText(mContext, "No Internet Connection", Toast.LENGTH_SHORT).show();
                      } else {
                          this.canGetLocation = true;
                          // First get location from Network Provider
                          if (isNetworkEnabled) {
                              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) {
                                      Log.d("isNetworkEbanbled", "Network Available");
                                      latitude = location.getLatitude();
                                      longitude = location.getLongitude();
                                  }
                              }
                          }
          
                          // if GPS Enabled get lat/long using GPS Services
                          if (isGPSEnabled) {
                              if (location == null) {
                                  if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
                                          PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                                          (this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                                  {
                                      locationManager.requestLocationUpdates(
                                              LocationManager.GPS_PROVIDER,
                                              MIN_TIME_BW_UPDATES,
                                              MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                                      Log.d("GPS Enabled", "GPS is Enabled");
                                      if (locationManager != null) {
                                          location = locationManager
                                                  .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                          if (location != null) {
                                              Log.d("isGPSEnabled", "GPS");
                                              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
               */
              public void stopUsingGPS() {
                  if (locationManager != null) {
                      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                              != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                              Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                          return;
                      }
                      locationManager.removeUpdates(GPSTracker.this);
                  }
              }
          
              /**
               * 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/wifi enabled
               *
               * @return boolean
               */
              public boolean canGetLocation() {
                  return this.canGetLocation;
              }
          
              /**
               * Function to show settings alert dialog
               * On pressing Settings button will lauch Settings Options
               */
              public void showSettingsAlert() {
                  AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
          
                  // Setting Dialog Title
                  alertDialog.setTitle("GPS  settings");
          
                  // Setting Dialog Message
                  alertDialog.setMessage("GPS is not enabled. Go to Seeting and Please Enabled GPS");
          
                  // On pressing 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 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;
              }
          
          }
          

          在你的 MainActivity.java 中调用这个类

          GPSTracker gps = new GPSTracker(context);
          

          【讨论】:

            【解决方案6】:

            尝试使用 GoogleApiClient 获取用户当前位置

            示例代码:

            首先您需要建立与 googleApiclient 的连接

            private synchronized void buildGoogleApiClient(){
                mGoogleApiClient = new GoogleApiClient.Builder(YourApplication.getContext())
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .addApi(LocationServices.API)
                        .build();
                mGoogleApiClient.connect();
            }
            

            Android 6.0 及以上版本请求权限

            public void checkLocationPermission(){
                if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                    // You don't have the permission you need to request it 
                    ActivityCompat.requestPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION), REQ_CODE);
                }else{
                    // You have the permission.
                    requestLocationAccess();
                }
            }
            

            然后执行 onRequestPermissionResult 来检查用户是否授予权限

             @Override
                public void onRequestPermissionsResult(int requestCode,
                                                       String permissions[], int[] grantResults) {
                    switch (requestCode) {
            
                        case REQUEST_LOCATION: {
                            // If request is cancelled, the result arrays are empty.
            
                            if (grantResults.length > 0
                                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                                requestLocationAccess();
                            } else {
            
            
                                    Snackbar.make(findViewById(android.R.id.content), "Please Allow to access to your Location",
                                            Snackbar.LENGTH_LONG).setAction("Allow",
                                            new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    Intent intent = new Intent();
                                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                                                    intent.setData(Uri.parse("package:" + getPackageName()));
            
                                                    startActivity(intent);
            
                                                }
                                            }).show();
            
                            }
                            return;
                        }
            
                        // other 'case' lines to check for other
                        // permissions this app might request
                    }
                }
            

            创建方法 requestLocationAccess 您将在其中访问位置

              public void requestLocationAccess(){
                    LocationRequest mLocationRequest = new LocationRequest();
                    mLocationRequest.setInterval((long) (LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS*1.1));
                    mLocationRequest.setFastestInterval(LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS);
                    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                    final LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
                    builder.setAlwaysShow(true); //this is the key ingredient
                    com.google.android.gms.common.api.PendingResult<LocationSettingsResult> result =
                                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
                    result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
                        @Override
                        public void onResult(@NonNull LocationSettingsResult result){
                            if(requester != null){
                                final Status resultStatus = result.getStatus();
                                switch(resultStatus.getStatusCode()){
                                    case LocationSettingsStatusCodes.SUCCESS:
                                        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                                                    googleApiClient, locationRequest, YourActivity.this);
            
            
            
                                        break;
                                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                        // Location settings are not satisfied. But could be fixed by showing the user a dialog.
            ActivityCompat.requestPermissions(YourActivity.this, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
                                        try{
                                            resultStatus.startResolutionForResult(this, REQUEST_LOCATION);
                                            break;
                                        }catch(IntentSender.SendIntentException ignored){}
                                    }
                                }
                            }
                        }
                    });  
                }
            

            然后实现 GoogleApliClient 回调onConnected 可以简单的获取用户位置

             @Override
                public void onConnected(@Nullable Bundle bundle) {
            
                    if (ContextCompat
                            .checkSelfPermission(this,
                                    ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                        location = LocationServices.FusedLocationApi.getLastLocation(
                                googleApiClient);
            
                    }
                }
            

            【讨论】:

            • 这段代码对我有用。如果您有任何问题,请告诉我@ZaptechDev Kumar
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-06-15
            • 1970-01-01
            • 2017-10-06
            • 1970-01-01
            • 2016-10-21
            • 1970-01-01
            相关资源
            最近更新 更多