我是android studio的新手,正在从事小型项目,但是当我尝试获取位置(经度和纬度)时,应用程序已成功构建,但随后遇到了问题。
问题是在智能手机上启动应用程序时,该应用程序始终停止运行
这是我的代码:
int LOCATION_PERMISSION_CODE = 1;
ActivityCompat.shouldShowRequestPermissionRationale(this , Manifest.permission.ACCESS_FINE_LOCATION );
ActivityCompat.requestPermissions(MainActivity.this , new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_PERMISSION_CODE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
final long meter = 1;
final long mill = 1;
LocationManager locationManger = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
assert locationManger != null;
locationManger.requestLocationUpdates(LocationManager.GPS_PROVIDER,meter,mill, new LocationListener() {
@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) {
}
});
Location lastLocationGPS = locationManger.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocationGPS == null) {
lastLocationGPS = locationManger.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
TextView textView2 = (TextView)findViewById(R.id.textView2);
TextView textView4 = (TextView)findViewById(R.id.textView4);
textView2.setText(Double.toString(lastLocationGPS.getLongitude()));
textView4.setText(Double.toString(lastLocationGPS.getLatitude()));
}
我尝试了您的代码,您面临的最可能的问题是,您正在检查清单上没有的两种权限。
请确保您应用的清单文件中包含以下两行:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
如果不是引起您问题的原因,请通过编辑问题以在“ logcat”窗口中添加您遇到的错误来提供有关问题的更多信息。