I want to get the location of the user using network. This is my code
package com.example.locationtest;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
public class WhereAmI extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
// String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 1000, 0,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
String timeStamp = (String) DateFormat.format("hh:mm:ss",
new java.util.Date());
String locationString = location.getLatitude() + ", "
+ location.getLongitude();
Log.i("Main", "Time = " + timeStamp + " Location = " + locationString);
}
}
This code works with my nexus 4, but if I use it with my Galaxy Gio the location is off by 30 Miles..
network location is based on the nearest Cell tower which the phone is connected to. It could be possible that your Nexus4 is connected to one Cell tower and the Galaxy Gio connected to another cell tower that could be like a bit far from where the Device is. To get an accurate fix, use GPS_PROVIDER. I had this issue before when using a NETWORK_PROVIDER. Got rid of it when I started using the GPS_PROVIDER which gave me accurate fixes
Related
I am an android beginner and I need your help! I am building a very simple running app and would like to have gather information about the speed. For this I am trying to create a very simple GPS class in order to use the getspeed() method.
I have created a little test app to ensure that my code is sound. In this app I am using getLatitude() and getLongitude() too but these will not be useful for my final code - I only need the speed really.
So far, I have managed to successfully test the class on the emulator but not on the phone. I can see the coordinates being populated on the screen when using the DDMS coordinates (getspeed() remained 0 but I know I cant test that on the emulator). When I try the code on my phone I have no response at all - despite waiting for the GPS to "warm up" (I also see that he GPS works when I move to GoogleMaps).
The whole things is driving me crazy, I am not sure what is happening with the onLocationChanged() method so appreciate any help you can give me.
Thanks!
The code is as per below:
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView speedText1, speedText2, speedText3;
double speed = 0;
double latitude = 0;
double longitude = 0;
String speed1;
String latitude1;
String longitude1;
boolean gps_enabled;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Toast.makeText(getBaseContext(), "location not null" , Toast.LENGTH_SHORT).show();
speedText1 = (TextView) findViewById(R.id.textView1);
speedText2 = (TextView) findViewById(R.id.textView2);
speedText3 = (TextView) findViewById(R.id.textView3);
speed = location.getSpeed();
speed1 = Double.toString(speed);
speedText1.setText(speed1);
latitude = location.getLatitude();
latitude1 = Double.toString(latitude);
speedText2.setText(latitude1);
longitude = location.getLongitude();
longitude1 = Double.toString(longitude);
speedText3.setText(longitude1);
Toast.makeText(getBaseContext(), latitude1 + longitude1 + speed , Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
} };
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
You are defining the LocationListener inside the onCreate() method, so you will not get location updates once that method finishes. You should try something like this:
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
TextView speedText1, speedText2, speedText3;
double speed = 0;
double latitude = 0;
double longitude = 0;
String speed1;
String latitude1;
String longitude1;
boolean gps_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0.0f, this);
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Toast.makeText(this, "location not null" , Toast.LENGTH_SHORT).show();
speedText1 = (TextView) findViewById(R.id.textView1);
speedText2 = (TextView) findViewById(R.id.textView2);
speedText3 = (TextView) findViewById(R.id.textView3);
}
#Override
public void onLocationChanged(Location location) {
speed = location.getSpeed();
speed1 = Double.toString(speed);
speedText1.setText(speed1);
latitude = location.getLatitude();
latitude1 = Double.toString(latitude);
speedText2.setText(latitude1);
longitude = location.getLongitude();
longitude1 = Double.toString(longitude);
speedText3.setText(longitude1);
Toast.makeText(this, latitude1 + longitude1 + speed, Toast.LENGTH_SHORT).show();
}
}
}
Hi I want to get location from cell tower(Sim card) without internet. I had used below mentioned code it's give me only last location when network available.
my requirement is to get location without WiFi or internet. can it's possible?
package com.example.gpscelltower;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CellTowerActivity1 extends Activity {
private static final String TAG = "Cell";
private static LocationManager locationManager;
private static LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cell_tower);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
String providerName=LocationManager.NETWORK_PROVIDER;
Location location=locationManager.getLastKnownLocation(providerName);
updateWithLocation(location);
//Cell-ID and WiFi location updates.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.d("TAG", "locationListner");
updateWithLocation(location);
String Text = "My current location is: " + "Latitude = "+ location.getLatitude() + "Longitude = " + location.getLongitude();
Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_LONG).show();
Log.d("TAG", "Starting..");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("TAG", "onSatatus");
}
public void onProviderEnabled(String provider) {
Log.d("TAG", "onProviderEnable");
}
public void onProviderDisabled(String provider) {
Log.d("TAG", "onProviderDisble");
}
};
}
private void updateWithLocation(Location location) {
Log.d("TAG", "UpdateWithLocation");
String displayString;
if(location!=null){
Double lat=location.getLatitude();
Double lng=location.getLongitude();
Long calTime=location.getTime();
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(calTime);
String time=formatter.format(calendar.getTime()).toString();
displayString="The Lat: "+lat.toString()+" \nAnd Long: "+lng.toString()+"\nThe time of Calculation: "+time;
}else{
displayString="No details Found";
}
Toast.makeText(CellTowerActivity1.this, ""+displayString, Toast.LENGTH_LONG).show();
}
}
Cell geolocation works through sending Cell towers IDs to server which maps it to coordinates. So, unfortunately it's not posssible to get your coordinates w/o data connection with standard APIs.
I am new to Andriod development..i try to get postal code and city name from reverse geocoding using below code.it finding latitude, longitude value fine but cant able to get cityname and postal code.
package com.example.code;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Geocoder gcoder=new Geocoder(this, Locale.ENGLISH);
List<Address> Data = null;
double latitude;
double longitude;
if (location != null) {
latitude=location.getLatitude();
longitude=location.getLongitude();
try {
Data=gcoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String cityname=Data.get(0).getLocality();
String postalcode=Data.get(0).getPostalCode();
String message=String.format("City Name \n PostalCode \n", Data.get(0).getLocality(),Data.get(0).getPostalCode());
Toast.makeText(LbsGeocodingActivity.this,message ,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show(); }
}
}
It looks like your code for finding the city and zipcode is right, but your code for formatting the string for your toast is wrong. It does not put the values in there.
It should look like this:
String message=String.format("City Name %s \n PostalCode %d \n", Data.get(0).getLocality(),Data.get(0).getPostalCode());
The %s represents a string and the %s represents a decimal number (integer).
I have a problem,
The locationmanager is working perfectly fine when i test it in the emulator and edit the location in the DDMS screen, but when i test it on the Samsung Galaxy SII, its nog working..
Please help me.
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
public String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format("Current Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ", location.getLongitude(), location.getLatitude(), getMyPhoneNumber());
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ",
location.getLongitude(), location.getLatitude(), getMyPhoneNumber()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
In the permissions i have:
ACCES_COURSE_LOCATION
ACCES_FINE_LOCATION
Maybe you are testing indoors, and can't get any GPS information.
Try to change LocationManager.GPS_PROVIDER-->LocationManager.NETWORK_PROVIDER.
It could be a problem with your incorrect usage of String.format(). Sometimes this can cause weird, device-specific issues. Try,
String lon = "" + location.getLongitude();
String lat = "" + location.getLatitude();
String num = getMyPhoneNumber();
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s",
lon,
lat,
num
);
Have you tried using this?
LocationManager lm = (LocationManager)act.getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, true);
Location loc = lm.getLastKnownLocation(provider);
i had similar issues using the locationmanager on my HTC incredible S running 4.0.4.
it would simply stop firing location changes on the real device after some time.
on some other devices it would work.
very intermittent.
my solution was to piss off the LocationManager and use LocationClient pardiagm.
http://developer.android.com/reference/com/google/android/gms/location/LocationClient.html
ever since google play services have been introduced the Locationmanager has been intermittent on my device. I cant give any other explanation as to why it occurs.
But the LocationClient works everytime plus it removes the dumb 'provider' notion from location management.
I want to get latitude and Longitude from the following Android code.
location = locationManager.getLastKnownLocation(provider);
Here i am getting error location is null.
Here is the code:
package com.p;
import android.app.Activity;
import android.os.Bundle;
import android.os.Bundle;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class GooglemapActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I have added the following permisions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
But I am getting the following error:
Provider not available
If the last known location is null, it's because the phone has no last known location. If there is no location cached, you need to request an updated location, either via network, or GPS. Note that this process can take time, so must be done asynchronously.
You need to read this document:
http://developer.android.com/guide/topics/location/obtaining-user-location.html
I also recommend reading this:
http://android-developers.blogspot.co.uk/2011/06/deep-dive-into-location.html
You haven't define a valid Criteria. Define that as follows
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);//true if required
criteria.setBearingRequired(false);//true if required
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);//search for enabled provider
have you switched on GPS in Settings -> Location ?
why do you use (int) (location.getLatitude()) -- latitude/longitude is a float
Think you need to specify from which provider you want to receive updates.
You have two options:
GPS_PROVIDER
NETWORK_PROVIDER
You're probably missing something like this:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
I think you may want to add the following permission as well, since I am pretty sure that the FINE relies on the COARSE...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>