所以我一直在尝试获取用户位置,起初我使用的是一个名为“简单位置”的库,以使我的生活更轻松。直到我意识到我的一些用户位置恢复了陈旧状态。
我可以很清楚地看到用户位于一个位置,但是我发送的位置是最初打开应用程序时返回的位置。
此后,我开始尝试本地获取该位置,但是我运气不高。当我在听更改时,有时除非我移动,否则它有时可能拒绝更新,这不好,因为如果他们还在,我需要获取用户的位置。
public class MainActivity extends AppCompatActivity implements LocationListener {
Button button;
TextView textView;
LocationManager locationManager;
LocationListener locationListener;
public static String lat = "";
public static String lng = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("Button", "Pressed");
textView.setText("Latitude: " + lat + " Longitude: " + lng);
}
});
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new MainActivity();
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 10, 0, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 10, 0, locationListener);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 10:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
configureLocation();
return;
}
}
@Override
public void onLocationChanged(Location location) {
Log.d("Lat", "lat"+location.getLatitude());
Log.d("Lng", "lng"+location.getLongitude());
lat = String.valueOf(location.getLatitude());
lng = String.valueOf(location.getLongitude());
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
public void configureLocation(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET
}, 10);
}
return;
} else {
locationManager.requestLocationUpdates("gps", 1000, 0, locationListener);
}
}
}
这是我正在使用的测试应用。有没有办法在应用程序打开后立即向我提供有关用户所在位置的最新报告?