This is my coding below, it is giving me an output but its not my exact location. (Its giving me some location in USA). I implemented a facility to get the user's current location using the Fused Location Provider API. and also i created intent service to fetch address from latitude and longitude using Geocoder. Please help me out with this issue for my project. Here is my coding below:
This is my main Activity
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);
}
}
Constant.java file
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;
}