Get Current Location GMaps - android

i tried a lot of "get current location" for android. But i think most of them are outdated, or i simply dont get it.
I DONT want to set a marker.addmarker(params..) i would like to use the blue default dot for my position on Gmaps. Here i've found somthing about that, but for my bad it also aint work.
Customize marker of myLocation Google Maps v2 Android
So in first line i need, my current Location with a Listener when my Location is updating. Im trying this right now (Testing on a real device). But myLocation is always =null.
//get GMaps Fragment
mMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true); //activate Blue dot
myLocation = mMap.getMyLocation(); //Testing, but not working = null
//Trying with LocationManager
locManager =(LocationManager)getSystemService(this.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locManager.getBestProvider(criteria, true);
myLocation = locManager.getLastKnownLocation(provider);
if(myLocation != null){
double lat = myLocation.getLatitude();
double lon = myLocation.getLongitude();
}
locManager.requestLocationUpdates(provider, 1000, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
myLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});

Follow this http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ . Then just place the latitude and longitude you get(using gps.getLatitude(), gps.getLongitude()) in your google map and it will show your current location.

Try this code, it is worked in my application:
private LocationManager locationManager;
private String provider;
double lat,lon;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locate);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 1, this);
if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
gpsalert();
}
// Criteria to select location provider
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Toast.makeText(getApplicationContext(), "Provider is available", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Provider is not available", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String addr,city,country;
lat=location.getLatitude();
lon=location.getLongitude();
//Toast.makeText(getApplicationContext(), "lat"+lat+"long"+lon, Toast.LENGTH_LONG).show();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
addr = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getAddressLine(2);
t1.setText(addr+"\n"+city+"\n"+country);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show();
//t1.setText("");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Enabled provider " + provider, Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
//locationManager.requestLocationUpdates(provider, 400, 1, this);
}
// Remove LocationListener updates
#Override
protected void onPause() {
super.onPause();
//locationManager.removeUpdates(this);
}
public void gpsalert()
{
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}

Related

android - can't get gps coordinate

I want to get user coordinate, the gps is on , I've asked for permission it has the permissions.
the location is set , I've my locations on other apps like google map but in my application , it doesn't work :
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
LocationManager mlocManager = null;
LocationListener mlocListener;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
startService();
}
public class FetchCordinates extends AsyncTask<String, Integer, String> {
AlertDialog.Builder a;
AlertDialog dialog;
public double lati = 0.0;
public double longi = 0.0;
public LocationManager mLocationManager;
public FetchCordinates.VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new FetchCordinates.VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
a = new AlertDialog.Builder(Admins.this);
a.setMessage("در حال به دست آوردن موقعیت جغرافیایی...");
a.setPositiveButton(("بیخیال"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
FetchCordinates.this.cancel(true);
}
});
dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
Log.v("this","got the location");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0 && !isCancelled()) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
it shows me the dialog for getting the location but it never get the current location .
What's wrong with my code ?
Please provide what you wrote in your Manifest.xml file. Maybe there is something wrong with the permissions.
You need
android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION
for API 5.0 or higher also:
android.hardware.location.gps

Sometimes I am getting empty location until I restart my phone why?

So I am getting the longitude and latitude as:
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude=location.getLongitude();
latitude=location.getLatitude();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Or use LocationManager.GPS_PROVIDER
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation!=null){
longitude=lastKnownLocation.getLongitude();
latitude=lastKnownLocation.getLatitude();
}
then I am getting my location depending on these info:
Geocoder myLocation = new Geocoder(Time.this, Locale.getDefault());
List<Address> myList=null;
try {
myList = myLocation.getFromLocation(latitude,longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(myList != null && myList.size()>0) {
address= (Address) myList.get(0);
if(address.getAddressLine(0)!=null){
addressStr += address.getAddressLine(0);
}
if(address.getAddressLine(1)!=null){
addressStr += ", "+address.getAddressLine(1);
}
if(address.getAddressLine(2)!=null){
addressStr += ", " +address.getAddressLine(2);
}
}
But sometimes the location stays null until I restart my phone why that's happening? and is there a way to fix it?
Try to setup your Location Listener as below :
public class BasicMapActivity_new2 extends Activity implements
LocationListener {
private LocationManager locationManager;
private String provider;
Double Latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new2.this, "GPS signal not found",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else if (!enabledWiFi) {
Toast.makeText(BasicMapActivity_new2.this,
"Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
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);
if (location != null) {
onLocationChanged(location);
} else {
// do something
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
Location old_one;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
// Toast.makeText(BasicMapActivity_new.this, "Location " + lat+","+lng,
// Toast.LENGTH_LONG).show();
LatLng coordinate = new LatLng(lat, lng);
Latitude = lat;
longitude = lng;
Toast.makeText(BasicMapActivity_new2.this,
"Location " + coordinate.latitude + "," + coordinate.longitude,
Toast.LENGTH_LONG).show();
}
#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
}
}
And do not forget to add permission into manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Update: This is because to add requestLocationUpdates() into onResume() and removeUpdates(this); into onPause(). This way your app will stop updated locations when it is not active. add below into your Activity:
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
this is a documented issue in google forums. Check this thread:
https://code.google.com/p/android/issues/detail?id=57707
Also i think the solution for this is to use Google Location API, this requires that you have Google Play services up to date and >= 2.2 i think. Hope this helps you. I battled this issue for long

android google maps v2 get last know location and always start with network provider

This Google Maps v2 api confuses me quite a bit. I have implemented it now in some way i would like to use it. I just have two small problems that i don't know how to go about.
Sometimes I don't get a location when i start the app with gps enabled or it takes way too long to get one.
So I would like it to always load with the internet location provider first to have a very fast location fix as well as always using the getlastknownlocation() first. Cant figure out how to go about it.
Here my code:
public class MapViewMain extends FragmentActivity implements LocationListener, LocationSource
{
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
final int RQS_GooglePlayServices = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapviewmain);
//start power button service
Intent intent=new Intent("com.epicelements.spotnsave.START_SERVICE");
this.startService(intent);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
Toast.makeText(this, "Google Service not found", Toast.LENGTH_LONG).show();
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locationManager != null)
{
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gpsIsEnabled) {
// Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
PopIt("No GPS found", "Would you like to go to the settings to activate it?");
}
if(gpsIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
}
else if(networkIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000L, 10F, this);
}
else
{
//Show an error dialog that GPS is disabled...
}
}
else
{
//Show some generic error dialog because something must have gone wrong with location manager.
}
setUpMapIfNeeded();
}
}
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
locationManager.getBestProvider(criteria, true);
if(mListener != null){
}
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Enable the my-location layer
if(locationManager != null)
{
mMap.setMyLocationEnabled(true); // Enable the my-location layer
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null)
{
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
{
setUpMap();
}
//This is how you register the LocationSource
mMap.setLocationSource(this);
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setPadding(0,60,0,150);
Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE);
}
#Override
public void activate(OnLocationChangedListener listener)
{
mListener = listener;
}
#Override
public void deactivate()
{
mListener = null;
}
#Override
public void onLocationChanged(Location location)
{
if( mListener != null )
{
mListener.onLocationChanged( location );
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
//save coordinate
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putFloat("lat", (float) location.getLatitude());
editor.putFloat("lng", (float) location.getLongitude());
editor.putFloat("accuracy", (float) location.getAccuracy());
editor.commit();
//marker stuff
mMap.clear();
mMap.addMarker(new MarkerOptions()
.position(coordinate)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 16));
}
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
// Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
// Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
// Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
// Alarm Dialog if GPS not enabled
public void PopIt( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message )
.setCancelable(false)
.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do stuff onclick of YES
//AlertDialog.dismiss();
}
})
.setNegativeButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do stuff onclick of CANCEL
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
}
}
You can use LocationClient for your purpose its give LastLocation very fast.
first declare class variable
private LocationClient client;
after in onCreate
try {
if (map == null) {
MapsInitializer.initialize(this);
client = new LocationClient(this, new ConnectionCallbacks() {
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle connectionHint) {
// TODO Auto-generated method stub
Toast.makeText(MotoFreightHomeMapMainActivity.this,
"onConnected", Toast.LENGTH_LONG).show();
Location currentLocation = client.getLastLocation();
if (currentLocation != null) {
//do you stuff here
}
}
}, new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
});
client.connect();
}
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
etMap.setVisibility(View.INVISIBLE);
btnEditLocation.setVisibility(View.INVISIBLE);
Toast.makeText(this, "Please install Google Play Library",
Toast.LENGTH_SHORT).show();
}
see full code here
http://developer.android.com/training/location/retrieve-current.html
You can find a sample and tutorial from here.

set Timeout for GPS listening

I'm able to get location update from network provider but when it comes to gps it takes a lot of time for the data to be picked. I want to keep a particular time for which only the GPS listener will work and then move on to network provider after sometime. How to fix this issue ?
This is my code..
public void gpslocation()
{
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
updateLocationForGeo(location);
//update(location);
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
System.out.println(provider+ "enabled provider");
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println(provider+ "disabled provider");
networklocation();
}
};
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, 10 * 1000, (float) 10.0,locationListener);
}
public void networklocation()
{
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
updateLocationForGeo(location);
//update(location);
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
System.out.println(provider+ "enabled provider");
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println(provider+ "disabled provider");
isGpsProvidersDisabled=true;
}
};
String timeProvider = LocationManager.NETWORK_PROVIDER;
locationManager.requestLocationUpdates(timeProvider, 1 * 1000, (float) 10.0, locationListener);
}
public void updateLocationForGeo(Location location){
System.out.println("location updated");
double dev_lat = location.getLatitude();
double dev_lang = location.getLongitude();
boolean out_of_range=false;
for(int i=0; i<arrayLength; i++){
double lattDiff = Math.toRadians(latarr[i]-dev_lat);
double longDiff = Math.toRadians(lonarr[i]-dev_lang);
double distance=(Math.sin(lattDiff/2)*Math.sin(lattDiff/2))+(Math.sin(longDiff/2)*Math.sin(longDiff/2)*Math.cos( Math.toRadians(latarr[i]))*Math.cos( Math.toRadians(dev_lat)));
System.out.println(distance+" distance" );
double c= (2 * Math.atan2(Math.sqrt(distance), Math.sqrt(1-distance)));
double radius=radarr[i]* 1.60934;
double d = 6371 * c;
if(d>radius)
{
out_of_range=true;
continue;
}
else{
System.out.println("enjoy");
out_of_range=false;
break;
}
}
Any help would be greatly appreciated.
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);
public class MyLocationListener implements LocationListener {
private Address mAddresses;
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
Geocoder gcd = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
mAddresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e) {
}
String cityName = (mAddresses != null) ? mAddresses.get(0)
.getLocality() : TimeZone.getDefault().getID();
String countryName = (mAddresses != null) ? mAddresses.get(0)
.getCountryName() : Locale.getDefault().getDisplayCountry()
.toString();
mCurrentSpeed.setText("Longitude"+loc.getLongitude()+" Latitude"+loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

Testing GPS current location on Android mobile phone

When, I test this code on my android mobile phone the current location doesn't show up. Should I configure my mobile or increment new code into the code to allow it run on my mobile properly. A hint will be much appreciated. the code is as follows
public class GetLocation extends Activity {
TextView tv;
double latitude,longitude,accuracy;
private LocationManager lm;
private LocationListener lo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)this.findViewById(R.id.txtLocation);
lm=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
lo = new mylocationlistener();
tv.setText("waiting for location");
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
createGpsDisabledAlert();
}
}
//dialog to check if gps enabled or not
private void createGpsDisabledAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS is disabled! Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
showGpsOptions();
}
});
builder.setNegativeButton("Do nothing",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
}); //close negative builder
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions(){
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
private class mylocationlistener implements LocationListener {
public void onLocationChanged(Location location) {
if (location !=null){
longitude = location.getLongitude();
latitude = location.getLatitude();
accuracy = location.getAccuracy();
/*
Log.d("LOCATION CHANGED", latitude + "");
Log.d("LOCATION CHANGED", longitude + "");
*/ String str = "\n CurrentLocation: "+
"\n Latitude: "+ latitude +
"\n Longitude: " + longitude +
"\n Accuracy: " + accuracy;
Toast.makeText(GetLocation.this,str,Toast.LENGTH_LONG).show();
tv.append(str);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(GetLocation.this,"Error onProviderDisabled",Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(GetLocation.this,"onProviderEnabled",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(GetLocation.this,"onStatusChanged",Toast.LENGTH_LONG).show();
}
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void onResume(){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lo);
super.onResume();
}
}
In your onCreate you need to call lm.requestLocationUpdates() to get your location listener working . See Requesting Location Updates

Categories

Resources