我的Lat Long始终显示0.0

时间:2017-04-06 06:46:18

标签: android google-api-client android-location locationlistener android-gps

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private final FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;


private double currentLattitude;
private double currentLongitude;

Button button;
TextView textView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();


    button = (Button) findViewById(R.id.btn_start);
    textView = (TextView) findViewById(R.id.txt_route);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            textView.setText(String.valueOf(currentLattitude + currentLongitude));



        }
    });
}

@Override
protected void onResume() {
    super.onResume();

    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();

    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onConnected(Bundle arg0) {
    final LocationRequest locationRequest = LocationRequest.create();
    locationRequest
            .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
    }
    fusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient,
            locationRequest, this);


    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (location == null) {

//            
  LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

        fusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient,
                locationRequest, this);

       // currentLattitude = location.getLatitude();
       // currentLongitude = location.getLongitude();
        Log.e("Lat" , ""  +currentLattitude);
        Log.e("Long" , ""  +currentLongitude);



    } else {

        currentLattitude = location.getLatitude();
        currentLongitude = location.getLongitude();

        Log.e("Lat" , ""  +currentLattitude);
        Log.e("Long" , ""  +currentLongitude);

    }
}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onLocationChanged(Location location) {
    // the location is no more than 10 min old, and with reasonable
    // accurarcy (50m), done
    if (System.currentTimeMillis() < location.getTime() + 10 * 60 * 1000
            && location.getAccuracy() < 50) {
        mGoogleApiClient.disconnect();
        mGoogleApiClient = null;
    }
}
}

在我的应用程序中,我获得了长期用户而没有启用移动GPS定位。我尝试了很多代码,但是这段代码总是抛出LAT LONG 0.0。请帮我解决这个问题。告诉我这段代码会出现什么问题。

3 个答案:

答案 0 :(得分:0)

基本上, Manifest.permission.ACCESS_FINE_LOCATION - 这将适用于GPS Manifest.permission.ACCESS_COARSE_LOCATION - 这将适用于网络

所以改变你的&amp;&amp;与||会对你有用,目前你要求两者都应该是允许的。

if (ActivityCompat.checkSelfPermission(this, `Manifest.permission.ACCESS_FINE_LOCATION`) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, 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;
    }

答案 1 :(得分:0)

您应该通过从函数中传递的Location对象获取纬度和经度来获取'onLocationChanged'回调中的坐标。 还要检查你的清单是否有这个:

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

答案 2 :(得分:0)

在“OnCreate”中添加此代码:


// CHECK LOCATION SERVICES IS ON
        LocationManagerControl locationManagerControl = new LocationManagerControl(this);
        try {
            if (locationManagerControl.isLocationServiceAvailable()) {
                try {
                    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) {
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                locationListener = new LocationListener() {
                    // @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                    }

                    // @Override
                    public void onLocationChanged(Location location) {
                        user_lat = location.getLatitude();
                        user_lng = location.getLongitude();

                    }
                };


            } else {
                locationManagerControl.createLocationServiceError(MainActivity.this);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

你想在任何你想要的地方打电话:

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

不要忘记添加:

LocationManager locationManager;
LocationListener locationListener;

并在AndroidManifest.xml文件中为您的应用程序添加以下权限

  • INTERNET
  • ACCESS_FINE_LOCATION
  • ACCESS_COARSE_LOCATION

我希望这有帮助..