在Android中获取GPS位置

时间:2017-06-18 15:27:52

标签: android gps android-permissions

我正在尝试通过Android获取当前的GPS位置,它不起作用并显示错误。我还包含了所需的runtime permission,但它仍然无效。

MainActivity.java

public class MainActivity extends AppCompatActivity implements LocationListener {


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

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    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.
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    }



}

@Override
public void onLocationChanged(Location location) {
    double latitude=location.getLatitude();
    double longitude=location.getLongitude();

    Log.i("Geo_location","Latitude: "+latitude+" ,Longitude: "+longitude);
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

}

的AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shaloin.gps">

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    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>

它显示的错误是:  "gps" location provider requires ACCESS_FINE_LOCATION permission.  我为此添加了此链接Requesting Permissions at Run Time中所述的运行时权限。请帮忙。谢谢:))

1 个答案:

答案 0 :(得分:0)

您没有正确请求运行时权限。

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.
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

}

如果未授予权限,您将明确请求位置更新。但是在if条件下应该做的是,如果未授予权限,请求权限。

要解决此问题,请剪切locationManager.requestLocationUpdates的行并将其粘贴到大括号之外。

然后在if条件中检查SDK版本,如果它高于23,则请求权限。

if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        }
return;

最后,您需要创建一个覆盖“onRequestPermissionsResult”的方法。 创建方法必须在onCreate方法之外完成。

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            // start to find location...

        } else { // if permission is not granted

            // decide what you want to do if you don't get permissions
        }
    }
}

最后,您需要为每个权限标识唯一的最终int变量,以便根据变量值请求权限。这是在类的开头完成的,您可以在其中定义实例变量。

final int LOCATION_PERMISSION_REQUEST_CODE = 1252; //Note that the value 1252 is arbitrary.