获取用户在Android API 23中的位置

时间:2016-10-08 15:47:03

标签: android gps location

我可以编写获取用户位置的代码,并且在API< 23.但是在API 23及更高版本中,我的代码在Log中没有返回任何内容。

更多详情:
我启用手动设备的GPS。 在第一次运行时,应用程序请求权限并且没有日志返回 在下一次运行时,应用程序将返回我准备好的Toast(检查您的提供商)。

这是我写的代码:

public class MainActivity extends AppCompatActivity implements LocationListener {

private static final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 124;
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 123;

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

    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

        } else {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_FINE_LOCATION);
        }
    }
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)) {

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSIONS_REQUEST_COARSE_LOCATION);

        }
    }

    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;
    }
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(new Criteria(), false);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location == null) {
        Toast.makeText(this, "Check your provider", Toast.LENGTH_SHORT).show();
    } else {
        Log.i("New Location", "lat: " + location.getLatitude());
        Log.i("New Location", "lng: " + location.getLongitude());
    }
}

@Override
public void onLocationChanged(Location location) {
    Log.i("Location", "lat: " + location.getLatitude());
    Log.i("Location", "lng: " + location.getLongitude());
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

}

1 个答案:

答案 0 :(得分:5)

在Android API 23+中,有一种新方法可以处理被视为“危险”的权限,其中包括android.permission.ACCESS_FINE_LOCATIONandroid.permission.ACCESS_COARSE_LOCATION等。

如果您已使用android.permission.ACCESS_COARSE_LOCATION,则无需处理android.permission.ACCESS_FINE_LOCATION

请从官方文档中查看此链接,该文档向您展示如何在Android API 23 +中运行时处理权限。

https://developer.android.com/training/permissions/requesting.html

这个也可以帮到你。

https://developer.android.com/guide/topics/location/strategies.html

如何检查权限:

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
    Manifest.permission.ACCESS_FINE_LOCATION);

如何申请权限:

if (ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.ACCESS_FINE_LOCATION)
    != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.ACCESS_FINE_LOCATION)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
            MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

        // MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

请注意,即使您在运行时请求权限,您仍然必须在android清单中保留权限条目,如下所示:

<manifest ... >
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    ...
    <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
    <uses-feature android:name="android.hardware.location.gps" />
    ...
</manifest>

检查并授予权限后,您应该查看上面位置策略的链接,在那里您可以找到您缺少的详细信息。

基本上,您没有注册侦听器以接收位置更新。在onCreate()方法结束时添加此行后,您应该开始在日志中看到位置更新。

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);