Location Manager's requestLocationUpdates called only once - android

I am calling the method and expect location updates multiple times:
locationManager.requestLocationUpdates("gps",0 ,0, loc_listener);
My loc_listener is defined as:
LocationListener loc_listener = new LocationListener() {
private final String TAG = "xoxoxo.LocationListener";
public void onLocationChanged(Location l) {
Intent locationAlert = new Intent("xoxoxo.LOCATION_CHANGED")
.putExtra("target_location", l);
sendBroadcast(locationAlert);
// locationManager.requestLocationUpdates("gps", 0 ,0, this);
}
public void onProviderEnabled(String p) {
Log.i(TAG, "Provider enabled");
}
public void onProviderDisabled(String p) {
Log.i(TAG, "Provider disabled");
}
public void onStatusChanged(String p, int status, Bundle extras) {
Log.i(TAG, "Status changed");
}
};
Defined as is, I will only get an update once, both on HTC Evo 2.2 and 2.2 + Google API emulator.
The hack to get multiple updates is to uncomment the line which registers for updates on each update:
locationManager.requestLocationUpdates("gps", 0 ,0, this);
Have you guys seen anything like this?

I have never seen the issue. The following is my code to test LocationManager and LocationListener. It works as expected when LocationListener is implemented as an anonymous class.
package com.test.locationmanager;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;
public class LocationManagerStatus extends Activity {
private LocationManager locationManager;
private TextView textView;
private final LocationListener gpsLocationListener =new LocationListener(){
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
final String tvTxt = textView.getText().toString();
switch (status) {
case LocationProvider.AVAILABLE:
textView.setText(tvTxt + "GPS available again\n");
break;
case LocationProvider.OUT_OF_SERVICE:
textView.setText(tvTxt + "GPS out of service\n");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
textView.setText(tvTxt + "GPS temporarily unavailable\n");
break;
}
}
#Override
public void onProviderEnabled(String provider) {
textView.setText(textView.getText().toString()
+ "GPS Provider Enabled\n");
}
#Override
public void onProviderDisabled(String provider) {
textView.setText(textView.getText().toString()
+ "GPS Provider Disabled\n");
}
#Override
public void onLocationChanged(Location location) {
locationManager.removeUpdates(networkLocationListener);
textView.setText(textView.getText().toString()
+ "New GPS location: "
+ String.format("%9.6f", location.getLatitude()) + ", "
+ String.format("%9.6f", location.getLongitude()) + "\n");
}
};
private final LocationListener networkLocationListener =
new LocationListener(){
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
final String tvTxt = textView.getText().toString();
switch (status) {
case LocationProvider.AVAILABLE:
textView.setText(tvTxt + "Network location available again\n");
break;
case LocationProvider.OUT_OF_SERVICE:
textView.setText(tvTxt + "Network location out of service\n");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
textView.setText(tvTxt
+ "Network location temporarily unavailable\n");
break;
}
}
#Override
public void onProviderEnabled(String provider) {
textView.setText(textView.getText().toString()
+ "Network Provider Enabled\n");
}
#Override
public void onProviderDisabled(String provider) {
textView.setText(textView.getText().toString()
+ "Network Provider Disabled\n");
}
#Override
public void onLocationChanged(Location location) {
textView.setText(textView.getText().toString()
+ "New network location: "
+ String.format("%9.6f", location.getLatitude()) + ", "
+ String.format("%9.6f", location.getLongitude()) + "\n");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.textview);
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 5000, 0,
networkLocationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, gpsLocationListener);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(networkLocationListener);
locationManager.removeUpdates(gpsLocationListener);
}
}

Related

requestLocationUpdates never called

I need my Actual position in GPS just once.
In this code, onLocationChanged is never called, I don't understand why.
As I call it:
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
It should run every 0 sec and every 0 meters.
How can I change the code so that it works?
public class MapActivity extends FragmentActivity implements
LocationListener {
private final String TAG = getClass().getSimpleName();
private GoogleMap mMap;
private Location loc;
private Context ctx;
private radius;
LocationManager mLocationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
ctx = MapActivity.this;
radius = getRadius();
mMap = initMap();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
loc = location;
Log.v("Location Changed", location.getLatitude() + " and "
+ location.getLongitude());
mLocationManager.removeUpdates(this);
myPlaces = new GetPlaces(ctx, GAS_STATION, mMap, loc, radius);
myPlaces.execute();
Log.e(TAG, "location : " + loc);
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
EDIT : I moved the call to loc :
myPlaces = new GetPlaces(ctx, GAS_STATION, mMap, loc, radius);
myPlaces.execute();
Log.e(TAG, "location : " + loc);
inside the onLocationChange. This way, I don't get nullpointerException anymore, but I can wait more than 20 sec to get location. It is not so good... If anybody have an idea of how to get the fix quickly!
What I did is add 2 listener, not only gps, but also network before onCreate :
Found the code here : Location Manager's requestLocationUpdates called only once
private final LocationListener gpsLocationListener =new LocationListener(){
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
final String tvTxt = textView.getText().toString();
switch (status) {
case LocationProvider.AVAILABLE:
textView.setText(tvTxt + "GPS available again\n");
break;
case LocationProvider.OUT_OF_SERVICE:
textView.setText(tvTxt + "GPS out of service\n");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
textView.setText(tvTxt + "GPS temporarily unavailable\n");
break;
}
}
#Override
public void onProviderEnabled(String provider) {
textView.setText(textView.getText().toString()
+ "GPS Provider Enabled\n");
}
#Override
public void onProviderDisabled(String provider) {
textView.setText(textView.getText().toString()
+ "GPS Provider Disabled\n");
}
#Override
public void onLocationChanged(Location location) {
locationManager.removeUpdates(networkLocationListener);
textView.setText(textView.getText().toString()
+ "New GPS location: "
+ String.format("%9.6f", location.getLatitude()) + ", "
+ String.format("%9.6f", location.getLongitude()) + "\n");
}
};
private final LocationListener networkLocationListener =
new LocationListener(){
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
final String tvTxt = textView.getText().toString();
switch (status) {
case LocationProvider.AVAILABLE:
textView.setText(tvTxt + "Network location available again\n");
break;
case LocationProvider.OUT_OF_SERVICE:
textView.setText(tvTxt + "Network location out of service\n");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
textView.setText(tvTxt
+ "Network location temporarily unavailable\n");
break;
}
}
#Override
public void onProviderEnabled(String provider) {
textView.setText(textView.getText().toString()
+ "Network Provider Enabled\n");
}
#Override
public void onProviderDisabled(String provider) {
textView.setText(textView.getText().toString()
+ "Network Provider Disabled\n");
}
#Override
public void onLocationChanged(Location location) {
textView.setText(textView.getText().toString()
+ "New network location: "
+ String.format("%9.6f", location.getLatitude()) + ", "
+ String.format("%9.6f", location.getLongitude()) + "\n");
}
};
and activate them in CallBack methods :
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
networkLocationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, gpsLocationListener);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(networkLocationListener);
locationManager.removeUpdates(gpsLocationListener);
}
And then it worked well! I think just GPS is not enough, because fix can last a lot to come !

GPS not working when activity resumed

I need to calculate the current latiude and longitude of the user before he logs in. I have tested my code in my mobile device but it does not seem to work. Here is my code :
LocationManager mlocManager=null;
LocationListener mlocListener=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
}
#Override protected void onResume() {
super.onResume();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, mlocListener);
}
#Override protected void onPause() {
super.onPause();
mlocManager.removeUpdates(mlocListener); //<8>
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
Toast.makeText(getApplicationContext(),"In onchange", Toast.LENGTH_SHORT).show();
if(loc!=null){
latitude=loc.getLatitude();
longitude=loc.getLongitude();
if(loc.getLatitude()!=0.0 || loc.getLongitude()!=0.0){
Toast.makeText(getApplicationContext(),"Location not null", Toast.LENGTH_SHORT).show();
SharedPreferences prefsSaveLatLong = context.getSharedPreferences("prefsSaveLatLong",Context.MODE_PRIVATE);
SharedPreferences.Editor e = prefsSaveLatLong.edit();
e.remove("LAT");
e.remove("LONG");
e.putString("LAT",Double.toString(loc.getLatitude()));
e.putString("LONG",Double.toString(loc.getLongitude()));
e.commit();
String Text = "My current location is: " + "Latitude = " + loc.getLatitude() + "Longitude = " + loc.getLongitude();
Toast.makeText(getApplicationContext(),Text+" "+latitude+" "+longitude, Toast.LENGTH_SHORT).show();
}else{
SharedPreferences prefsSaveLatLong = context.getSharedPreferences("prefsSaveLatLong",Context.MODE_PRIVATE);
if(prefsSaveLatLong.contains("LAT") && prefsSaveLatLong.contains("LONG")){
SharedPreferences.Editor e1 = prefsSaveLatLong.edit();
e1.remove("LAT");
e1.remove("LONG");
e1.commit();
}
}
// set latitude longitude to label
setLatLongLabel();
}else{
latLongLabel.setTextColor(Color.parseColor("#FF0000"));
latLongLabel.setText("Latitude-Longitude not available");
SharedPreferences prefsSaveLatLong = context.getSharedPreferences("prefsSaveLatLong",Context.MODE_PRIVATE);
if(prefsSaveLatLong.contains("LAT") && prefsSaveLatLong.contains("LONG")){
SharedPreferences.Editor e1 = prefsSaveLatLong.edit();
e1.remove("LAT");
e1.remove("LONG");
e1.commit();
}
}
}
#Override
public void onProviderDisabled(String provider)
{
gpsEnabled=false;
if(!gpsEnabled){
Toast.makeText( getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT ).show();
showSettingsAlert();
}
}
#Override
public void onProviderEnabled(String provider)
{
gpsEnabled=true;
Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
if(status==0){
Toast.makeText(getApplicationContext(),"OUT_OF_SERVICE",Toast.LENGTH_SHORT).show();
SharedPreferences prefsSaveLatLong = context.getSharedPreferences("prefsSaveLatLong",Context.MODE_PRIVATE);
if(prefsSaveLatLong.contains("LAT") && prefsSaveLatLong.contains("LONG")){
SharedPreferences.Editor e1 = prefsSaveLatLong.edit();
e1.remove("LAT");
e1.remove("LONG");
e1.commit();
}
}
else if(status==1){
Toast.makeText(getApplicationContext(),"TEMPORARILY_UNAVAILABLE",Toast.LENGTH_SHORT).show();
}else if(status==2){
Toast.makeText(getApplicationContext(),"AVAILABLE",Toast.LENGTH_SHORT).show();
}
}
}/* End of Class MyLocationListener */enter code here
`
Try some thing like this
public class ShowLocationActivity 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.");
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) {
// TODO Auto-generated method stub
}
#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();
}
}
See this tutorial

Asynctask implements LocationListener : onLocationChanged never called

I make a simple code who allow an user to get his current GPS position when he push some button.
So, i create a MainActivity and an Asynctask class, the Asynctask implements LocationListener but the override onLocationChanged is never call ! (no trace in LogCat..)
Then, I get gps data but he never change when I push the button :/
And if I leave the application, if I force the processus to exit in parameter option Android and I launch again my apps, the gps data keep same. I don't understand that..and why the override method is never called.
Here my only file :
public class MainActivity extends Activity {
public static Context context;
public Button push = null;
public getGPS tache_getGPS = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplication().getApplicationContext();
push = (Button) findViewById(R.id.button);
push.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("T: onClick", "debut");
tache_getGPS = new getGPS();
tache_getGPS.execute();
Log.i("T: onClick", "fin");
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
class getGPS extends AsyncTask<Void, Integer, Location> implements
LocationListener {
final long REFRESH = 5 * 1000;
private Location location;
private LocationManager lm;
protected void onPreExecute() {
Log.i("T: onPreExcute", "debut");
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
// Configure location manager - I'm using just the network provider in
// this example
lm = (LocationManager) MainActivity.context
.getSystemService(Context.LOCATION_SERVICE);
String best = lm.getBestProvider(crit, false);
Log.i("T: onPreExecute", "best : " + best);
lm.requestLocationUpdates(best, 0, 1, this);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// nearProgress.setVisibility(View.VISIBLE);
Log.i("T: onPreExcute", "fin");
}
protected Location doInBackground(Void... params) {
Log.i("T: doInBackground", "debut");
// Try to use the last known position
Location lastLocation = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
/*
// If it's too old, get a new one by location manager
if (System.currentTimeMillis() - lastLocation.getTime() > REFRESH) {
while (location == null)
try {
Thread.sleep(100);
} catch (Exception ex) {
}
return location;
}
*/
Log.i("T: doInBackground", "fin");
return lastLocation;
}
protected void onPostExecute(Location location) {
Log.i("T: onPostExecute", "debut");
// nearProgress.setVisibility(View.GONE);
lm = (LocationManager) MainActivity.context
.getSystemService(Context.LOCATION_SERVICE);
lm.removeUpdates(this);
Log.i("T: onPostExecute",
"Altitude : " + String.valueOf(location.getAltitude()));
Log.i("T: onPostExecute",
"Longitude : " + String.valueOf(location.getLongitude()));
Log.i("T: onPostExecute",
"Latitude : " + String.valueOf(location.getLatitude()));
Log.i("T: onPostExecute",
"Precision(mètre) : " + String.valueOf(location.getAccuracy()));
Log.i("T: onPostExecute", "fin");
Toast.makeText(
MainActivity.context,
"Altitude : " + String.valueOf(location.getAltitude()) + "\n"
+ "Longitude : "
+ String.valueOf(location.getLongitude()) + "\n"
+ "Latitude : "
+ String.valueOf(location.getLatitude()) + "\n"
+ "Precision(mètre) : "
+ String.valueOf(location.getAccuracy()),
Toast.LENGTH_SHORT).show();
return;
}
#Override
public void onLocationChanged(Location newLocation) {
Log.i("T: onLocationChanged", "debut");
location = newLocation;
Log.i("T: onLocationChanged", "fin");
}
#Override
public void onProviderDisabled(String provider) {
Log.i("T: onProviderDisabled", provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i("T: onProviderEnabled", provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("T: onStatusChanged", "provider : " + provider);
Log.i("T: onStatusChanged", "status : " + status);
Log.i("T: onStatusChanged", "extras : " + extras.toString());
}
}
Thanks for help, and sorry for my poor english writing x)
NEW CODE (after advises =) ), without Asinctask
public class MainActivity extends Activity implements LocationListener{
public static Context context;
public Button push = null;
public getGPS tache_getGPS = null;
private Location location;
private LocationManager lm;
final long REFRESH = 5 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplication().getApplicationContext();
push = (Button) findViewById(R.id.button);
push.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("T: onClick", "debut");
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location lastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (System.currentTimeMillis() - lastLocation.getTime() > REFRESH) {
while (location == null)
try { Thread.sleep(100); } catch (Exception ex) { }
Log.i("FINAL : location", location.toString());
Toast.makeText(MainActivity.context, "location : "+location.toString(), Toast.LENGTH_SHORT).show();
return;
}
Log.i("FINAL : lastlocation", lastLocation.toString());
Toast.makeText(MainActivity.context, "lastLocation : "+lastLocation.toString(), Toast.LENGTH_SHORT).show();
Log.i("T: onClick", "fin");
}
});
}
#Override
protected void onResume(){
super.onResume();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
lm = (LocationManager) MainActivity.context.getSystemService(Context.LOCATION_SERVICE);
String best = lm.getBestProvider(crit, false);
Log.i("T: onPreExecute", "best : " + best);
lm.requestLocationUpdates(best, 1, 1, this);
}
#Override
protected void onPause(){
super.onPause();
lm.removeUpdates(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location newLocation) {
Toast.makeText(context, "onLocationChanged", Toast.LENGTH_SHORT).show();
Log.i("T: onLocationChanged", "debut");
location = newLocation;
Log.i("T: onLocationChanged", "fin");
}
#Override
public void onProviderDisabled(String provider) {
Log.i("T: onProviderDisabled", provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i("T: onProviderEnabled", provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("T: onStatusChanged", "provider : " + provider);
Log.i("T: onStatusChanged", "status : " + status);
Log.i("T: onStatusChanged", "extras : " + extras.toString());
}
}
In requestLocationUpdates you specified 1 as the minDistance (minDistance is the minimum distance interval for notifications, in meters). Try to set it to 0.

GPS doesn't search on my Android

I'm new on android programation and I have a problem with my aplication.
My Gps just doesn't search for location, or anything else.
And yes, my GPS is tunned on.
The manifest cointains the permitions:
ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
Could somebody help me?
public class LocationTest extends Activity implements
LocationListener {
private static final String[] A = { "invalid", "n/a", "fine", "coarse" };
private static final String[] P = { "invalid", "n/a", "low", "medium",
"high" };
private static final String[] S = { "out of service",
"temporarily unavailable", "available" };
private LocationManager mgr;
private TextView output;
private String best;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
output = (TextView) findViewById(R.id.output);
log("Location providers:");
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
log("\nBest provider is: " + best);
log("\nLocations (starting with last known):");
if (best != null) {
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
}
}
#Override
protected void onResume() {
super.onResume();
// Start updates (doc recommends delay >= 60000 ms)
if (best != null) {
mgr.requestLocationUpdates(best, 15000, 1, this);
}
}
#Override
protected void onPause() {
super.onPause();
// Stop updates to save power while app paused
mgr.removeUpdates(this);
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
log("\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider) {
log("\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
log("\nProvider status changed: " + provider + ", status="
+ S[status] + ", extras=" + extras);
}
/** Write a string to the output window */
private void log(String string) {
output.append(string + "\n");
}
/** Write information from all location providers */
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String provider : providers) {
dumpProvider(provider);
}
}
/** Write information from a single location provider */
private void dumpProvider(String provider) {
LocationProvider info = mgr.getProvider(provider);
StringBuilder builder = new StringBuilder();
builder.append("LocationProvider[")
.append("name=")
.append(info.getName())
.append(",enabled=")
.append(mgr.isProviderEnabled(provider))
.append(",getAccuracy=")
.append(A[info.getAccuracy() + 1])
.append(",getPowerRequirement=")
.append(P[info.getPowerRequirement() + 1])
.append(",hasMonetaryCost=")
.append(info.hasMonetaryCost())
.append(",requiresCell=")
.append(info.requiresCell())
.append(",requiresNetwork=")
.append(info.requiresNetwork())
.append(",requiresSatellite=")
.append(info.requiresSatellite())
.append(",supportsAltitude=")
.append(info.supportsAltitude())
.append(",supportsBearing=")
.append(info.supportsBearing())
.append(",supportsSpeed=")
.append(info.supportsSpeed())
.append("]");
log(builder.toString());
}
/** Describe the given location, which might be null */
private void dumpLocation(Location location) {
if (location == null)
log("\nLocation[unknown]");
else
log("\n" + location.toString());
}
}
I normally don't do this, but I almost have to go.
This is the code I use, it works. (just put this in a new project).
I didn't clean it, because I ripped it from my other project, but it does work, when you make a new project and just copy/paste this.:
import java.util.Timer;
import java.util.TimerTask;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class MainActivity extends Activity {
Timer timer1;
LocationManager lm;
boolean gps_loc = false;
boolean gps_enabled=false;
boolean network_enabled=false;
double lat;
double lng;
String gps_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
lat = location.getLatitude();
lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
gps_location = sLat + " " + sLng;
Toast.makeText(getBaseContext(), "We got gps location!",
Toast.LENGTH_LONG).show();
System.out.println("We got gps");
System.out.println("lat = "+lat);
System.out.println("lng = "+lng);
}
} catch (Exception e) {
}
}
};
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 35000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
Also add this in manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
No time to explain now, maybe tomorrow if you still need it.
It prints the latitude and longitude in your logcat.

Cannot find current location using GPS

I have tried the below program. It is working in eclipse -> if u give lattitude and longitude value through ddms means it displayed in emulator as current position....
but its not detecting current position in android phone.
private class mylocationlistener implements LocationListener {
public void onLocationChanged(Location location) {
Date today = new Date();
Timestamp currentTimeStamp = new Timestamp(today.getTime());
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPS){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
String str = "\n CurrentLocation: "+
"\n Latitude: "+ location.getLatitude() +
"\n Longitude: " + location.getLongitude() +
"\n Accuracy: " + location.getAccuracy() +
"\n CurrentTimeStamp "+ currentTimeStamp;
Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
tv.append(str);
}
else
{
String s1="GPS activation in process";
Toast.makeText(MainActivity.this,s1,Toast.LENGTH_SHORT).show();
/*alert.setTitle("gps");
alert.setMessage("GPS activation in progress,\n Please click after few second.");
alert.setPositiveButton("OK", null);
alert.show();*/
}
}
else
{
String s2="Enable Gps";
Toast.makeText(MainActivity.this,s2,Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
I made one service for that. It is easy for get Longitude / Latitude using it.
Copy/paste this class in your project.
package com.sample;
import com.sample.globalconstant;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyServiceGPS extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location.getLatitude() +"....."+ location.getLongitude());
globalconstant.lat = location.getLatitude();
globalconstant.lon = location.getLongitude();
Toast.makeText(getApplicationContext(), location.getLatitude() +"....."+ location.getLongitude(), 1000).show();
mLastLocation.set(location);
}
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
Copy this code in your Activity when you want to start:
startService(new Intent(this,MyServiceGPS.class));
Create one class globalconstant:
public class globalconstant { public static double lat, lon; }
when you want to current latitude and longitude in your project only write this globalconstant.lat ,globalconstant.lon
Add uses-permission in Manifest
If you want to overlay of your current location then it is better to use default method instead of custom overlay..
Here is default overlay method of current location.
MyLocationOverlay mMyLocationOverlay = new MyLocationOverlay(getApplicationContext(),
Your_MapView);
mMyLocationOverlay.enableMyLocation();
mMyLocationOverlay.onProviderEnabled(LocationManager.NETWORK_PROVIDER);
mapOverlays = map_view.getOverlays();
you can also use GPS
mMyLocationOverlay.onProviderEnabled(LocationManager.GPS_PROVIDER);
you can use this Example for Finding Location Periodically
Is it possible that your android phone is not getting a GPS signal? locationManager.getLastKnownLocation will return null if the GPS has not had time to get a fix yet. Android does not provide a 'give me the location now' method. When the GPS has got a fix, the onLocationChanged() will run. If it is fine with emulator, then there is some problem with the device. Checkout my question Not able to get Location by GPS : Android I had similar problem. What happened with me was that I was receiving location in google maps by network provider. Are you sure you are receiving it through GPS?

Categories

Resources