Search..

Sunday, June 12, 2022

How to get user Current Loction and Last Location from Android in 2022

 First f all you have to ask some manifest permission

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
add this dependency
implementation 'com.google.android.gms:play-services-location:18.0.0'
//also u will need goole play service classpath in proect level gradle but in
new verson android don't need
classpath 'com.google.gms:google-services:4.3.10'

Declare there variable at class level (MainActivity.java) as Your requiremwnt
private FusedLocationProviderClient mFusedLocationProviderClient;
private LocationRequest mLocationRequest;
 private LocationCallback mLocationCallback  //this variable is optional if want to
 automatic update location after interval 

 Note :- If you want to Only location then You don't need to google api key if want to show map in app
then you have to add google map api 
//Declare the one boolean variable to check permission granted or not if permssion is granted 
then set boolean value true ..also u can apply different logic rather then if ..else 
according to ur cutomization.
if (isPermisionGranted) {
mProgressDialog.setMessage("We are Fetching Your address");
mProgressDialog.show();
checkAllSettingForLocation();


} else {
Toast.makeText(BreakDownActivity.this, "please give me permision location permision first", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}

To caheck the permission user has been given the permission or not 
private void checkPermission()
{
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)==
PackageManager.PERMISSION_GRANTED){
checkAllSettingForLocation();  
isPermissionGranted=true;
    }else
{
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){

requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_FINE_LOCATION);
}
}
}
//override the method of onRequestPermissionResult

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==PERMISSION_FINE_LOCATION)
if (grantResults[0]==PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "permission accept", Toast.LENGTH_SHORT).show();



}else
{
Toast.makeText(MainActivity.this, "permissin deny please accept the permisson", Toast.LENGTH_SHORT).show();
}
}


//to check all setting for location
private void checkAllSettingForLocation() {


LocationSettingsRequest locationSettingsRequest=new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest).build();

SettingsClient client=LocationServices.getSettingsClient(BreakDownActivity.this);
Task<LocationSettingsResponse> locationSettingsResponseTask=
client.checkLocationSettings(locationSettingsRequest);

locationSettingsResponseTask.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(@NonNull LocationSettingsResponse locationSettingsResponse) {
//if all setting is good then update the location

getUserCurrentLocation();


}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if(e instanceof ResolvableApiException)
{
mProgressDialog.dismiss();
ResolvableApiException apiException=(ResolvableApiException) e;
try {
apiException.startResolutionForResult(BreakDownActivity.this,1002);
}catch (IntentSender.SendIntentException exception)
{
mProgressDialog.dismiss();
e.printStackTrace();
Toast.makeText(BreakDownActivity.this, "error :"+exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});



}
//this logic getcurrent location of user
private void getUserCurrentLocation() {
  mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

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.
LocationUpdate.checkSelfLoctionPermission(BreakDownActivity.this);

}
//this logic apply for to get location fast and more acccurate
//otherwise don't need to call getCurrentLocation and getLastLocation both together
if (!Constant.FETCHINGLOCTIONFIRSTTIEME) {
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.getToken();
mFusedLocationProviderClient.
getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, token)
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(@NonNull Location location) {

if (location != null) {
Constant.FETCHINGLOCTIONFIRSTTIEME=true;
getAdreessByLocation(location);
} else {
Common.AlertDialogBox(BreakDownActivity.this, "Fetching location ",
getString(R.string.fetchingerror));


mProgressDialog.dismiss();


}


}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
mProgressDialog.dismiss();
Toast.makeText(BreakDownActivity.this, "Exception error" + e.getMessage(), Toast.LENGTH_SHORT).show();


}
});
}
else {
mFusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(@NonNull Location location) {

if (location != null) {
getAdreessByLocation(location);
} else {
Common.AlertDialogBox(BreakDownActivity.this, "Fetching location ",
getString(R.string.fetchingerror));


mProgressDialog.dismiss();


}


}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
mProgressDialog.dismiss();
Toast.makeText(BreakDownActivity.this, "Exception error" + e.getMessage(), Toast.LENGTH_SHORT).show();

}
});


}
}
//getCustomer location by their location point
private void getAdreessByLocation(Location location) {
String adressinfo = "";

latitude = location.getLatitude();
longtitude = location.getLongitude();

Geocoder geocoder = new Geocoder(BreakDownActivity.this);
try {
List<Address> adress = geocoder.getFromLocation(latitude, longtitude, 1);
adressinfo = "Adress line :-\n " + adress.get(0).getAddressLine(0);
// +"\nget admin area : "+ adress.get(0).getAdminArea()
// +"\nget subAdmin area : "+adress.get(0).getSubAdminArea()
// + "\nget locality : "+adress.get(0).getLocality()
// + "\nget locale : "+adress.get(0).getLocale()
// + "\nget sublocality : "+adress.get(0).getSubLocality();


// + "\nget permisses : "+adress.get(0).getPremises()
// + "\nget feature name : "+adress.get(0).getFeatureName();

Log.d("adress=", adressinfo);

} catch (Exception e) {
mProgressDialog.dismiss();
Common.AlertDialogBox(BreakDownActivity.this, "Location Exception", "email us:-codingsick@gmail.com");

}
inflater = LayoutInflater.from(BreakDownActivity.this);

mView = inflater.inflate(R.layout.dialog_location_info, null);
mDialog = new Dialog(BreakDownActivity.this);
mDialog.setContentView(mView);
mDialog.setCancelable(true);
mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

mDialog.show();
mProgressDialog.dismiss();

getLocationValueFromDialog(adressinfo);
Toast.makeText(BreakDownActivity.this, "Fetching location success", Toast.LENGTH_SHORT).show();


}

No comments:

Post a Comment