/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/LocationLookup.java
ViewVC logotype

Diff of /android/TrainInfo/src/dk/thoerup/traininfo/LocationLookup.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

android/TrainInfo/src/dk/thoerup/traininfo/StationLocator.java revision 241 by torben, Sun Aug 9 11:21:30 2009 UTC android/TrainInfo/src/dk/thoerup/traininfo/LocationLookup.java revision 1446 by torben, Wed May 4 20:25:15 2011 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfo;  package dk.thoerup.traininfo;
2    
 import java.util.ArrayList;  
 import java.util.List;  
   
 import org.json.JSONArray;  
 import org.json.JSONObject;  
3    
4  import android.content.Context;  import android.content.Context;
5  import android.location.Criteria;  import android.content.SharedPreferences;
6    import android.location.GpsSatellite;
7    import android.location.GpsStatus;
8  import android.location.Location;  import android.location.Location;
9  import android.location.LocationListener;  import android.location.LocationListener;
10  import android.location.LocationManager;  import android.location.LocationManager;
 import android.location.LocationProvider;  
11  import android.os.Bundle;  import android.os.Bundle;
12  import android.os.Handler;  import android.preference.PreferenceManager;
13  import android.util.Log;  import android.util.Log;
 import dk.thoerup.traininfo.util.DownloadUtil;  
14    
 public class StationLocator implements LocationListener{  
15    
16          LocationManager locManager;  public class LocationLookup implements LocationListener, GpsStatus.Listener {
17          Context cntx;          
18          Handler hndl;          public enum LookupStates {
19                    GOTLOCATION,
20                    NOPROVIDER,
21                    STARTED,
22                    IDLE
23            }
24    
25          ArrayList<StationBean> stationList = new ArrayList<StationBean>();          private LocationManager locManager;
26          List<StationBean> safeStationList = java.util.Collections.unmodifiableList(stationList);          private Context cntx;
27    
28            private Location savedLocation = null;
29            private int satCount;
30            
31            private boolean hasGps;
32                    
33          Location savedLocation = null;          private LookupStates state;
34            
35            private long startTime;
36    
37          public StationLocator(Context c, Handler h) {          public LocationLookup(Context c) {
38                    state = LookupStates.IDLE;
39                  cntx = c;                  cntx = c;
                 hndl = h;  
40          }          }
41                    
42          public List<StationBean> getStations() {          
43                  return safeStationList;          public boolean hasLocation() {
44                    return savedLocation != null;
45            }
46            
47            public Location getLocation()
48            {
49                    return savedLocation;
50            }
51            
52            public boolean hasGps() {
53                    return hasGps;
54            }
55            
56            public int getSatCount() {
57                    return satCount;
58            }
59            
60            public LookupStates getState() {
61                    return state;
62          }          }
63                    
64          public void abortLocationListener() {          
65                  locManager.removeUpdates(this);          public long elapsedTime() {
66                    long now = android.os.SystemClock.elapsedRealtime();
67                    
68                    return now - startTime;
69          }          }
70    
71          public void locateStations() {          public void locateStations() {
72                  //http://www.google.com/uds/GlocalSearch?callback=google.search.LocalSearch.RawCompletion&context=1&lstkp=0&rsz=small&hl=en&source=gsc&gss=.com&sig=fadf0e8d483d0f70bea11d5905010a16&q=Train%20station&near=56.377424%2C9.656695&key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr6OwBovxn7TDAH5Q&v=1.0&nocache=1249640467498                  
73                    state = LookupStates.STARTED;
74                    
75                    hasGps = false;
76                  locManager = (LocationManager) cntx.getSystemService(Context.LOCATION_SERVICE);                  locManager = (LocationManager) cntx.getSystemService(Context.LOCATION_SERVICE);
77                  /*//testcode                  satCount = 0;
78                  List<String> provs = locManager.getAllProviders();                  
79                  for (String p  : provs) {                  startTime = android.os.SystemClock.elapsedRealtime();
80                          Log.e("Provider", p);                  
81                  }                  boolean hasProvider = false;
82                  provs = locManager.getProviders(true);                  
83                  for (String p  : provs) {                  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
84                          Log.e("ActiveProvider", p);                  String networkPref = prefs.getString("location", "GPS"); //default value is gps
85                  }                  
86                  */                  if (networkPref.equals("GPS")) {
87                  Criteria c = new Criteria();                          if (locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
88                  c.setAccuracy(Criteria.ACCURACY_FINE);                                  locManager.addGpsStatusListener(this);
89                  String bestProv = locManager.getBestProvider(c, true);                                  locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
90                  Log.e("BestProvider", bestProv);                                  
91                                                    hasGps = true;
92                                    hasProvider = true;
93                  if (bestProv != null) {                          }
94                          savedLocation = locManager.getLastKnownLocation(bestProv);                  }
95                          locManager.requestLocationUpdates(bestProv, 0, 0, this);                  
96                  } else {                  if (locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
97                            locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
98                            hasProvider = true;                    
99                    }
100                    
101                            
102                    if (hasProvider == false) {
103                          // message that no suitable provider was found                          // message that no suitable provider was found
104                          hndl.sendEmptyMessage(TrainInfoList.NOPROVIDER);                          //hndl.sendEmptyMessage(StationList.NOPROVIDER);
105                            state = LookupStates.NOPROVIDER;
106                            
107                  }                  }
108          }          }
109          @Override          @Override
110          public void onLocationChanged(Location location) {          public void onLocationChanged(Location location) {              
111                  Log.i("Location", "Got location fix " + location.getLatitude() + ", " + location.getLongitude() + " accuracy=" + location.getAccuracy() + " provider=" +location.getProvider());                  Log.i("Location", "Got location fix " + location.getLatitude() + ", " + location.getLongitude() + " accuracy=" + location.getAccuracy() + " provider=" +location.getProvider());
112                    
113    
114                  savedLocation = new Location(location); //save a copy                  if (savedLocation == null || location.getAccuracy() < savedLocation.getAccuracy())
115                            savedLocation = new Location(location); //save a copy
116                                    
117                  if (location.getProvider().equals("gps") && location.getAccuracy() > 100) //if we have a gps provider lets wait for a more precise fix                  if (hasGps) {
118                          return;                          if (!location.getProvider().equals("gps")) {
119                                    return; // at least give the gps a chance
120                            } else if (location.getAccuracy() > 512) {
121                                    return; //if we have a gps provider lets wait for a more precise fix
122                            }
123    
124                    }
125                    stopSearch();
126                    state = LookupStates.GOTLOCATION;
127    
                 locManager.removeUpdates(this);  
                 hndl.sendEmptyMessage(TrainInfoList.GOTLOCATION);  
128          }          }
129                    
         public void findNearestStations() {  
                 findNearestStations(savedLocation);  
         }  
130                    
131          public void findNearestStations(Location location) {          public void stopSearch()
132                  //ToDo: to be nice put the api key into the request          {
133                  String urlSource = "http://www.google.com/uds/GlocalSearch?callback=google.search.LocalSearch.RawCompletion&context=1&q=Train%20station&near=" + location.getLatitude() + "%2C" + location.getLongitude() + "&v=1.0";                  if (state == LookupStates.STARTED) {
134                  //String urlSource = "http://www.google.com/uds/GlocalSearch?callback=google.search.LocalSearch.RawCompletion&context=1&q=Train%20station&near=56.2%2C9.0&v=1.0";                          state = LookupStates.IDLE;
135                            locManager.removeGpsStatusListener(this);
136                  try {                          locManager.removeUpdates(this);
                         String data = DownloadUtil.getContent(urlSource, 30000, "UTF-8");  
                         StringBuilder builder = new StringBuilder(data);  
   
                         while (builder.charAt(0) != '{')  
                                 builder.deleteCharAt(0);  
                         while (builder.charAt(builder.length()-1) != '}')  
                                 builder.deleteCharAt(builder.length()-1);  
   
                         JSONObject json = new JSONObject(builder.toString());  
                         // now have some fun with the results...  
                         JSONArray res = json.getJSONArray("results");  
   
                         Location tmpLocation = new Location("gps");  
                         stationList.clear();  
                           
                         for (int i=0; i<res.length(); i++) {  
                                 JSONObject jsonStation = res.getJSONObject(i);  
   
                                 double lat = jsonStation.getDouble("lat");  
                                 double lng = jsonStation.getDouble("lng");  
                                 String title = jsonStation.getString("title");  
                                 String addr = jsonStation.getString("streetAddress");  
                                 tmpLocation.setLatitude(lat);  
                                 tmpLocation.setLongitude(lng);  
   
                                 float distance = location.distanceTo(tmpLocation);  
   
                                 stationList.add( new StationBean(title,lat,lng,(int)distance,addr) );  
   
                                 Log.e("Location", title + " " + lat +"," + lng);  
                         }  
                         hndl.sendEmptyMessage(TrainInfoList.GOTSTATIONLIST);  
   
                 } catch (Exception e) {  
                         Log.e("Location","Location",e);  
                         hndl.sendEmptyMessage(TrainInfoList.LOOKUPSTATIONFAILED);  
137                  }                  }
                           
138          }          }
139    
140    
141          @Override          @Override
142          public void onProviderDisabled(String provider) {          public void onProviderDisabled(String provider) {
                 // TODO Auto-generated method stub  
   
143          }          }
144    
145    
146          @Override          @Override
147          public void onProviderEnabled(String provider) {          public void onProviderEnabled(String provider) {
                 // TODO Auto-generated method stub  
   
148          }          }
149    
150    
# Line 153  public class StationLocator implements L Line 153  public class StationLocator implements L
153                  // TODO Auto-generated method stub                  // TODO Auto-generated method stub
154    
155          }          }
           
         public static void injectMockLocation(Context cntx) {  
                 Location loc = new Location("gps2");  
                 loc.setLatitude(56.378084);  
                 loc.setLongitude(9.659815);  
                   
                 LocationManager lm = (LocationManager) cntx.getSystemService(Context.LOCATION_SERVICE);  
                 lm.setTestProviderEnabled("gps2", true);  
                 lm.setTestProviderLocation("gps2", loc);  
156    
157    
158            @Override //GpsStatus.Listener
159            public void onGpsStatusChanged(int event) {
160                    if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
161                            int count = 0;
162                            GpsStatus status =  locManager.getGpsStatus(null);
163                            for (GpsSatellite sat : status.getSatellites()) {
164                                    count ++;
165                            }                      
166                            
167                            satCount = count;
168                    }
169                    
170          }          }
171  }  }

Legend:
Removed from v.241  
changed lines
  Added in v.1446

  ViewVC Help
Powered by ViewVC 1.1.20