我查看了其他问题,但无法找到答案。 无论如何,我试图获得设备的位置,它只是不会工作。我使用的是Android 5.0(API 21)。
public class MainActivity extends AppCompatActivity implements LocationListener {
LocationManager locationManager;
String provider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
Location location = locationManager.getLastKnownLocation(provider);
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
错误是在.getLastKnowLocation()中。它说我应该检查权限,但我已经将权限添加到Android清单。
uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_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;
}
但是当我运行它时,它总会返回; ,就像我没有权限一样。
答案 0 :(得分:1)
您需要启用运行时权限
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},1200);
答案 1 :(得分:1)
如果您只希望自己的应用程序达到API级别21,则可以在模块级别targetSdkVersion 21
文件中设置build.gradle
,这将使您面临的错误消失。
如果您希望开始定位API级别23或更高级别,则除了在清单中声明权限外,还需要在运行时请求权限。