可以获取 Location 并在 android 4.0.3+ 上运行的应用程序

Application that can get Location and runs on android 4.0.3+

对于小于 6 的 android 版本,只需将这些权限请求添加到清单即可:

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

但对于 android 版本 6,我也需要明确请求许可才能获取位置:

requestPermissions(new String[]{ Manifest.permission.ACCESS_FINE_LOCATION}, 1340);

问题是,如果我添加上面的代码,应用程序只能在 android 6 上运行,而在较低版本上无法 运行,因为 requestPermissions 在较低版本上不存在。如果我删除它,我将无法获得 android 6.

上的位置

我该怎么做才能让我的应用程序能够在 android 4.0.3+

上获取位置

您可以检查 phone 的 API 级别,即 运行 您的应用程序,如下所示:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
     //later than 4.x - so here you can run the code
     //ideally you want to make this call in a helper method which you then annotate with the @TargetApi
     requestPermissions(new String[]{ Manifest.permission.ACCESS_FINE_LOCATION}, 1340);
    }
else{
  //nothing to do in your case ?
}

您还可以在要进行 "Lollipop+" 调用的方法中使用 @TargetApi(Build.VERSION_CODES.LOLLIPOP)