getLastKnownLocation始终返回null - API 23

时间:2015-12-24 01:27:30

标签: android

我试图制作一个适用于用户位置的应用程序。 首先,我做了一个小测试应用程序,以返回用户在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);
}

}

1 个答案:

答案 0 :(得分:1)

对于getLastKnownLocation工作,我执行了以下步骤:

  • 我打开终端并输入命令“telnet localhost 5554”,其中5554指的是AVD端口
  • 打开AVD上安装的地图应用程序
  • 在终端中输入命令行“geo fix 12 45”。在此示例中,您可以键入任何纬度和经度信息。

在那之后,它设法获得了位置。

enter image description here