未通过位置管理器Android检索位置

时间:2017-01-16 15:48:33

标签: android google-maps locationmanager

我正在尝试检索我的经度和纬度,以便使用Google商家信息获取一些JSON。问题是它甚至没有进入LocationListener,我从来没有看到该日志消息。我想获得我当前位置的经度和纬度。有人有什么想法吗?

这是我的代码:

public class ListRestActivity extends AppCompatActivity {


private Location mLastLocation;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
        new GetNearbyPlacesData().execute();
    }

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private boolean checkLocationPermission() {{
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Asking user if explanation is needed
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

                //Prompt the user once explanation has been shown
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }

}
}

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        Log.d("onLocationChanged", "entered");

        mLastLocation = location;

        //Place current location marker
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }


};

}

0 个答案:

没有答案