获取当前gps位置android studio

时间:2017-02-09 02:26:02

标签: android google-maps gps location

我正在尝试编写一个Android应用程序,显然,它使用用户的位置在地图活动上放置标记,或者在这种情况下打印纬度和经度。但是,我找不到适合我的教程或上一个问题。我正在寻找以位置对象或纬度和经度的形式使用gps获取用户当前位置的绝对最简单的方法。我目前的代码如下,直接来自this tutorial

public class MainActivity extends AppCompatActivity
        implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    private TextView lat, lng;
    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;
    private boolean mRequestingLocationUpdates;
    private LocationRequest mLocationRequest;

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

        lat = (TextView) findViewById(R.id.lat);
        lng = (TextView) findViewById(R.id.lng);

        // Create an instance of GoogleAPIClient.
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
    }

    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
    }

    protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

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

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    @Override
    public void onConnected(Bundle bundle) {
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mCurrentLocation != null) {
            lat.setText(String.valueOf("Lat: " + mCurrentLocation.getLatitude()));
            lng.setText(String.valueOf("Lng: " + mCurrentLocation.getLongitude()));
        }
        else
            Log.i("Problem", "mCurrentLocation is null");

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        updateUI();
    }

    private void updateUI() {
        lat.setText(String.valueOf("Lat: " + mCurrentLocation.getLatitude()));
        lng.setText(String.valueOf("Lng: " + mCurrentLocation.getLongitude()));
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

我的AndroidManifest.xml是:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.root.locationtest">

    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="LocationTest"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我似乎总是得到日志消息&#34; mCurrentLocation为空&#34;,因此应用程序中没有任何内容发生变化。行mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);上还有一条警告,表示&#34;呼叫需要用户可能拒绝的许可。&#34;如有任何帮助,请提前感谢。

编辑: 我用&#34;呼叫需要权限包围了所有行,用户可能会拒绝该行#34;使用if语句:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED)

解决了这个警告。但是,onConnect()方法中的权限被拒绝,并且mCurrentLocation仍为空。

1 个答案:

答案 0 :(得分:0)

呼叫需要用户可能拒绝的权限。此错误是由于Android在运行时获得用户许可所需的更高版本。只是在清单中宣布无济于事。所以你需要添加权限代码。

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;
    }