我试图制作一个适用于用户位置的应用程序。
首先,我做了一个小测试应用程序,以返回用户在getLastKnownLocation
分配API 23请求的权限控制的位置。
位置控制由条件
决定if (location != null){
Log.i("LogX","Got Location!");
} else{ Log.i("LogX","It has location");}
问题是,在任何时候,返回"它有位置"。
我认为这应该与使用getLastKnownLocation
。
我的主要活动
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);
permissaoMapa();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null){
Log.i("LogX","Got Location!");
} else{ Log.i("LogX","It has location");}
}
private void permissaoMapa(){
if(ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)){
}else{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},0);
}
}else {
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int result : grantResults) {
if (result == PackageManager.PERMISSION_DENIED) {
return;
} else {
if (grantResults.length ==1) {
}
}
}
}
@Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lon = location.getLatitude();
Log.i("LogX",lat.toString());
Log.i("LogX", lon.toString());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
}