我想构建在用户离线时提供当前位置的代码。我创建了一个代码,其中我使用GPS提供商,但我只在用户在线时提供当前位置。我想获得用户的当前和新鲜的位置 这是代码
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener=new LocationListener() {
@Override
public void onLocationChanged(Location location) {
lat=location.getLatitude();
String mm = "";
longitude=location.getLongitude();
locationManager.removeUpdates(this);
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, longitude, 1);
Address obj = addresses.get(0);
mm = obj.getCountryName();
mm=mm+" , "+obj.getSubAdminArea();
mm=mm+" , "+obj.getSubLocality();
mm=mm+" , "+obj.getFeatureName();
Log.v("IGA", "Address" + mm);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] permissions,
int[] grantResults)
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
答案 0 :(得分:1)
请定义 online / offlin e
我建议你使用: locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListenerGPS, null);
您的更新代码应为:
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener=new LocationListener() {
@Override
public void onLocationChanged(Location location) {
lat=location.getLatitude();
String mm = "";
longitude=location.getLongitude();
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, longitude, 1);
Address obj = addresses.get(0);
mm = obj.getCountryName();
mm=mm+" , "+obj.getSubAdminArea();
mm=mm+" , "+obj.getSubLocality();
mm=mm+" , "+obj.getFeatureName();
Log.v("IGA", "Address" + mm);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
String[] permissions, int[] grantResults)
return;
}
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListenerGPS, null);