无法获取用户位置

时间:2019-09-26 23:19:04

标签: android permissions gps location userlocation

因此,我尝试获取用户位置,并希望将其作为Toast()或在日志中弹出,但没有任何反应。

我已将<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>添加到清单中,这是我的课程:

public class MainActivity extends AppCompatActivity {

private LocationManager locationManager;
private LocationListener locationListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get the users location
    locationManager = (LocationManager) 
this.getSystemService(Context.LOCATION_SERVICE);

    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            Log.i("LOCATION", location.toString());
            Toast.makeText(MainActivity.this, location.toString(), 
Toast.LENGTH_SHORT).show();
        }

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

            Log.i("STATUS", String.valueOf(status));
        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    // Ask users permission to get location
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == 1) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
            }
        }
    }
}
}

该应用首次请求权限,在我接受之后,它并未显示任何通过OnStatusChanges()方法获得位置的迹象。我尝试过使用lastKnownLocation(),它可以正常工作,但仅此而已...

有什么想法吗?

谢谢!

0 个答案:

没有答案