So I'm trying to get the actual coordinates of the smartphone and then submit it. For this purpose I am working with a (non-optimal) email solution. I want to get the coordinates and then submitting them by email.
If I press the button, it should get the coordinates and then putting them into mail.
Somehow I only get 0.0 into the email client, which should be the default values.
Anyway, here is my relevant code:
I initialise lat and lon with double in the public class.
public LatLng getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
finden
try {
lat = location.getLatitude();
lon = location.getLongitude();
//überschreiben der Variabeln lon & lat funktioniert
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
And this is my button.
final Button button = (Button) findViewById(R.id.addbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getLocation();
Intent i = new Intent(Intent.ACTION_SENDTO);
//i.setType("message/rfc822");
i.setData(Uri.parse("mailto:"));
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"adress#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "Subject - New Location was added");
i.putExtra(Intent.EXTRA_TEXT , "Latitude: " + lat + " Longitude: " + lon " );
try {
startActivity(i);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MapsActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
So what is my fault? The app is running, but it wont get the coordinates.
Have you provided the ACESS_FINE_LOCATION in the manifest file? You need this permission to access location.
You need to add this in the manifest file.
Edit:
Look, these days fused location provider is being used and there do come some instances where you don't get the permission and location doesn't come up. Read this file which is a basic example for retrieving location -
https://github.com/googlesamples/android-play-location/blob/master/BasicLocationSample/app/src/main/java/com/google/android/gms/location/sample/basiclocationsample/MainActivity.java
Also, this is the guide for it -
https://developer.android.com/training/location/retrieve-current.html
Related
This is my code to register network provider
netlocationListener = new MynetLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,interval,mttravel,
netlocationListener);
/*----------Listener class to get coordinates ------------- */
private class MynetLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
Toast.makeText(getBaseContext(), "accuracy & network provider"+loc.getAccuracy(),Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), "location changed", Toast.LENGTH_LONG).show();
CharSequence time1=android.text.format.DateFormat.format("MM-dd-yyyy hh:mm:ss", new java.util.Date());
.LENGTH_LONG).show();
String date =time1.toString();
float tsp= 0;
Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = Double.toString(loc.getLongitude());
Log.v(TAG, longitude);
String latitude =Double.toString( 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 = null;
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 accuracy=Float.toString( loc.getAccuracy());
String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName + "accuracy"
+ accuracy + "speed"+loc.getSpeed();
}
It shows true -
Toast.makeText(getBaseContext(), Boolean.toString(locationMangaer.isProviderEnabled(LocationManager.NETWORK_PROVIDER)), Toast.LENGTH_LONG).show();
If I change provider to GPS then it works perfectly but I need to get location from network provider. I checked working with internet, wifi but still no result.
Its not even entering the onlocationchanged().
For network based location, they are a lot less inaccurate than GPS, meaning you need to move the device a much larger distance to allow the signal to hook on to another network tower before
onLocationChanged() is called. Also not all network towers provide location.
I don't see where you're initializing the location manager. I'd guess you're not getting messages using network location because you're not moving enough to trigger an location change. Network position is not very accurate. I've seen network positioning be over 100ft off, and would hazard a guess that your device has a hundred foot "error radius" that you will have to move outside of to get a location update.
I've cut-n-pasted my code below, you're mileage may vary.
// see if this line gives you what you want
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// get location via network
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
// get location via GPS
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
My app just need to know user's country, and my app doesn't care where user moves.
All I want to know is :
When user start app, app will send user's approximately location(latitude and longitude) to server.
Here is my code with error. I try to send a string to getlocation function, and I hope it can return original string with adding latitude and longitude information.
private String getlocation (String url){
LocationManager status = (LocationManager) (this.getSystemService(Context.LOCATION_SERVICE));
if (status.isProviderEnabled(LocationManager.GPS_PROVIDER) || status.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v("print","enable to locate");
} else {
Log.v("print","fail to locate");
}
Location location = status.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
Log.v("print","succed!!!##");
Double longitude = location.getLongitude();
String loc=Double.toString(longitude);
url=url+loc;
}
else{
Log.v("print","location return null");
}
return url;
}
I use network_provider, and it always print "enable to locate", then print "location return null"
So what's wrong with my code that my location always return null.
I use AVD manerger, and I also try GPS_PROVIDER. I use Emulator control to send Decimal on location control. It doesn't work ,too.
By the way, I set network and GPS permission,too.
So much thanks for help!
I am getting location by below code but enable " use wireless networks " in settings i.e ( through settings - Location services - use wireless networks)
public void getCurrentLocation() {
LocationManager locationManager;
String bestProvider;
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Log.e(TAG, "Latitude: "+location.getLatitude()+" , Longitude: "+location.getLongitude());
}
I'm trying to build a string with origin and destination gps coordinates for google mapping purposes. The first thing that I need to do is to get the gps coordinates of my current location, since this is the origin point. Then, I need to concatenate these coordinates into a larger string that I use to get directions.
I have code that gets these coordinates, and also code that concatenates them into the correct string format. However, my problem is that my string building code is running first, which is leaving me with null pointer issues since the string is referencing gps coordinates that haven't processed yet.
Here it is. The gotLocation() method comes from implementing advice in this post:
Public class DirectionsActivity extends Activity {
String myLat, myLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parser parser;
LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(final Location location){
try {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
myLat = Double.toString(lat);
myLng = Double.toString(lng);
String gps_location = myLat + " " + myLng;
Toast.makeText(getBaseContext(), "First Message", Toast.LENGTH_SHORT).show();
}
}catch (Exception e) {
}
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
Toast.makeText(getBaseContext(), "Second Message", Toast.LENGTH_LONG).show();
buildString();
setContentView(R.layout.activity_directions);
}
The toast output when I run this is "Second Message" followed by "First Message". They should display in the opposite order.
Getting a location is an asynchronous operation, you don't have control on the time at which you get the answer from the system.
How would you be sure to find a satellite or cell phone mat before your toast appears ? :)
I'm trying to give a direction to the user using google map from one location to another.
I'm using the code bellow but I have no idea why it's not working. I can't figure out the problem everything seems right.
final double latitude = 37.894404;
final double longitude = -122.0660386;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
if(lastKnownLocation != null){
double lat = lastKnownLocation.getLatitude();
double longi = lastKnownLocation.getLongitude();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+lat+","+longi+"&daddr="+latitude+","+longitude));
startActivity(intent);
}else{
Toast.makeText(contactus.this,"Coudn't get provider", Toast.LENGTH_SHORT).show();
}
}
First off you need to wrap your call to LocationManager with a try/catch block and grab whatever exception you're getting off the call. Have a look below. This will make the call and catch the exception.. Go from there once you know why it's coming back NULL. You will always have trouble getting location geopoints using the emulator for whatever reason. Also, Google does not always return with geopoints so in the emulator I have looped until it has come back.. Not a good idea
try{
Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
}
catch(IOException e) {
Log.e("IOException", e.getMessage());
//Toaster on high-----------------//
Context context = getApplicationContext();
CharSequence text = "IOException: " + e.getMessage();
int dur = Toast.LENGTH_LONG;
Toast.makeText(context, text, dur).show();
I actually got it working and here is the code I used,
final double latitude = 45.894404;
final double longitude = -112.0660386;
LocationManager lManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
String towers = lManager.getBestProvider(crit, false);
Location userCurrentLocation = lManager.getLastKnownLocation(towers);
if(userCurrentLocation != null){
double lat = userCurrentLocation.getLatitude();
double longi = userCurrentLocation.getLongitude();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+lat+","+longi+"&daddr="+latitude+","+longitude));
startActivity(intent);
}else{
Toast.makeText(contactus.this, "Couldn't locate a provider to find your location", Toast.LENGTH_LONG).show();
}
Don't forget to add the premission to find the user location to you manifest, include it above ,
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Following is the code which i am using to find the latitude longitude and location of a place in my app, but it always show no location found
I have added the permissions in manifest file
{
LocationManager locManager;
setContentView(R.layout.main);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
String param = (String)locManager.getProviders(true).get(0);
Location loc = locManager.getLastKnownLocation(param);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
private void updateWithNewLocation(Location location)
{
TextView myLocationText = (TextView)findViewById(R.id.widget52);
String latLongString = " ";
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
}
else
{
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString);
}
private final LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider)
{
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
}
pls help me...
I've put your code in an Android project and ran it on the emulator and it seems to be working fine.
I would change the code to first check for a lastknown location, and after that check for location updates.
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
If that location is null, or too stale (timestamp) for your needs, you can start requesting location updates. (currently, you're first requesting location updates from the GPS, and then decide to retrieve its lastknownlocation). This might cause the location manager to stop querying the GPS.
Also you need to ensure the following is in place :
For GPS Provider, make sure the following permission is put in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Ensure the GPS is turned on that you have sufficient GPS coverage.
Do this by checking for the GPS icon in your Notification bar
Test on a real device
Although testing GPS location listeners works partly through the emulator, the behavior of an actual device will always be different.
Debug on the emulator
Basic GPS testing can be done using the emulator. Put a breakpoint in your locationlistener, and use the DDMS perspective to send some GPS coordinates to your AVD image.
#Siva, your problem is with the UI thread, as your updates are from different thread.
To verify if this is the UI problem, put a toast or Log cat the message when you receive an update.
Once you know that UI problem, then try using Handler to postInvalidate() the UI.