I want to create a app to Track the Users who installed my App, So i have a following code for tracking, This code working good but it will return only CITY NAME. But i need full details like street name, city, like wise .
public class GetCurrentLocation extends Activity
implements OnClickListener {
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb = null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to" +
" see the changes in coordinates." + "\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
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;
}
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Try this :
public void setCurrentLocation() {
if (UtilityMethods.isGPSEnabled(mContext)) {
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(LOCATION_PERMS, LOCATION_REQUEST);
// return;
} else {
getCurrentAddress();
}
} else {
alertbox("Gps Status", "Your Device's GPS is Disable", mContext);
}
}
Using LocationManager
public void getCurrentAddress() {
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
try {
if (Build.VERSION.SDK_INT >= 23 && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} catch (Exception ex) {
Log.i("msg", "fail to request location update, ignore", ex);
}
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String locality = addresses.get(0).getLocality();
String subLocality = addresses.get(0).getSubLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
if (subLocality != null) {
currentLocation = locality + "," + subLocality;
} else {
currentLocation = locality;
}
current_locality = locality;
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(HomeActivity.this, Constants.ToastConstatnts.ERROR_FETCHING_LOCATION, Toast.LENGTH_SHORT).show();
}
}
}
Use fused Location Provider to get current device latitude and longitude.
With the help of latitude and longitude, you can get city name and address.
To get full street name, use getMaxAddressLineIndex().
In onLocationChanged, check whether you are getting current location or not.
Edit:
String strAdd = "";
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(TabClubActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (!addresses.isEmpty()) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append(" ");
}
strAdd = strReturnedAddress.toString();
textview.setText(strAdd);
Log.e("MyCurrentLoctionAddress", "" + strReturnedAddress.toString());
cityName=addresses.get(0).getLocality();
} else {
// Log.e("MyCurrentLoctionAddress", "No Address returned!");
}
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
I tried the Geocoder however the results are unreliable. So better go for the nearbysearch googleapi for the result. It provides the city name directly. Here's the version of my implementation.
interface Api{
String BASE_URL = "https://maps.googleapis.com";
#GET("/maps/api/place/nearbysearch/json")
Call<List<ResultDO>> getPlaceDetailByLatLong(#Query("location") String type,#Query("radius") String radius,#Query("key")String key);
}
And in the main activity or fragment.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
API service = retrofit.create(API.class);
service.getCityResults(types, input, location, radius, key).enqueue(new Callback<List<ResultDO>>() {
#Override
public void onResponse(Call<List<ResultDO>> call, Response<List<ResultDO>> response) {
tvCity.setText(response.body().get(0).getVicinity());// first object gives me the city name
}
#Override
public void onFailure(Call<List<ResultDO>> call, Throwable t) {
}
});
You can get address (street name, city, country, etc) by converting Geographic Location (e.g Latitude, longitude) to address. This process called Reverse Geocoding this doc.
You can use FusedLocationProviderApi(), but it has been deprecated (here). The alternative, You can use FusedLocationProviderClient() to get LastKnownLocation, from LastKnownLocation object (contain latitude and longitude), so we can use to get address like street name, city, country, etc using Geocoder. The sample doc do synchronously. But here i am doing Asynchronously using AsyncTask. Hope this Help.
To get Current Location:
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.tasks.OnCompleteListener;
public class MainActivity extends AppCompatActivity{
//before public class MainActivity extends AppCompatActivity implements LocationListener,...,...
private static final String TAG = "MainActivity";
public static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 101;
private FusedLocationProviderClient mFusedLocationClient;
private Location mGetedLocation;
private double currentLat, currentLng;
private void getLastLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
return;
}
mFusedLocationClient.getLastLocation()
.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mGetedLocation = task.getResult();
//currentLat = mGetedLocation.getLatitude();
//currentLng = mGetedLocation.getLongitude();
//start reverse geocoding
//little different with the doc
(new GetAddressTask(this)).execute(mGetedLocation);
}else{
Log.e(TAG, "no location detected");
Log.w(TAG, "getLastLocation:exception", task.getException());
}
}
});
}
To Get Address from LastKnownLocation
//sorry, I forgot where I got this asyncTask code. So I did not mention the source.
//If anyone feels that making this code please comment.
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
GetAddressTask(Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground(Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e1) {
Log.e("LocationSampleActivity",
"IO Exception in getFromLocation()");
e1.printStackTrace();
return ("IO Exception trying to get address");
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments " +
Double.toString(loc.getLatitude()) +
" , " +
Double.toString(loc.getLongitude()) +
" passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
/*
address.getLocality(),
address.getCountryName());
*/
return address.getLocality();
} else {
return "No address found";
}
}
#Override
protected void onPostExecute(String address) {
if (address != null)
mtextView.setText(address);//=============================> GOT THIS
}
}
In the Activity Class makes a customized method :
private void getTheUserPermission() {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationGetter locationGetter = new LocationGetter(FreshMenuSearchActivity.this, REQUEST_LOCATION, locationManager);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationGetter.OnGPS();
} else {
locationGetter.getLocation();
}
}
Make a UserDefined Class name LocationGetter:-
public class LocationGetter {
private int REQUEST_LOCATION;
private FreshMenuSearchActivity mContext;
private LocationManager locationManager;
private Geocoder geocoder;
public LocationGetter(FreshMenuSearchActivity mContext, int requestLocation, LocationManager locationManager) {
this.mContext = mContext;
this.locationManager = locationManager;
this.REQUEST_LOCATION = requestLocation;
}
public void getLocation() {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mContext, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location LocationGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location LocationNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location LocationPassive = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (LocationGps != null) {
double lat = LocationGps.getLatitude();
double longi = LocationGps.getLongitude();
getTheAddress(lat, longi);
} else if (LocationNetwork != null) {
double lat = LocationNetwork.getLatitude();
double longi = LocationNetwork.getLongitude();
getTheAddress(lat, longi);
} else if (LocationPassive != null) {
double lat = LocationPassive.getLatitude();
double longi = LocationPassive.getLongitude();
getTheAddress(lat, longi);
} else {
Toast.makeText(mContext, "Can't Get Your Location", Toast.LENGTH_SHORT).show();
}
}
}
private void getTheAddress(double latitude, double longitude) {
List<Address> addresses;
geocoder = new Geocoder(mContext, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
Log.d("neel", address);
} catch (IOException e) {
e.printStackTrace();
}
}
public void OnGPS() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mContext.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Related
I have created program that will access your location, for that I required permission to allow access to my location. I know the permission to be applied and how to handle that permission to but I couldn't get that done in my main Program. Every time I try to add permission It doesn't read requestPermission() ,to make it read I ave added #RequiresApi(api = Build.VERSION_CODES.M) this too.Can anyone please tell me how to add that in my code.
I have two class: 1) NetwrokProviderActivity in which I'm calling my 2) class,ApplocationService. Here I'm sharing my code. Please help me to resolve this
Permission that I require
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;
}
#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)
{
configureButton();
return;
}
}
}
ApplocationClass in which I need to add this Permission
public AppLocationService(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled) {
if(location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
NetwrokprovideActivity
AppLocationService appLocationService;
Button btnNetworkProvider;
TextView txtLati;
TextView txtLongi;
TextView txtAddress;
TextView txtCity;
TextView txtState;
TextView txtCountry;
TextView txtPostalCode;
protected Context context=this;
Location location;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_provider);
txtLati= (TextView) findViewById(R.id.txt_Latitude);
txtLongi= (TextView) findViewById(R.id.txt_Longitude);
txtAddress= (TextView) findViewById(R.id.txt_NetAddress);
txtCity= (TextView) findViewById(R.id.txt_NetCity);
txtState= (TextView) findViewById(R.id.txt_NetState);
txtCountry= (TextView) findViewById(R.id.txt_NetCountry);
txtPostalCode= (TextView) findViewById(R.id.txt_NetPostalCode);
appLocationService = new AppLocationService(NetworkProviderActivity.this);
btnNetworkProvider = (Button) findViewById(R.id.btn_Location_NetworkProvider);
btnNetworkProvider.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation();
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
List<Address> addresses;
Geocoder geocoder=new Geocoder(context, Locale.getDefault());
txtLati.setText("Latitude: "+latitude);
txtLongi.setText("Longitude: "+ longitude);
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
Log.e(TAG,"network...");
txtAddress.setText("Address: "+address);
txtCity.setText("City: "+city);
txtState.setText("State: "+state);
txtCountry.setText("Country: "+country);
txtPostalCode.setText("Postal Code: "+postalCode);
}
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
NetworkProviderActivity.this);
alertDialog.setTitle(provider + " SETTINGS");
alertDialog
.setMessage(provider + " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
NetworkProviderActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
You need to add the permission on manifest, to support APIs equal and above 23 you also have to request programatically.
You need to add this in your maniufest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
I working with a project to find the address using latitude and longitude. I got answer in Jellybean but when comes to Lollipop and Marshmallow it only showing latitude and longitude, not getting address. It shows location provider is not found. Is there any error in my code?
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider,5000, 0,this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (location != null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
TextView longitude = (TextView) findViewById(R.id.textView);
TextView latitude = (TextView) findViewById(R.id.textView1);
longitude.setText("Current Longitude:" + location.getLongitude());
latitude.setText("Current Latitude:" + location.getLatitude());
Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
// String mylocation;
try {
List < Address > addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
address1.setText(address);
String city = addresses.get(0).getLocality();
textViewCity.setText(city);
String state = addresses.get(0).getAdminArea();
textViewState.setText(state);
String country = addresses.get(0).getCountryName();
textViewCountry.setText(country);
String postalCode = addresses.get(0).getPostalCode();
textViewPostal.setText(postalCode);
String knownName = addresses.get(0).getFeatureName();
System.out.println("Address >> " + address + " " +city+ " \n" + state + " \n" + country+ "\n"+postalCode+ "\n"+knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
add this class.
public class SingleShotLocationProvider {
public static interface LocationCallback {
public void onNewLocationAvailable(GPSCoordinates location);
}
// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, 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;
}
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}, null);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override public void onProviderEnabled(String provider) { }
#Override public void onProviderDisabled(String provider) { }
}, null);
}
}
}
// consider returning Location instead of this dummy wrapper class
public static class GPSCoordinates {
public float longitude = -1;
public float latitude = -1;
public GPSCoordinates(float theLatitude, float theLongitude) {
longitude = theLongitude;
latitude = theLatitude;
}
public GPSCoordinates(double theLatitude, double theLongitude) {
longitude = (float) theLongitude;
latitude = (float) theLatitude;
}
}
}
and use like this:
SingleShotLocationProvider.requestSingleUpdate(getActivity(),
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
lat = location.latitude;
lag = location.longitude;
}
});
here you can get lat - lag if your device location is enable. so also check that is enable or not.
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showEnableLocationDialog();
} else {
SingleShotLocationProvider.requestSingleUpdate(getActivity(),
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
lat = location.latitude;
lag = location.longitude;
}
});
}
public void showEnableLocationDialog() {
final android.app.AlertDialog.Builder builderDialog = new android.app.AlertDialog.Builder(getActivity());
builderDialog.setTitle("Enable Location");
builderDialog.setMessage("Please enable location for near by search");
builderDialog.setPositiveButton("Enable",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
builderDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//fetchImages();
}
});
android.app.AlertDialog alert = builderDialog.create();
alert.show();
}
and i hope you are asking run-time permission for location first. otherwise you will never get location.
i have develop app that when run take the city name by lat and long using a GPSTracker.java class and add this city name to url for retrive json data.
My code works very fine from API 18 to API 22 but now when i run my code on API 23 the geocoder doesn't work and city name is null
This is my code on Main Activity for retrive city name:
// To get City-Name from coordinates
GPSTracker gpsTracker = new GPSTracker(getActivity());
String cityName = null;
Geocoder gcd = new Geocoder(getContext(), Locale.ENGLISH);
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
Log.d("nome_cit", "debug_cit " + cityName);
// Controllo formattazione nomi Car2Go
if(cityName.equals("Rome")) {
nome_citta = "Roma";
}else if (cityName.equals("Florence")){
nome_citta = "Firenze";
}
else if (cityName.equals("Milan")){
nome_citta = "Milano";
}
else if (cityName.equals("Turin")){
nome_citta = "Torino";
}else if (cityName.equals("New York")){
nome_citta = "NewYorkCity";
}else if (cityName.equals("Los Angeles")){
nome_citta = "LosAngeles";
}
else if (cityName.equals("San Diego")){
nome_citta = "SanDiego";
}
else if (cityName.equals("Twin Cities")){
nome_citta = "TwinCities";
}
else if (cityName.equals("Vienna")) {
nome_citta = "wien";
}
else if (cityName.equals("Munich")) {
nome_citta = "München";
}
else if (cityName.equals("Osler")) {
nome_citta = "Rheinland";
}
// Controllo formattazione JCDecaux
else if (cityName.equals("Valencia")) {
nome_citta_test = "Valence";
}
else if (cityName.equals("Parigi")) {
nome_citta_test = "Paris";
}
else if (cityName.equals("Besançon")){
nome_citta_test = "Besancon";
}
else if (cityName.equals("Créteil")) {
nome_citta_test = "Creteil";
}
else {
nome_citta = cityName;
nome_citta_test = cityName;
}
}
else {
}
} catch (IOException e) {
e.printStackTrace();
}
on my map for my position i have set this permission:
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
.PERMISSION_GRANTED && ActivityCompat
.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager
.PERMISSION_GRANTED) {
/*Toast.makeText(getActivity(),
"Need location permission for map.setMyLocationEnabled(true);",
Toast.LENGTH_LONG).show();*/
MultiplePermissionsListener snackbarMultiplePermissionsListener =
SnackbarOnAnyDeniedMultiplePermissionsListener.Builder
.with((ViewGroup) getView(), "La app ha bisogno di ablitare i permessi di localizzaione per mostrare la mappa")
.withOpenSettingsButton("Settings")
.withCallback(new Snackbar.Callback() {
#Override
public void onShown(Snackbar snackbar) {
// Event handler for when the given Snackbar has been dismissed
}
#Override
public void onDismissed(Snackbar snackbar, int event) {
// Event handler for when the given Snackbar is visible
}
})
.build();
Dexter.checkPermissions(snackbarMultiplePermissionsListener, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE, Manifest.permission.GET_ACCOUNTS);
return;
}
and this is my GPSTracker.java class:
public final class GPSTracker implements LocationListener {
private final Context mContext;
// flag for GPS status
public boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Function to get the user's current location
*
* #return
*/
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("isGPSEnabled", "=" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v("isNetworkEnabled", "=" + isNetworkEnabled);
if (isGPSEnabled == false && isNetworkEnabled == false) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
location=null;
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
location=null;
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
// DecimalFormat latitude = new DecimalFormat("00.00");
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle(R.string.title);
// Setting Dialog Message
alertDialog
.setMessage(R.string.subtitle);
// On pressing Settings button
alertDialog.setPositiveButton(R.string.impostazioni,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton(R.string.cancella,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setCancelable(false);
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Also i have notice that using place picker on API 23 i recive this error:
Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
for this code:
if (resultCode == getActivity().RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
String addresses = place.getAddress().toString();
if (addresses != null) {
puntoA.setText(addresses);
}if (addresses.isEmpty()){
addresses = "(" + place.getLatLng().latitude + "," + place.getLatLng().longitude + ")";
puntoA.setText("nessun indirizzo disponibile " + addresses);
}
//puntoA.setText(addresses);
// Recupero coordinate
Geocoder geocoder = new Geocoder(getActivity());
List<Address> address = null;
try {
address = geocoder.getFromLocationName(addresses, 1);
} catch (IOException e) {
e.printStackTrace();
}
if(address.size() > 0) {
Lat = address.get(0).getLatitude();
Lon = address.get(0).getLongitude();
}
else if (address.size() == 0) {
Lat = place.getLatLng().latitude;
Lon = place.getLatLng().longitude;
}
but also this function works very well on other API version
Any help please?
now my code works fine on API 23 and i use this code:
// To get City-Name from coordinates
GPSTracker gpsTracker = new GPSTracker(getActivity());
Double LatFab = gpsTracker.getLatitude();
Double LonFab = gpsTracker.getLongitude();
List<Address> geocodeMatchess = null;
String Country_;
try {
geocodeMatchess = new Geocoder(getActivity(), Locale.ENGLISH).getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
if (geocodeMatchess.isEmpty()) {
}else {
Country_ = geocodeMatchess.get(0).getLocality();
citta_fab = Country_;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hope this hel you
my application is using GPS services now i in case the GPS is off the user have the option to navigate to the device settings and set the GPS on.
now i would like to handle the user selection,
in case the user turn on the GPS the app should run again the getLocation function other wise do nothing.
but i do not know how can i handle the result of the new activity because i run it from non activity class. the relevant method is LocationAlertDialog
this is my class code:
public class GPSportLocationManager {
private boolean gpsEnabled,networkEnabled,isLocationUpdating,tryLocating = true;
private LocationManager locationManager;
private Location currentLoc=null;
private Context context;
private OnLocationFoundListener listener;
private int networkLocCount=0,gpsLocCount=0;
public GPSportLocationManager(Context ctx,OnLocationFoundListener mListener){
this.context = ctx;
this.listener = mListener;
}
/**
* method which finding the device location.
*/
public void getLocation(){
listener.getLocationInProccess();
try {
locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gpsEnabled && !networkEnabled){
LocationAlertDialog();
}else{
if(gpsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Constants.GPS_MIN_TIME_BETWEEN_UPDATE,Constants.GPS_MIN_DISTANCE_CHANGE,gpsListener);
}if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
Constants.NETWORK_MIN_TIME_BETWEEN_UPDATE,Constants.NETWORK_MIN_DISTANCE_CHANGE,networkListener);
}
}
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable() {
#Override
public void run() {
if(currentLoc == null){
if(gpsEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else if(networkEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(currentLoc != null && listener !=null){
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
listener.onLocationFound(currentLoc);
}
}
}
},30, TimeUnit.SECONDS);
}catch (Exception e){
Toast.makeText(context,"Error while getting location"+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
/**
* GPS location listener handle the callbacks.
*/
private LocationListener gpsListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(gpsLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
gpsLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
private LocationListener networkListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(networkLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
networkLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public void LocationAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Location settings");
alertDialog
.setMessage("We cannot retrieve your location. Please click on Settings and make sure your GPS is enabled");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tryLocating =false;
listener.onLocationFound(currentLoc);
dialog.cancel();
}
});
alertDialog.show();
}
/**
* this function get Longitude and Latitude coordinates and send back the real street address.
* #param LATITUDE
* #param LONGITUDE
* #param ctx
* #return
*/
public String getCompleteAddressString(double LATITUDE, double LONGITUDE, Context ctx) {
String strAdd = "";
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
Log.w("My Current location address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current location address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current location address", "Can not get Address!");
}
return strAdd;
}
/**
* this function convert real address to geographical coordinates.
* #param strAddress -real address
* #return LatLng object which contain the coordinates
*/
public LatLng getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
Log.d("coordinates",p1.latitude+""+p1.longitude);
} catch (Exception ex) {
Log.d("Location Exception", "error converting address");
ex.printStackTrace();
}
return p1;
}
public boolean isTryLocating() {
return tryLocating;
}
}
I made an application in android. I have to find current location of user i.e. City name
I use the below code, it could generate latitude & longitude but did not get name of the city.
My code is:
public class GetCurrentLocation extends Activity implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,
locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----------Method to Check GPS is enable or disable ------------- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
How can I get name of the city i.e Current location of user ( like delhi, mumbai etc) ?
Try this way:
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
strReturnedAddress.append(returnedAddress.getLocality()).append("\n");
strReturnedAddress.append(areturnedAddress.getPostalCode()).append("\n");
strReturnedAddress.append(returnedAddress.getCountryName()).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
For more information go to: http://developer.android.com/reference/android/location/Geocoder.html
try this-
Geocoder geocoder = new Geocoder(getActivity(),Locale.ENGLISH);
StringBuilder stringBuilder = new StringBuilder();
List<Address> addressList;
try {
addressList = geocoder.getFromLocation(Latitude, Longitude, 1);
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't forget to give permissions in manifest-
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
I would recommend to use google play services to vet the location http://developer.android.com/google/play-services/location.html
If your app can be installed in devices with no google play services check out this code https://github.com/BeyondAR/beyondar/tree/master/android/BeyondAR_Framework/src/com/beyondar/android/util/location and start with the location manager