DummyLocationProvider issue - android

I'm trying to get the latitude and longitude and below is class which does that...
But i get android runtime exception at
Location l = locMgr.getLastKnownLocation(bestProvider);
and at longt = Double.toString(loc.getLongitude());
Also provider is always shown as DummyLocationProvider even on the phone
public class Util implements LocationListener {
public static LocationManager locMgr;
private static List<String> providers;
private static String bestProvider;
private Context context;
public static String lat;
public static String longt;
public Util(Context context) {
this.context = context;
if(locMgr == null) //Get LocationManager
locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void getLocations() {
//List All providers
providers = locMgr.getAllProviders();
//Get criteria
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get best provider
bestProvider = locMgr.getBestProvider(criteria, false);
printProvider(bestProvider);
//Get Last known location
Location l = locMgr.getLastKnownLocation(bestProvider);
if(l==null)
System.out.println("im null");
printLocation(l);
}
private void printLocation(Location loc) {
if(loc == null) { //means there is no recent location
getNewLocation();
}else
lat = Double.toString(loc.getLatitude());
longt = Double.toString(loc.getLongitude());
System.out.println("cached " + lat + " " + longt);
}
private void printProvider(String provider) {
System.out.println(provider);
LocationProvider info = locMgr.getProvider(provider);
System.out.println("provider= " + info.toString() + "\n\n");
}
private boolean getNewLocation() {
if(locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { //This is executed since it can get locations faster than gps (is executed only if use wireless networks for locations is selected)
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
return true;
}else if(locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) { //This is exceuted if n/w locations is turned off & gps is turned on
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
return true;
}else { //executed when gps & location by network is turned off..
return false;
}
}

Please modify your code, it may help you..
Location l = context.locMgr.getLastKnownLocation(bestProvider);

Related

get current Location with GPS

I want to get my current latitude and longitutude each 30 second but I can get same coordinates in each 30 second its doesn't change I use Gps services class it is below.How can I change location when I moved to device.
public class GPSService extends Service implements LocationListener {
// saving the context for later use
private final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;
// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;
// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;
// Declaring a Location Manager
protected LocationManager mLocationManager;
public GPSService(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
}
/**
* Returs the Location
*
* #return Location or null if no location is found
*/
public Location getLocation() {
try {
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If we are reaching this part, it means GPS was not able to fetch
// any location
// Getting network status
isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If reaching here means, we were not able to get location neither
// from GPS not Network,
if (!isGPSEnabled) {
// so asking user to open GPS
askUserToOpenGPS();
}
} catch (Exception e) {
e.printStackTrace();
}
// if reaching here means, location was not available, so setting the
// flag as false
isLocationAvailable = false;
return null;
}
/**
* Gives you complete address of the location
*
* #return complete address in String
*/
public String getLocationAddress() {
if (isLocationAvailable) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
return ("IO Exception trying to get address:" + e1);
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "
+ Double.toString(mLatitude) + " , "
+ Double.toString(mLongitude)
+ " passed to address service";
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/
String addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
}
} else {
return "Location Not available";
}
}
/**
* get latitude
*
* #return latitude in double
*/
public double getLatitude() {
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
/**
* get longitude
*
* #return longitude in double
*/
public double getLongitude() {
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
}
return mLongitude;
}
/**
* close GPS to save battery
*/
public void closeGPS() {
if (mLocationManager != null) {
mLocationManager.removeUpdates(GPSService.this);
}
}
/**
* show settings to open GPS
*/
public void askUserToOpenGPS() {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use use location services?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
/**
* Updating the location when location changes
*/
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
and I call getLocation method for Myclass
double latitudem2, longitudem2;
String cnvrt_latitude2,cnvrt_longitude2;
if (mGPSService2.isLocationAvailable == false) {
cnvrt_latitude2 = "0";
cnvrt_longitude2 = "0";
// Or you can continue without getting the location, remove the return; above and uncomment the line given below
// address = "Location not available";
} else {
mGPSService2.getLocation();
// Getting current location co-ordinates
latitudem2 = mGPSService2.getLatitude();
longitudem2 = mGPSService2.getLongitude();
//Toast.makeText(getApplicationContext(), "Latitude:" + latitudem + " | Longitude: " + longitudem, Toast.LENGTH_LONG).show();
cnvrt_latitude2 = String.valueOf(latitudem2);
cnvrt_longitude2 = String.valueOf(longitudem2);
}
I used a different way. I think you should use Google play.
dependencies {
..
compile 'com.google.android.gms:play-services:8.4.0'
..
}
and in your activity:
private void initGoogleClient() {
googleClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
and then register your app:
LocationRequest req = new LocationRequest();
req.setInterval(60 * 60 * 1000);
req.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(googleClient, req, this);
You can change the priority according to your requirements.
Don't forget to implement the listeners in your Activity
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
LocationListener {
...
}
I made something similar to know UV index according to the current position. You can give a look at my post.

Longitude and Latiude null in android

I have a GPSTracker file but in the android M iam geting a zero on the locations... i ask for your help to solve this problem...see the code below
Fragment with the location and a webview to google maps
public class ComoChegar extends Fragment {
EmpresaID item;
public ComoChegar() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View tela = inflater.inflate(R.layout.fragment_como_chegar, container, false);
Bundle id = getActivity().getIntent().getExtras();
String Filial = id.getString("filial");
if (isOnline()) {
item = new EmpresaID(Filial);
Autenticado(item);
}
else
{
android.app.AlertDialog.Builder alerta = new android.app.AlertDialog.Builder(getActivity());
alerta.setMessage("Você está sem Acesso a Internet por favor verifique suas configurações, ative o wi-fi ou seus dados móveis");
alerta.setPositiveButton("OK", null);
alerta.show();
}
return tela;
}
public void Autenticado(EmpresaID id)
{
ServerRequests server = new ServerRequests(getActivity());
server.getEmpresa(id, new GetEmpresaID() {
#Override
public void done(EmpresaID empresa) {
if(empresa == null) {
Erro();
}
else {
GPSTracker gps = new GPSTracker(getActivity());
List<Address> addresses;
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Geocoder geocoder;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
if(latitude == 0 && longitude == 0)
{
gps.showSettingsAlert();
}
else {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
String saida = "" + address + "," + city + "-" + postalCode;
String chegada = "" + empresa.endereco + " " + empresa.numero + "," + empresa.bairro + "-" + empresa.cidade;
WebView mapa = (WebView) getActivity().findViewById(R.id.mapa);
mapa.setWebViewClient(new WebViewClient());
mapa.getSettings().setJavaScriptEnabled(true);
String ida = saida.replace(" ", "+");
String trem = chegada.replace(" ", "+");
String Url = "https://www.google.com/maps/dir/" + latitude + "," + longitude + "/" + trem + "";
mapa.loadUrl(Url);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void Erro() {
android.support.v7.app.AlertDialog.Builder alerta = new android.support.v7.app.AlertDialog.Builder(getActivity());
alerta.setMessage("Erro ao Carregar dados do servidor");
alerta.setPositiveButton("OK", null);
alerta.show();
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
}
the GPSTracker class
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("Erro");
// Setting Dialog Message
alertDialog.setMessage("GPS não está ligado. Gostaria de Checar nas Configurações?");
// On pressing Settings button
alertDialog.setPositiveButton("Configurações", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Since your LocationListener tries to get location using only Network not GPS, with this code snippet: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
probably you are getting latitude and longitude values but with a delay. I had the same problem then I begin to use new/latest Location service API and use:
GoogleApiClient.
First you need to implement
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
from you activity that want to fetch the location data.
Define
private GoogleApiClient mGoogleApiClient;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
If you haven't add
<uses-permission `android:name="android.permission.ACCESS_FINE_LOCATION"/>`
to the manifest file, add that.
For further documentation : https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient

Getting current location in Android

I know it is a common question and has been answered a number of times... But I am looking for an answer to a specific problem.
I have written a method which is required to return current lat/long as string. The code goes like this:
public class LibraryProvider {
public String basicMethod(String string) {
String text = string;
LocationManager locationManager;
String provider;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
text = "Provider " + provider + " has been selected.";
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
text = text + "\n" + "lat: " + String.valueOf(lat);
text = text + "\n" + "lng: " + String.valueOf(lng);
} else {
text = "Location not available";
}
return text;
}
}
However, the android studio is not allowing this.get System Service:
cannot resolve Method getSystemService(java.lang.String)
I am new to android and not clear about context and intents... I think the problem has something to do with it.
(edited)
the code i was using to load the above class is as under
private final class ServiceHandler extends android.os.Handler {
public ServiceHandler(Looper looper){
super(looper);
}
public void handleMessage(Message msg){
dynamicClassLoader();
}
String text;
private void dynamicClassLoader(){
final String apkFile =Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/apkFile.apk";
String className = "com.va.android.level2.lib.LibraryProvider";
final File optimisedDexOutputPath = getDir("outdex", 0);
DexClassLoader classLoader = new DexClassLoader(apkFile,optimisedDexOutputPath.getAbsolutePath(),null,getClassLoader());
try{
Class loadedClass = classLoader.loadClass(className);
// LibraryInterface lib = (LibraryInterface) loadedClass.newInstance();
// lib.basicMethod("hello");
Object obj =(Object)loadedClass.newInstance();
Method method = loadedClass.getMethod("basicMethod", String.class);
text = (String) method.invoke(obj,"added method");
showOutput(text);
} catch (Exception e){
e.printStackTrace();
}
}
private void showOutput(final String str){
mServiceHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyService.this,str, Toast.LENGTH_LONG).show();
}
});
}
}
earlier it was working, but now it is raising some exception at loadedClass.newInstance(); .....i think i need to pass the context ...but how??
Try get Activity Context reference in custom class constructor and use it ;
public class LibraryProvider {
private Context context;
public LibraryProvider(Context context){
this.context=context;
}
}
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
You need a Context to call getSystemService(...).
Actually you are calling it from "this" that is not a class that has a Context.
try this
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.d("DEBUG",location.toString());
double lat = location.getLatitude();
double lon = location.getLongitude();
}
};
try this
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
see this link on how to get current location in Android

Location tracking in background while onChanging of the location in Android

I am developing android application using the Location. I am able to get the current location using following code.
public void GetLocation()
{
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
private LocationManager mLocationManager;
private String mProvider;
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGPSEnabled && isNetworkEnabled)
{
mProvider = mLocationManager.getBestProvider(criteria, false);
Location location = mLocationManager.getLastKnownLocation(mProvider);
Sring mLatitude=String.valueOf(arg.getLatitude());
String mLongitude=String.valueOf(arg.getLongitude());
}
}
I need to update the location of the user in background, once the location is changed not frequently. How can I achieve this?
public class CurrentLatLng implements LocationListener {
public static final int GPS_NOT_ENABLED = -1;
public static final int VALID = 1;
LocationManager manager;
Context context;
public CurrentLatLng(Context context) {
this.context = context;
}
public void getCurrentLatLng() {
//Check if GPS is enabled
if (Commons.isGPSEnabled(context)) {
manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 10, this);
} else {
// GPS NOT ENABLED. EVEN THEN THE LOCATION WILL BE RECIEVED AS WE ARE GETTING LOCATION BY NETWORK_PROVIDER
}
}
#Override
public void onLocationChanged(Location l) {
// HERE YOU WILL GET THE LATEST LOCATION AND WILL BE UPDATING WHENEVER YOU CHANGE YOUR LOCATION.
}
}
You need to use location listener. You can listen the location in specific meters or specific time interval. Check this tutorial.
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
**MINIMUM_TIME_BETWEEN_UPDATES**,
**MINIMUM_DISTANCE_CHANGE_FOR_UPDATES**,
new MyLocationListener()
);

How to get longitude and latitude in Android

I want to find the longitude and latitude of my current location, but I keep get NULL.
double lat = loc.getLatitude(); //Cause the result is null, so can't know longitude and latitude
double lng = loc.getLongitude();
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider); //result is null!
This is the code to get the GPS status. It works fine:
public void onGpsStatusChanged(int event) { // get the GPS statue
LocationManager locationManager = (LocationManager) GpsActivity.this.getSystemService(Context.LOCATION_SERVICE);
GpsStatus status = locationManager.getGpsStatus(null);
String satelliteInfo = updateGpsStatus(event, status);
myTextView.setText(satelliteInfo);//work fine ,searched satellite:16
}
};
private String updateGpsStatus(int event, GpsStatus status) {
StringBuilder sb2 = new StringBuilder("");
if (status == null) {
sb2.append("searched satellite number" +0);
} else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
int maxSatellites = status.getMaxSatellites();
Iterator<GpsSatellite> it = status.getSatellites().iterator();
numSatelliteList.clear();
int count = 0;
while (it.hasNext() && count <= maxSatellites) {
GpsSatellite s = it.next();
numSatelliteList.add(s);
count++;
}
sb2.append("searched satellite number:" + numSatelliteList.size());
}
return sb2.toString();
}
getLastKnownLocation() only returns a recent GPS fix, if available. You need to implement a LocationListener and use LocationManager#requestLocationUpdates() to fetch a new location.
Basic implementation:
public class Example extends Activity implements LocationListener {
LocationManager mLocationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
// Do something with the recent location fix
// otherwise wait for the update below
}
else {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
}
}
// etc..
}

Categories

Resources