使用GPS_PROVIDER和NETWORK_PROVIDER获取当前位置的问题

时间:2017-06-07 05:06:54

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

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

public void Setup() {

    var watcher = new FileSystemWatcher{
        Path = "My network path",
        NotifyFilter = NotifyFilters.FileName | NotifyFilters.Attributes | NotifyFilters.LastWrite | NotifyFilters.Security, Filter = "*"
    };

    watcher.Created += OnCreated;
    watcher.Renamed += OnRenamed;
    // uncomment out line below to add the error handler 
    watcher.Error += OnError; 
    watcher.IncludeSubdirectories = true;
    watcher.EnableRaisingEvents = true;
}

public static void OnRenamed(object source, RenamedEventArgs e)
{           
    try
    {                       
        MessageBox.Show("Raname call");
    }
    catch (Exception Ex)
    {
        errorLog(Ex);
    }
}           

public static void OnCreated(object source, FileSystemEventArgs e)
{
    try
    {
        MessageBox.Show("OnCreated call");
    }
    catch (Exception Ex)
    {
         errorLog(Ex);
    }
}

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

我还在我的清单文件中提供了必要的权限。

可能是什么问题?

感谢。

6 个答案:

答案 0 :(得分:0)

这是我的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;
    }





}

答案 1 :(得分:0)

mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);   // 'this' is  onLocationChanged()

@Override
public void onLocationChanged(Location location) {
         mCurrentLatitude = location.getLatitude();
         mCurrentLongitude = location.getLongitude();
}

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

正如JayDeep Patel引用我的答案,

我使用了融合的谷歌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()));
    }
}

答案 4 :(得分:0)

试用此代码

GPSTracker gps = new GPSTracker(context);

将此课程调用到您的MainActivity.java

{{1}}

答案 5 :(得分:0)

尝试使用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);

        }
    }