[英]How to get the Get Current Latitude, Longitude and Address for my app in Android Studio
这是我下面的编码,它给了我一个 output 但它不是我的确切位置。 (它给了我在美国的一些位置)。 我使用 Fused Location Provider API 实现了一个工具来获取用户的当前位置。 我还创建了意图服务来使用地理编码器从纬度和经度中获取地址。 请帮我解决我的项目的这个问题。 下面是我的编码:
这是我的主要活动
public class ContactDetails extends AppCompatActivity {
private static final int REQUEST_CODE_LOCATION_PERMISSION = 1;
public TextView LatLong;
ProgressBar pb;
private ResultReceiver resultReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_details);
resultReceiver=new AddressResultReceiver(new Handler());
LatLong = (TextView) findViewById(R.id.latlong);
pb = (ProgressBar) findViewById(R.id.progressBar);
findViewById(R.id.buttonGetCurrentLocation).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(
getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
ContactDetails.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION_PERMISSION
);
} else {
getCurrentLocation();
}
}
});
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_LOCATION_PERMISSION && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
private void getCurrentLocation() {
pb.setVisibility(View.VISIBLE);
final LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
// return;
}
LocationServices.getFusedLocationProviderClient(ContactDetails.this)
.requestLocationUpdates(locationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
LocationServices.getFusedLocationProviderClient(ContactDetails.this)
.removeLocationUpdates(this);
if (locationResult != null && locationResult.getLocations().size() > 0) {
int latestLocationIndex = locationResult.getLocations().size() - 1;
double latitude =
locationResult.getLocations().get(latestLocationIndex).getLatitude();
double longitude =
locationResult.getLocations().get(latestLocationIndex).getLongitude();
LatLong.setText(String.format("Latitude: %s\nLongtitude: %s", latitude, longitude));
Location location= new Location("providerNA");
location.setLatitude(latitude);
location.setLongitude(longitude);
fetchAddressFromLatLong(location);
} else {
pb.setVisibility(View.GONE);
}
}
}, Looper.getMainLooper());
}
private void fetchAddressFromLatLong(Location location){
Intent intent=new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, resultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, location);
startService(intent);
}
private class AddressResultReceiver extends ResultReceiver {
AddressResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if(resultCode== Constants.SUCCESS_RESULT) {
add.setText(resultData.getString(Constants.RESULT_DATA_KEY));
}else {
Toast.makeText(ContactDetails.this, resultData.getString(Constants.RESULT_DATA_KEY), Toast.LENGTH_SHORT).show();
}
pb.setVisibility(View.GONE);
}
}
FetchAddressIntentService.java
public class FetchAddressIntentService extends IntentService {
private ResultReceiver resultReceiver;
public FetchAddressIntentService() {
super("FetchAddressIntentService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
if(intent != null) {
String errorMessage="";
resultReceiver=intent.getParcelableExtra(Constants.RECEIVER);
Location location= intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
if(location==null){
return;
}
Geocoder geocoder= new Geocoder(this, Locale.getDefault());
List<Address> addresses=null;
try {
addresses=geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (Exception exception) {
errorMessage= exception.getMessage();
}
if (addresses== null || addresses.isEmpty()){
deliverResultToReceiver(Constants.FAILURE_RESULT,errorMessage);
}else {
Address address=addresses.get(0);
ArrayList<String> addressFragments= new ArrayList<>();
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++){
addressFragments.add(address.getAddressLine(i));
}
deliverResultToReceiver(
Constants.SUCCESS_RESULT,
TextUtils.join(
Objects.requireNonNull(System.getProperty("line.separator")),
addressFragments
)
);
}
}
}
private void deliverResultToReceiver(int resultCode, String addressMessage) {
Bundle bundle=new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, addressMessage);
resultReceiver.send(resultCode, bundle);
}
}
常量.java 文件
class Constants {
private static final String PACKAGE_NAME="com.example.registration";
static final String RESULT_DATA_KEY= PACKAGE_NAME + ".RESULT_DATA_KEY";
static final String RECEIVER= PACKAGE_NAME+ ".RECEIVER";
static final String LOCATION_DATA_EXTRA = PACKAGE_NAME+ ".LOCATION_DATA_EXTRA";
static final int SUCCESS_RESULT=1;
static final int FAILURE_RESULT= 0;
}
如果你在模拟器上运行你的应用程序,那么你应该发送一个位置来模拟它。 默认是 GooglePlex 的位置,也就是您收到的位置。
否则,您的精度可能不正确。
尝试检查此问题以模拟位置。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.