I am a begginer in Android programming and I encountered a problem with displaying the current location of my phone using the NETWORK PROVIDER, with which I need some help.
Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.txtLat);
txtLon = (TextView) findViewById(R.id.txtLon);
Log.d("ADebugTag", "WTF");
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
txtLat.setText(String.valueOf(location.getLatitude()));
txtLon.setText(String.valueOf(location.getLongitude()));
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Log.d("ADebugTag", "WTF END");
}
I try to set the latitude and longitude of the location into the TextViews, but my app crashes when i try tu run it.
Also, I tried to print a full stack trace, but I couldn't find a method to make it work..
UPDATE: Thanks for all the replies :D - After posting this I realized I should have also posted the layout of the main activity, just in case.
<TextView
android:id = "#+id/txtLat"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="LATITUDINE" />
<TextView
android:id = "#+id/txtLon"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/txtLat"
android:text="LONGITUDINE" />
Also, I have tried to print something in logcat when the onLocationChanged method gets called, but the message is not displayed when I run the app, meaning that the method is not called.
I am running this app on an older device, using Android 2.3.6, maybe that is useful information as well.
It's highly possible that you are lacking the corresponding app rights. Make sure you added following lines to your manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I am not sure about the first 2, but for sure you must have the coarse and fine location permissions.
Here's an example that I reuse in m apps, using a custom class to wrap the LocationListener:
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class MyLocationListener implements LocationListener {
// GLOBALS
float currentLatitude = 0;
float currentLongitude = 0;
float currentAltitude = 0;
float currentAccuracy = 0;
float currentSpeed = 0;
float currentBearing = 0;
String currentProvider = "";
public MyLocationListener(Context context) {
super();
}
// Define all LocationListener methods
public void onLocationChanged(Location location) {
currentLatitude = (float)location.getLatitude();
currentLongitude = (float)location.getLongitude();
currentAltitude = (float)location.getAltitude();
currentAccuracy = (float)location.getAccuracy();
currentSpeed = (float)location.getSpeed();
currentBearing = (float)location.getBearing();
currentProvider = location.getProvider();
}
public void onProviderDisabled (String provider) {
//currentProvider = "";
Log.v(TAG, "Provider is " + provider);
}
public void onProviderEnabled (String provider) {
//currentProvider = provider;
Log.v(TAG, "Provider is " + provider);
}
public void onStatusChanged (String provider, int status, Bundle extras) {
Log.v(TAG, "Status is " + status);
}
// Custom Methods
public String getCurrentLatitude() {
String lat = Float.toString(currentLatitude);
return lat;
}
public String getCurrentLongitude() {
String lon = Float.toString(currentLongitude);
return lon;
}
public String getCurrentAltitude() {
String alt = Float.toString(currentAltitude);
return alt;
}
public String getCurrentAccuracy() {
String acc = Float.toString(currentAccuracy);
return acc;
}
public String getCurrentSpeed() {
String spd = Float.toString(currentSpeed);
return spd;
}
}
... and then in onCreate
// GPS
locationListener = new MyLocationListener(this); // instance of above class
// Runnable
handler = new Handler();
runnable = new Runnable() {
public void run() {
handler.postDelayed(this, REFRESH_RATE);
// Get Data
float lat = Float.parseFloat(locationListener.getCurrentLatitude());
float lon = Float.parseFloat(locationListener.getCurrentLongitude());
// Update Text
ActualLatitude.setText(locationListener.getCurrentLatitude());
ActualLongitude.setText(locationListener.getCurrentLongitude());
}
};
handler.postDelayed(runnable, REFRESH_RATE);
.. and then in onResume
#Override
protected void onResume() {
super.onResume();
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, REFRESH_RATE, 5, locationListener);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
.. and then in onDestroy
#Override
public void onDestroy() {
super.onDestroy();
// Kill Runnable
handler.removeCallbacks(runnable);
// Stop GPS
locationManager.removeUpdates(locationListener);
locationManager = null;
}
Some other notes:
make sure you have requested the COARSE_LOCATION and/or FINE_LOCATION in your AndroidManifest
double check the id's of your textviews - you said it was crashing and without seeing a stacktrace, for all we know the location stuff is fine but its crashing on a NPE!
Here is my current working code for getting user location in android:
public class MyApp extends Application{
private LocationManager locationManager;
private LocationListener listener;
#Override public void onCreate(){
super.onCreate();
}
public void acquireUserCoordinates(){
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
listener = new GpsListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
}else {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
listener = new GpsListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
}
}
private class GpsListener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
double mLatitude = location.getLatitude();
double mLongitude = location.getLongitude();
EventBus.getDefault().post(new UserLocationAcquiredEvent(true, mLatitude, mLongitude));
try {
if (listener != null)
locationManager.removeUpdates(listener);
} catch (Exception e) {
}
locationManager = null;
} else {
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
}
Now, you notice that I use EventBus library here to post results to the respective activity/fragment.
In your activity or fragment, you get the application instance (getApplication()) and call the acquireUserCoordinates() method then you can override onEvent(EventClassHere event) and then easily update the UI respectively (like dismiss dialog).
You can find EventBus here: EventBus
I hope this helps you.
Good luck and happy coding!
Related
I am new to Android and try to have one example to get GPS location.
I surf through the web and have following code.
The program will crash once I click the button to get a GPS.
I found it seems something wrong when I call locationManager.requestLocationUpdates(commandStr, 1000, 0, locationListener);
I trace it into requestLocationUpdates and found it crashed at Looper class
public final class Looper {
Looper(boolean quitAllowed) {
throw new RuntimeException("Stub!");
}
public static void prepare() {
throw new RuntimeException("Stub!");
}
public static void prepareMainLooper() {
throw new RuntimeException("Stub!");
}
public static Looper getMainLooper() {
throw new RuntimeException("Stub!");
}
public static void loop() {
throw new RuntimeException("Stub!");
}
Following are the complete code, ,dose anyone know which part of program is wrong
public class MainActivity extends AppCompatActivity {
private TextView tvLocation;
private Button btGetLocation;
private LocationManager locationManager;
private String commandStr;
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
public LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
tvLocation.setText("經度" + location.getLongitude() + "\n緯度" + location.getLatitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commandStr = LocationManager.GPS_PROVIDER;
// LocationManager.GPS_PROVIDER //使用GPS定位
// LocationManager.NETWORK_PROVIDER //使用網路定位
tvLocation = (TextView) findViewById(R.id.textView);
btGetLocation = (Button) findViewById(R.id.button);
btGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// LocationManager可以用來獲取當前的位置,追蹤設備的移動路線
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.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.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_ACCESS_COARSE_LOCATION);
return;
}
locationManager.requestLocationUpdates(commandStr, 1000, 0, locationListener);
// 事件的條件設定為時間間隔1秒,距離改變0米,設定監聽位置變化
Location location = locationManager.getLastKnownLocation(commandStr);
if (location != null)
tvLocation.setText("經度"+location.getLongitude()+"\n緯度"+location.getLatitude());
else
tvLocation.setText("定位中");
// location.getLongitude() //取得經度
// location.getLatitude() //取得緯度
// location.getAltitude() //取得海拔高度
}
});
}
}
Here some code example:
public class Activity extends AppCompatActivity{
//variables for GPS data
private LocationManager locationManager;
private Location location;
private int minTime = 1000 //=1s
private int minDistance = 5 //=5m
private List<String> providers;
private final ActivityLocationListener locationListener = new ActivityLocationListener();
#Override
protected void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout_file);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
providers = locationManager.getProviders(true);
//this will print you the available providers in your LogCat
//in some virtual devices network is not available
Log.d(NoteMapActivity.this.getClass().getSimpleName(), "available providers:\n" + providers);
}
public void onButtClick(View view){
this.requestLocationUpdates();
}
public void requestLocationUpdates(){
locationManager = (LocationManager) getSystemService(LOCATON_SERVICE);
//with this following code you will call onLocationChanged()
if (providers.contains("gps")){
//"permisson check"
try {
locationManager.requestLocationUpdates("gps", minTime, minDistance, locationListener);
} catch (SecurityException ex){
Log.e(getClass().getSimpleName(), "no permisson: " + ex.toString());
}
//if gps is not available you can use "network" or "passive" instead, maybe with if-else conditions
}
//create a class inside of this one!
class ActivityLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
currentLocation = location;
Log.d(NoteMapActivity.this.getClass().getSimpleName(), "received location:\n" + currentLocation.getLatitude() + ", " + currentLocation.getLongitude());
addCurrentLocationMarkerToMap();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
}
I have a class "OldLocationService" (generally I'm using fused location from GoogleApiClient but I keep that class in case of old Google Play):
public class OldLocationService {
static Location loc;
private static final String TAG = MainActivity.class.getSimpleName();
protected LocationManager service;
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
Log.d(TAG, "New location: " + location.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public void EnableGPS(String provider, Context ctx) {
service = (LocationManager) ctx.getSystemService(ctx.LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(provider);
if (enabled) {
service.requestLocationUpdates(provider, 10000, 0, mLocationListener, Looper.getMainLooper());
}
else
{
Log.d(TAG, "GPS is not enabled");
}
}
public void DisableGPS() {
try {
if (!(service==null)) {
service.removeUpdates(mLocationListener);
} else {
Log.d(TAG, "service is null");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
Somewhere in another class I'm calling:
OldLocationService OLS = new OldLocationService();
OLS.EnableGPS(LocationManager.NETWORK_PROVIDER, mContext);
And I'm getting locations correctly. However, when I'm trying to disable GPS:
OldLocationService ols = new OldLocationService();
ols.DisableGPS();
Then in logcat I get:
service is null
Why I can't remove GPS updates? How to do that?
Sorry for my English errors,
Defozo
First of all don't make 2 instances of your OldLocationService class.. you must remove updates from the same instance from which you started them.. because each instance has its own copy of variables/fields, in your case protected LocationManager service;
OldLocationService ols = new OldLocationService(); // declare it globally
// in middle of some code
OLS.EnableGPS(LocationManager.NETWORK_PROVIDER, mContext);
// more code here
If you're removing Location updates from a Service then you must put the code in it's onDestroy() method from the same instance:
public void onDestroy(){
ols.DisableGPS();
super.onDestroy();
}
I am not getting GPS location in my code, while Google maps is showing current location and even its updating, I am starting a service, inside service registering locationListener to the locationManager, handling onLocationChanged callback method, doing entry in the AndroidManifest.xml even. The logs onCreate methods is showing.
below is my code, could you guys please let me know where i am doing wrong...
public class LocationService extends Service implements LocationListener {
private static final long MIN_TIME_INTERVAL_FOR_GPS_LOCATION = 100;
private static final float MIN_DISTANCE_INTERVAL_FOR_GPS_LOCATION = 1.0f;
private static String TAG = LocationService.class.getSimpleName();
private LocationManager locationManager;
private static Location mCurrentLocation;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate...");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_INTERVAL_FOR_GPS_LOCATION, MIN_DISTANCE_INTERVAL_FOR_GPS_LOCATION, this);
mCurrentLocation = getBestLocation();
}
private Location getBestLocation() {
Log.i(TAG, "getBestLocation...");
Location location_gps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location_network = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// If both are available, get the most recent
if (location_gps != null && location_network != null) {
return (location_gps.getTime() > location_network.getTime()) ? location_gps : location_network;
} else if (location_gps == null && location_network == null) {
return null;
} else {
return (location_gps == null) ? location_network : location_gps;
}
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged...");
Toast.makeText(LocationService.this, "Location Found", Toast.LENGTH_SHORT).show();
mCurrentLocation = location;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public static Location getmCurrentLocation() {
return mCurrentLocation;
}
public static void setmCurrentLocation(Location mCurrentLocation) {
LocationService.mCurrentLocation = mCurrentLocation;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy...");
locationManager.removeUpdates(this);
}
}
Your locationManager called requestLocationUpdates using GPS provider only.
I think your device could not catch GPS satellite signal, in-door sate.
So, you should call requestLocationUpdates using Network provider too.
Next two links are may helpful to you.
http://developer.android.com/guide/topics/location/strategies.html
http://developer.android.com/training/location/receive-location-updates.html
I am developing a small android application in which I want to find out the user's current location by using the network provider. I tried this in following ways but it's not giving me any output :
networklocationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("********************************",
"this is my network location " + location);
String Location_text = "NETWORK LOCATION latitude:"
+ location.getLatitude() + " longitude:"
+ location.getLatitude();
network_location.setText(Location_text);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location
// updates
networklocationManager
.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
networklocationListener);
I gave permissions in my manifest file like this
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
Is there any thing which I am missing ? Is this the correct way? Need help. Thank you...
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager gpslocationManager;
private LocationManager networklocationManager;
private LocationManager networklocationManager1;
private String provider;
private TextView gps_location;
private TextView network_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gps_location = (TextView) findViewById(R.id.gps_location);
network_location = (TextView) findViewById(R.id.network_location);
networkLocation();
}
public void networkLocation() {
networklocationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("********************************",
"this is my network location " + location);
String Location_text = "NETWORK LOCATION latitude:"
+ location.getLatitude() + " longitude:"
+ location.getLatitude();
network_location.setText(Location_text);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
networklocationManager
.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
networklocationListener);
}
}
Make sure you enable Location Services in Settings! That should be the problem. It might be disabled (and this setting will usually be found in Location and Security in Settings)
Let me know if it works!
Is your network provider enabled?
boolean network_enabled;
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
ex.printStackTrace();
}
I hope this part of the code will help you extracted from vogella.
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
#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.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location 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);
}
#Override
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));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I want to display latitude and longitude my current location..
For this rather than searching in Google, i searched in SO.
I just want to display my current location latitude and longitude.
See my code below :
public class LocationGetter extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
LocationManager mlocManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new LocationManagerHelper();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100,mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
+ '\n');
tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
+ '\n');
Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));
} else {
tv.setText("GPS is not turned on...");
}
/** set the content view to the TextView */
setContentView(tv);
}
/* Class My Location Listener */
public static class LocationManagerHelper implements LocationListener {
private static double latitude;
private static double longitude;
#Override
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
}
#Override
public void onProviderDisabled(String provider) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public static double getLatitude() {
return latitude;
}
public static double getLongitude() {
return longitude;
}
}
}
I have also added permission in manifest file :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
See the output i am getting :
Where i am going wrong ? I dont understand, its a simple code and why its not working ?
I just verified your code and it works with these changes, you just need to move the tv.append() calls to the onLocationChanged() method as that is called each time, if you don't use that for the CallBack, then u will get the first set values only and it's only executed once.
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
+ '\n');
tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
+ '\n');
Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));
}
and I have used these permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
You can look at these and filter out the ones you won't be interested in. I have used a downloaded .gpx file from here
I've tested it on Android 2.2 though,
You got location in Onlocationchanged
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
}
so the lattitude and longitude will be displayed only when the change from the current location.for checking you give some latitude and longitude and send from your emulator control in DDMS and after that you run your program.Sure it will show the location.
If you run this program in device then it show latitude and longitude 0.0 until we change our position.You must move at least 10 meter from your current position to see the output. Because without change current position onLocationChange() method does not fire and output will be 0.0
Use the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
I think with the emulator you can't get the GPS co-ordinates. If you are working with the mobile, try the GPS outside of your building. sometimes you won't get the GPS co-ordinates inside the building. If that time also you failed, then i will post the code that we got succeeded.
The below code just now i have tested and its works for 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.widget.Toast;
public class GetGPS extends Activity {
String GPSPROVIDER = LocationManager.GPS_PROVIDER;
private static final long MIN_GEOGRAPHIC_POOLING_TIME_PERIOD = 10000;
private static final float MIN_GEOGRAPHIC_POOLING_DISTANCE = (float)5.0;
public LocationManager gpsLocationManager;
static Context context = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
/*Get a listener for GPS*/
LocationListener gpsLocationListener = null;
gpsLocationListener = new GpsLocationListener(this);
/*Start Location Service for GPS*/
gpsLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
/*Register GPS listener with Location Manager*/
gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_GEOGRAPHIC_POOLING_TIME_PERIOD,
MIN_GEOGRAPHIC_POOLING_DISTANCE, gpsLocationListener);
boolean isavailable = gpsLocationManager.isProviderEnabled(GPSPROVIDER);
if(isavailable) {
Location loc = gpsLocationManager.getLastKnownLocation("gps");
if(loc != null) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(GetGPS.this,"Longitude is "+longitude + " Latitude is "+latitude, Toast.LENGTH_LONG).show();
}
}
}
public static class GpsLocationListener implements LocationListener {
public GpsLocationListener(Context context){
}
public void onLocationChanged(Location loc) {
if (loc != null) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(context,"Longitude is "+longitude + " Latitude is "+latitude, Toast.LENGTH_LONG).show();
}
}//End of onLocationChanged Method
#Override
public void onProviderDisabled(String provider) {
}//End of onProviderDisabled Method
#Override
public void onProviderEnabled(String provider) {
}//End of onProviderEnabled Method
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}//End of onStatusChanged Method
}//End of GpsLocationListener class
}
I tested this by moving the device from one place to another...
I hope it will helps..